Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b47c04f77 |
No files matched your search
@@ -1,88 +0,0 @@
|
||||
---
|
||||
name: antigravity-manager
|
||||
description: Comprehensive guide to Antigravity Manager architecture, workflows, and development. Use this to understand how to work on the project.
|
||||
---
|
||||
|
||||
# Antigravity Manager Developer Guide
|
||||
|
||||
## 🏗️ Architecture Overview
|
||||
|
||||
Antigravity Manager is a hybrid Desktop Application built with Electron, React, and NestJS. It follows a modular architecture where the frontend (Renderer) communicates with the backend (Main) via type-safe IPC (ORPC).
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
User[User Interface] -->|React/Vite| Renderer[Renderer Process]
|
||||
Renderer -->|ORPC Client| IPC[IPC Layer]
|
||||
IPC -->|ORPC Router| Main[Main Process]
|
||||
Main -->|Bootstraps| Server[NestJS Server]
|
||||
Main -->|Calls| Services[Service Layer]
|
||||
Services -->|Read/Write| DB[(SQLite Database)]
|
||||
Services -->|HTTP| Cloud[Cloud APIs (Google/Anthropic)]
|
||||
```
|
||||
|
||||
### Key Technologies
|
||||
|
||||
- **Frontend**: React 19, TailwindCSS v4, TanStack Router, TanStack Query.
|
||||
- **Backend**: Electron (Main), NestJS (Core Logic), Better-SQLite3 (Data).
|
||||
- **Communication**: ORPC (Type-safe IPC wrapper around Electron IPC).
|
||||
- **Build**: Electron Forge + Vite.
|
||||
|
||||
## 📂 Directory Structure
|
||||
|
||||
- `src/main.ts`: Electron Main Process entry point.
|
||||
- `src/preload.ts`: Bridge between Main and Renderer.
|
||||
- `src/renderer.tsx`: React App entry point.
|
||||
- `src/components/`: Reusable React UI components (Radix UI based).
|
||||
- `src/ipc/`: IPC Routers and Handlers (Domain logic).
|
||||
- `router.ts`: Main ORPC router definition.
|
||||
- `account/`, `cloud/`, `database/`: Domain-specific handlers.
|
||||
- `src/server/`: NestJS application modules (proxies/gateways).
|
||||
- `src/services/`: Core business logic (framework agnostic).
|
||||
- `GoogleAPIService.ts`: Gemini/Cloud interactions.
|
||||
- `AutoSwitchService.ts`: Account rotation logic.
|
||||
- `src/routes/`: Frontend routing definitions (File-based).
|
||||
|
||||
## 🚀 Development Workflow
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- npm (Project uses `package-lock.json`)
|
||||
|
||||
### Common Commands
|
||||
|
||||
- **Start Dev Server**: `npm start`
|
||||
- **Lint Code**: `npm run lint`
|
||||
- **Unit Test**: `npm run test:unit`
|
||||
- **E2E Test**: `npm run test:e2e`
|
||||
- **Build Production**: `npm run make`
|
||||
|
||||
## 🧠 Core Concepts
|
||||
|
||||
### IPC Communication (ORPC)
|
||||
|
||||
The project uses `orpc` for type-safe communication.
|
||||
|
||||
- **Define**: Create a router in `src/ipc/router.ts` with Zod schemas.
|
||||
- **Implement**: Add logic in handlers (e.g., `src/ipc/account/handler.ts`).
|
||||
- **Call**: Use the generated client in React components.
|
||||
|
||||
### Database Access
|
||||
|
||||
Data is stored in a local SQLite file (`test.db` in dev, user data in prod).
|
||||
|
||||
- Use `Better-SQLite3` for direct access.
|
||||
- Logic should be encapsulated in `src/services` or `src/ipc`.
|
||||
|
||||
### Account Management
|
||||
|
||||
- Accounts are added via OAuth (Google/Claude).
|
||||
- `GoogleAPIService` handles token exchange and refreshing.
|
||||
- `AutoSwitchService` monitors usage and switches active accounts automatically.
|
||||
|
||||
## ⚠️ Critical Rules
|
||||
|
||||
1. **Type Safety**: strict TypeScript usage; Zod for runtime validation.
|
||||
2. **Components**: Use `src/components/ui` (Radix primitives) for consistency.
|
||||
3. **Async**: Handle all IPC/DB calls asynchronously with try/catch.
|
||||
4. **Security**: Never commit secrets. API keys are user-provided or encrypted locally.
|
||||
@@ -1,18 +1,14 @@
|
||||
---
|
||||
description: Implement an approved OpenSpec change and keep tasks in sync.
|
||||
---
|
||||
|
||||
<!-- OPENSPEC:START -->
|
||||
|
||||
**Guardrails**
|
||||
|
||||
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||
- Keep changes tightly scoped to the requested outcome.
|
||||
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
|
||||
|
||||
**Steps**
|
||||
Track these steps as TODOs and complete them one by one.
|
||||
|
||||
1. Read `changes/<id>/proposal.md`, `design.md` (if present), and `tasks.md` to confirm scope and acceptance criteria.
|
||||
2. Work through tasks sequentially, keeping edits minimal and focused on the requested change.
|
||||
3. Confirm completion before updating statuses—make sure every item in `tasks.md` is finished.
|
||||
@@ -20,6 +16,5 @@ Track these steps as TODOs and complete them one by one.
|
||||
5. Reference `openspec list` or `openspec show <item>` when additional context is required.
|
||||
|
||||
**Reference**
|
||||
|
||||
- Use `openspec show <id> --json --deltas-only` if you need additional context from the proposal while implementing.
|
||||
<!-- OPENSPEC:END -->
|
||||
@@ -1,17 +1,13 @@
|
||||
---
|
||||
description: Archive a deployed OpenSpec change and update specs.
|
||||
---
|
||||
|
||||
<!-- OPENSPEC:START -->
|
||||
|
||||
**Guardrails**
|
||||
|
||||
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||
- Keep changes tightly scoped to the requested outcome.
|
||||
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. Determine the change ID to archive:
|
||||
- If this prompt already includes a specific change ID (for example inside a `<ChangeId>` block populated by slash-command arguments), use that value after trimming whitespace.
|
||||
- If the conversation references a change loosely (for example by title or summary), run `openspec list` to surface likely IDs, share the relevant candidates, and confirm which one the user intends.
|
||||
@@ -23,7 +19,6 @@ description: Archive a deployed OpenSpec change and update specs.
|
||||
5. Validate with `openspec validate --strict` and inspect with `openspec show <id>` if anything looks off.
|
||||
|
||||
**Reference**
|
||||
|
||||
- Use `openspec list` to confirm change IDs before archiving.
|
||||
- Inspect refreshed specs with `openspec list --specs` and address any validation issues before handing off.
|
||||
<!-- OPENSPEC:END -->
|
||||
@@ -1,11 +1,8 @@
|
||||
---
|
||||
description: Scaffold a new OpenSpec change and validate strictly.
|
||||
---
|
||||
|
||||
<!-- OPENSPEC:START -->
|
||||
|
||||
**Guardrails**
|
||||
|
||||
- Favor straightforward, minimal implementations first and add complexity only when it is requested or clearly required.
|
||||
- Keep changes tightly scoped to the requested outcome.
|
||||
- Refer to `openspec/AGENTS.md` (located inside the `openspec/` directory—run `ls openspec` or `openspec update` if you don't see it) if you need additional OpenSpec conventions or clarifications.
|
||||
@@ -13,7 +10,6 @@ description: Scaffold a new OpenSpec change and validate strictly.
|
||||
- Do not write any code during the proposal stage. Only create design documents (proposal.md, tasks.md, design.md, and spec deltas). Implementation happens in the apply stage after approval.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. Review `openspec/project.md`, run `openspec list` and `openspec list --specs`, and inspect related code or docs (e.g., via `rg`/`ls`) to ground the proposal in current behaviour; note any gaps that require clarification.
|
||||
2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, and `design.md` (when needed) under `openspec/changes/<id>/`.
|
||||
3. Map the change into concrete capabilities or requirements, breaking multi-scope efforts into distinct spec deltas with clear relationships and sequencing.
|
||||
@@ -23,7 +19,6 @@ description: Scaffold a new OpenSpec change and validate strictly.
|
||||
7. Validate with `openspec validate <id> --strict` and resolve every issue before sharing the proposal.
|
||||
|
||||
**Reference**
|
||||
|
||||
- Use `openspec show <id> --json --deltas-only` or `openspec show <spec> --type spec` to inspect details when validation fails.
|
||||
- Search existing requirements with `rg -n "Requirement:|Scenario:" openspec/specs` before writing new ones.
|
||||
- Explore the codebase with `rg <keyword>`, `ls`, or direct file reads so proposals align with current implementation realities.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'npm'
|
||||
directory: '/'
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
interval: "weekly"
|
||||
@@ -1,7 +1,7 @@
|
||||
name-template: 'v$RESOLVED_VERSION'
|
||||
tag-template: 'v$RESOLVED_VERSION'
|
||||
categories:
|
||||
- title: "🚀 What's new"
|
||||
- title: '🚀 What''s new'
|
||||
labels:
|
||||
- 'feature'
|
||||
- 'feat'
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: Publish Release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -10,7 +11,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest, macos-14, ubuntu-latest]
|
||||
os: [windows-latest, macos-latest, ubuntu-latest]
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
@@ -39,8 +40,4 @@ jobs:
|
||||
- name: Publish Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
|
||||
run: npm run publish
|
||||
@@ -1,37 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- beta
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Semantic Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Required for semantic-release to analyze commits
|
||||
persist-credentials: false # We use a token in the next steps
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} # Use GH_TOKEN to trigger other workflows
|
||||
run: npx semantic-release
|
||||
@@ -102,6 +102,3 @@ out/
|
||||
|
||||
# Tanstack
|
||||
.tanstack/
|
||||
|
||||
# Sentry Config File
|
||||
.env.sentry-build-plugin
|
||||
Vendored
-7
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"editor.formatOnSave": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": "explicit"
|
||||
},
|
||||
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"]
|
||||
}
|
||||
@@ -106,6 +106,7 @@ Keep this managed block so 'openspec update' can refresh the instructions.
|
||||
- `npm run test:e2e` - 运行 Playwright 端到端测试
|
||||
- `npm run test:all` - 运行所有测试
|
||||
|
||||
|
||||
### 运行单个测试 (Running Single Tests)
|
||||
|
||||
- 单元测试: `npm run test:unit path/to/test.test.ts`
|
||||
|
||||
+6
-107
@@ -1,118 +1,17 @@
|
||||
<a name="readme-top"></a>
|
||||
|
||||
# Changelog
|
||||
|
||||
## [0.5.0](https://github.com/Draculabo/AntigravityManager/compare/v0.4.0...v0.5.0) (2026-01-30)
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
### ✨ Features
|
||||
|
||||
* **i18n:** add Russian localization ([#48](https://github.com/Draculabo/AntigravityManager/issues/48)) ([63956c9](https://github.com/Draculabo/AntigravityManager/commit/63956c9c2d60f829a998237abe6ade675fdb01ed))
|
||||
* Implement collapsible sidebar and refined status bar UI ([#45](https://github.com/Draculabo/AntigravityManager/issues/45)) ([1265d04](https://github.com/Draculabo/AntigravityManager/commit/1265d044f69e52fba7da72fde6c47a0b85c58232))
|
||||
* sentry integration ([#51](https://github.com/Draculabo/AntigravityManager/issues/51)) ([a785640](https://github.com/Draculabo/AntigravityManager/commit/a785640d7a51b65a6852383401bd7c284b716975))
|
||||
|
||||
## [0.4.0](https://github.com/Draculabo/AntigravityManager/compare/v0.3.5...v0.4.0) (2026-01-28)
|
||||
|
||||
### ✨ Features
|
||||
|
||||
* add system autostart and single-instance support ([ea51253](https://github.com/Draculabo/AntigravityManager/commit/ea51253d589abd537682344d3bdb684b8fc9a511))
|
||||
* implement smart foreground quota refresh with debounce ([dd9e84a](https://github.com/Draculabo/AntigravityManager/commit/dd9e84a0dbefad6066193b6bd468689a755a02e3))
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
* stub nestjs optional modules for packaging ([f0eb7c6](https://github.com/Draculabo/AntigravityManager/commit/f0eb7c6b619a3ea9ea203d66f5dbce731d731e3c))
|
||||
|
||||
## [0.3.5](https://github.com/Draculabo/AntigravityManager/compare/v0.3.4...v0.3.5) (2026-01-26)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- "Check Quota Now" button not refreshing UI after polling ([#42](https://github.com/Draculabo/AntigravityManager/issues/42)) ([e959ee3](https://github.com/Draculabo/AntigravityManager/commit/e959ee346e7c26a8a4c5b7deefa5bd2452153f9d))
|
||||
|
||||
### 📝 Documentation
|
||||
|
||||
- remove beta download links from README ([5a21680](https://github.com/Draculabo/AntigravityManager/commit/5a2168030eac4ddeffa1c3b002b2de48b6a11a8f))
|
||||
|
||||
## [0.3.4](https://github.com/Draculabo/AntigravityManager/compare/v0.3.3...v0.3.4) (2026-01-26)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **security:** add safeStorage fallback for production builds ([#38](https://github.com/Draculabo/AntigravityManager/issues/38)) ([#43](https://github.com/Draculabo/AntigravityManager/issues/43)) ([0208058](https://github.com/Draculabo/AntigravityManager/commit/02080588b764ed88a5831152a3a1249f1d077d29))
|
||||
|
||||
### 📝 Documentation
|
||||
|
||||
- update beta release link ([d5ee08d](https://github.com/Draculabo/AntigravityManager/commit/d5ee08d5a06a915a8b82f680b38e2f532105498c))
|
||||
|
||||
## [0.3.4-beta.1](https://github.com/Draculabo/AntigravityManager/compare/v0.3.3...v0.3.4-beta.1) (2026-01-25)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **security:** add safeStorage fallback for production builds ([#38](https://github.com/Draculabo/AntigravityManager/issues/38)) ([92dc2f6](https://github.com/Draculabo/AntigravityManager/commit/92dc2f6f2169eb1a32950694387f2333ea2de682))
|
||||
|
||||
## [0.3.3](https://github.com/Draculabo/AntigravityManager/compare/v0.3.2...v0.3.3) (2026-01-25)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- accept lowercase antigravity in process detection ([0d4e2ab](https://github.com/Draculabo/AntigravityManager/commit/0d4e2ab21f37704e09ef1a67c181c48b42df1180))
|
||||
|
||||
### 📝 Documentation
|
||||
|
||||
- add beta download link to readme ([f15bb48](https://github.com/Draculabo/AntigravityManager/commit/f15bb48fdda10fda3c2382941ee0ce51204f750a))
|
||||
- clean up changelog duplicate ([22265e1](https://github.com/Draculabo/AntigravityManager/commit/22265e153c9d394229aa48afdc5948044b74e842))
|
||||
|
||||
## [0.3.2](https://github.com/Draculabo/AntigravityManager/compare/v0.3.1...v0.3.2) (2026-01-25)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- handle keychain hint and suppress pgrep spam ([bd3d41a](https://github.com/Draculabo/AntigravityManager/commit/bd3d41aed17bafe9d684c5c421bad8b90afa19a8))
|
||||
|
||||
### 📝 Documentation
|
||||
|
||||
- add macOS self-signing workaround for Keychain issues ([01e3f8f](https://github.com/Draculabo/AntigravityManager/commit/01e3f8f8fd6dacc5eed214ed4b505d6d85f4bcff))
|
||||
|
||||
### 🔧 Continuous Integration
|
||||
|
||||
- setup semantic release configuration and github actions workflow ([d2945a6](https://github.com/Draculabo/AntigravityManager/commit/d2945a6e8a14d75f577716183cdff093443d9636))
|
||||
- trigger publish on release published event ([6a07bc0](https://github.com/Draculabo/AntigravityManager/commit/6a07bc0a10a5ad802777e007cfd7390852119b15))
|
||||
|
||||
## [0.3.1] - 2026-01-25
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fixed startup race condition causing cloud accounts verify failure ([f0718db])
|
||||
- Enabled WAL mode and force initialization on startup to resolve process resource contention ([1bce5d3])
|
||||
|
||||
## [0.3.0] - 2026-01-23
|
||||
|
||||
### New Features
|
||||
|
||||
- Verify Google OAuth code automatically after receipt
|
||||
- Add button to open logs folder
|
||||
- Add expiration warning for Google OAuth authentication
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fixed `state.vscdb` path on Linux to include `User/globalStorage` subdirectory (Fixed [#26](https://github.com/Draculabo/AntigravityManager/issues/26))
|
||||
- Improved process detection on macOS/Linux using `find-process` to reliably identify the main application and exclude helper processes (Fixed [#27](https://github.com/Draculabo/AntigravityManager/issues/27))
|
||||
- Fixed keychain access error on macOS Apple Silicon (M1/M2/M3) by adding arm64 build to CI
|
||||
|
||||
### Maintenance
|
||||
|
||||
- Add VS Code settings for auto-formatting and ESLint
|
||||
|
||||
## [0.2.2] - 2026-01-19
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fixed tray icon not appearing in production builds on Windows
|
||||
- Used `extraResource` config to properly copy assets outside of ASAR package
|
||||
- Added debug logging for tray icon path resolution
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.2.1] - 2026-01-19
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Fixed process detection to be case-insensitive on Linux/macOS (`pgrep -xi`) ([#24](https://github.com/Draculabo/AntigravityManager/pull/24)) - Thanks [@Olbrasoft](https://github.com/Olbrasoft)!
|
||||
- Fixed manager exclusion logic to prevent accidental self-termination ([#24](https://github.com/Draculabo/AntigravityManager/pull/24))
|
||||
- Fixed zombie tray icons on application restart/hot reload ([#24](https://github.com/Draculabo/AntigravityManager/pull/24))
|
||||
- Fixed process detection to be case-insensitive on Linux/macOS (`pgrep -xi`)
|
||||
- Fixed manager exclusion logic to prevent accidental self-termination
|
||||
- Fixed zombie tray icons on application restart/hot reload
|
||||
|
||||
### Maintenance
|
||||
|
||||
|
||||
@@ -280,24 +280,6 @@ Please check:
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Q: macOS shows Keychain/Credential error and OAuth cannot be saved?</b></summary>
|
||||
|
||||
This is a common macOS security behavior, usually when the app is unsigned or run directly from Downloads.
|
||||
This is a **temporary workaround** for personal use:
|
||||
|
||||
1. Move the app to `/Applications`
|
||||
2. Run the following commands in Terminal (repeat after every update)
|
||||
|
||||
```plaintext
|
||||
sudo xattr -dr com.apple.quarantine "/Applications/Antigravity Manager 2.app"
|
||||
codesign --force --deep --sign - "/Applications/Antigravity Manager 2.app"
|
||||
```
|
||||
|
||||
Reopen the app and allow Keychain access if prompted.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Q: How to report issues or suggestions?</b></summary>
|
||||
|
||||
|
||||
@@ -280,24 +280,6 @@ AntigravityManager/
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Q: macOS 上提示 Keychain/凭据管理不可用,OAuth 无法保存?</b></summary>
|
||||
|
||||
这是 macOS 安全机制导致的常见问题,通常出现在未签名的应用或从 Downloads 直接运行的场景。
|
||||
这是**临时方案**,仅适合个人设备:
|
||||
|
||||
1. 将应用移动到 `/Applications`
|
||||
2. 打开终端执行以下命令(每次更新后都需要重新执行)
|
||||
|
||||
```plaintext
|
||||
sudo xattr -dr com.apple.quarantine "/Applications/Antigravity Manager 2.app"
|
||||
codesign --force --deep --sign - "/Applications/Antigravity Manager 2.app"
|
||||
```
|
||||
|
||||
重新打开应用后,Keychain 应会提示授权(可选“始终允许”)。
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Q: 如何反馈问题或建议?</b></summary>
|
||||
|
||||
|
||||
@@ -25,14 +25,4 @@ export default defineConfig([
|
||||
reactHooks.configs.flat.recommended,
|
||||
eslintPluginPrettierRecommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
rules: {
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
'@typescript-eslint/no-empty-object-type': 'off',
|
||||
'@typescript-eslint/ban-ts-comment': 'off',
|
||||
'no-empty-pattern': 'off',
|
||||
'prefer-const': 'off',
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -22,7 +22,6 @@ const config: ForgeConfig = {
|
||||
name: 'Antigravity Manager',
|
||||
executableName: 'antigravity-manager',
|
||||
icon: 'images/icon', // Electron Forge automatically adds .icns/.ico
|
||||
extraResource: ['src/assets'], // Copy assets folder to resources/assets
|
||||
},
|
||||
rebuildConfig: {},
|
||||
hooks: {
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ src/
|
||||
**数据库位置:**
|
||||
* macOS: `~/Library/Application Support/Antigravity/User/globalStorage/state.vscdb`
|
||||
* Windows: `%APPDATA%/Antigravity/User/globalStorage/state.vscdb`
|
||||
* Linux: `~/.config/Antigravity/User/globalStorage/state.vscdb`
|
||||
* Linux: `~/.config/Antigravity/state.vscdb`
|
||||
|
||||
**关键数据库键:**
|
||||
* `antigravityAuthStatus`: 认证状态和用户信息。
|
||||
|
||||
Generated
+248
-7621
File diff suppressed because it is too large.
Load diff
+2
-13
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "antigravity-manager",
|
||||
"productName": "Antigravity Manager",
|
||||
"version": "0.5.0",
|
||||
"version": "0.2.1",
|
||||
"description": "Antigravity Manager - Electron App",
|
||||
"main": ".vite/build/main.js",
|
||||
"private": true,
|
||||
@@ -38,10 +38,6 @@
|
||||
"@eslint/compat": "^1.4.1",
|
||||
"@eslint/js": "^9.39.0",
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@semantic-release/changelog": "^6.0.3",
|
||||
"@semantic-release/git": "^10.0.1",
|
||||
"@semantic-release/github": "^12.0.2",
|
||||
"@sentry/vite-plugin": "^4.8.0",
|
||||
"@swc/core": "^1.15.8",
|
||||
"@tanstack/router-plugin": "^1.135.0",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
@@ -57,7 +53,6 @@
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"babel-plugin-react-compiler": "1.0.0",
|
||||
"code-inspector-plugin": "^1.3.3",
|
||||
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||
"electron": "^37.3.1",
|
||||
"electron-devtools-installer": "^4.0.0",
|
||||
"electron-playwright-helpers": "^1.8.2",
|
||||
@@ -72,8 +67,6 @@
|
||||
"node-addon-api": "^8.3.1",
|
||||
"prettier": "^3.6.2",
|
||||
"prettier-plugin-tailwindcss": "^0.7.1",
|
||||
"semantic-release": "^25.0.2",
|
||||
"semantic-release-config-gitmoji": "^1.5.3",
|
||||
"sharp": "^0.34.5",
|
||||
"tailwindcss": "^4.1.16",
|
||||
"ts-node": "^10.9.2",
|
||||
@@ -92,6 +85,7 @@
|
||||
"@nestjs/microservices": "^11.1.11",
|
||||
"@nestjs/platform-express": "^11.1.11",
|
||||
"@nestjs/platform-fastify": "^11.1.10",
|
||||
"@nestjs/websockets": "^11.1.11",
|
||||
"@orpc/client": "^1.10.4",
|
||||
"@orpc/server": "^1.11.3",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
@@ -108,9 +102,6 @@
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"@radix-ui/react-toggle": "^1.1.9",
|
||||
"@radix-ui/react-toggle-group": "^1.1.11",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@sentry/electron": "^7.7.0",
|
||||
"@sentry/integrations": "^7.114.0",
|
||||
"@tailwindcss/vite": "^4.1.17",
|
||||
"@tanstack/react-query": "^5.90.7",
|
||||
"@tanstack/react-router": "^1.139.3",
|
||||
@@ -125,7 +116,6 @@
|
||||
"date-fns": "^4.1.0",
|
||||
"electron-squirrel-startup": "^1.0.1",
|
||||
"fastify": "^5.6.2",
|
||||
"find-process": "^2.0.0",
|
||||
"happy-dom": "^20.0.10",
|
||||
"i18next": "^25.6.3",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
@@ -142,7 +132,6 @@
|
||||
"undici": "^7.16.0",
|
||||
"update-electron-app": "^3.1.1",
|
||||
"uuid": "^13.0.0",
|
||||
"yaml": "^2.8.2",
|
||||
"zod": "^4.1.12"
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
/**
|
||||
* Semantic Release Configuration
|
||||
*
|
||||
* This configuration uses the specific release rules requested by the user,
|
||||
* but adapts the plugin configuration to work with standard Conventional Commits
|
||||
* instead of Gitmoji (since the project history doesn't use emojis).
|
||||
*/
|
||||
|
||||
const REPO_URL = 'https://github.com/Draculabo/AntigravityManager';
|
||||
const GITHUB_BASE_URL = 'https://github.com';
|
||||
const FULL_CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`;
|
||||
|
||||
const releaseRules = [
|
||||
{
|
||||
release: 'minor',
|
||||
type: 'feat',
|
||||
},
|
||||
{
|
||||
release: 'patch',
|
||||
type: 'fix',
|
||||
},
|
||||
{
|
||||
release: 'patch',
|
||||
type: 'perf',
|
||||
},
|
||||
{
|
||||
release: 'patch',
|
||||
type: 'style',
|
||||
},
|
||||
{
|
||||
release: 'patch',
|
||||
type: 'refactor',
|
||||
},
|
||||
{
|
||||
release: 'patch',
|
||||
type: 'build',
|
||||
},
|
||||
{ release: 'patch', scope: 'README', type: 'docs' },
|
||||
{ release: 'patch', scope: 'README.md', type: 'docs' },
|
||||
{ release: false, type: 'docs' },
|
||||
{
|
||||
release: false,
|
||||
type: 'test',
|
||||
},
|
||||
{
|
||||
release: false,
|
||||
type: 'ci',
|
||||
},
|
||||
{
|
||||
release: false,
|
||||
type: 'chore',
|
||||
},
|
||||
{
|
||||
release: false,
|
||||
type: 'wip',
|
||||
},
|
||||
{
|
||||
release: 'major',
|
||||
type: 'BREAKING CHANGE',
|
||||
},
|
||||
{
|
||||
release: 'major',
|
||||
scope: 'BREAKING CHANGE',
|
||||
},
|
||||
{
|
||||
release: 'major',
|
||||
subject: '*BREAKING CHANGE*',
|
||||
},
|
||||
{ release: 'patch', subject: '*force release*' },
|
||||
{ release: 'patch', subject: '*force patch*' },
|
||||
{ release: 'minor', subject: '*force minor*' },
|
||||
{ release: 'major', subject: '*force major*' },
|
||||
{ release: false, subject: '*skip release*' },
|
||||
];
|
||||
|
||||
const getGithubUsernameFromEmail = (email) => {
|
||||
if (!email) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const match = email.match(/^(?:\d+\+)?(?<username>[a-z0-9-]+)@users\.noreply\.github\.com$/i);
|
||||
|
||||
return match?.groups?.username;
|
||||
};
|
||||
|
||||
const isBotIdentity = (value) => {
|
||||
return typeof value === 'string' && /bot/i.test(value);
|
||||
};
|
||||
|
||||
const buildReleaseFooter = (commits) => {
|
||||
const mergedPullRequests = new Map();
|
||||
const contributors = new Map();
|
||||
|
||||
(commits || []).forEach((commit) => {
|
||||
const message = [commit?.message, commit?.subject, commit?.header].filter(Boolean).join('\n');
|
||||
if (message) {
|
||||
const mergeMatches = message.match(/pull request #(?<number>\d+)/gi);
|
||||
if (mergeMatches) {
|
||||
mergeMatches.forEach((match) => {
|
||||
const number = match.replace(/\D/g, '');
|
||||
if (number) {
|
||||
mergedPullRequests.set(number, {
|
||||
number,
|
||||
url: `${REPO_URL}/pull/${number}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const squashMatches = message.match(/\(#(?<number>\d+)\)/g);
|
||||
if (squashMatches) {
|
||||
squashMatches.forEach((match) => {
|
||||
const number = match.replace(/\D/g, '');
|
||||
if (number) {
|
||||
mergedPullRequests.set(number, {
|
||||
number,
|
||||
url: `${REPO_URL}/pull/${number}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const author = commit?.author || commit?.committer;
|
||||
const username = getGithubUsernameFromEmail(author?.email);
|
||||
const displayName = username ? `@${username}` : author?.name;
|
||||
|
||||
if (!displayName || isBotIdentity(displayName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (username && isBotIdentity(username)) {
|
||||
return;
|
||||
}
|
||||
|
||||
contributors.set(username || displayName, {
|
||||
name: displayName,
|
||||
url: username ? `${GITHUB_BASE_URL}/${username}` : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
const footerLines = [];
|
||||
const sortedPullRequests = Array.from(mergedPullRequests.values()).sort(
|
||||
(left, right) => Number(left.number) - Number(right.number),
|
||||
);
|
||||
if (sortedPullRequests.length > 0) {
|
||||
footerLines.push('### 🔀 Merged Pull Requests');
|
||||
sortedPullRequests.forEach((pullRequest) => {
|
||||
footerLines.push(`- [#${pullRequest.number}](${pullRequest.url})`);
|
||||
});
|
||||
footerLines.push('');
|
||||
}
|
||||
|
||||
const sortedContributors = Array.from(contributors.values()).sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
);
|
||||
if (sortedContributors.length > 0) {
|
||||
footerLines.push('### 🙌 Contributors');
|
||||
sortedContributors.forEach((contributor) => {
|
||||
if (contributor.url) {
|
||||
footerLines.push(`- [${contributor.name}](${contributor.url})`);
|
||||
return;
|
||||
}
|
||||
|
||||
footerLines.push(`- ${contributor.name}`);
|
||||
});
|
||||
footerLines.push('');
|
||||
}
|
||||
|
||||
footerLines.push(`Full Changelog: ${FULL_CHANGELOG_URL}`);
|
||||
|
||||
return footerLines.join('\n');
|
||||
};
|
||||
|
||||
const appendReleaseNotes = (notes, commits) => {
|
||||
const trimmedNotes = (notes || '').trimEnd();
|
||||
const footer = buildReleaseFooter(commits);
|
||||
|
||||
if (!footer) {
|
||||
return trimmedNotes;
|
||||
}
|
||||
|
||||
return `${trimmedNotes}\n\n${footer}`;
|
||||
};
|
||||
|
||||
const appendReleaseNotesPlugin = {
|
||||
publish: async (pluginConfig, context) => {
|
||||
if (!context?.nextRelease?.notes) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.nextRelease.notes = appendReleaseNotes(context.nextRelease.notes, context.commits);
|
||||
},
|
||||
};
|
||||
|
||||
const releaseConfig = {
|
||||
branches: ['main', { name: 'beta', prerelease: true }],
|
||||
plugins: [
|
||||
[
|
||||
'@semantic-release/commit-analyzer',
|
||||
{
|
||||
preset: 'conventionalcommits',
|
||||
releaseRules: releaseRules,
|
||||
},
|
||||
],
|
||||
[
|
||||
'@semantic-release/release-notes-generator',
|
||||
{
|
||||
preset: 'conventionalcommits',
|
||||
presetConfig: {
|
||||
types: [
|
||||
{ type: 'feat', section: '✨ Features' },
|
||||
{ type: 'fix', section: '🐛 Bug Fixes' },
|
||||
{ type: 'perf', section: '⚡ Performance Improvements' },
|
||||
{ type: 'revert', section: '⏪ Reverts' },
|
||||
{ type: 'docs', section: '📝 Documentation' },
|
||||
{ type: 'style', section: '💄 Styles' },
|
||||
{ type: 'refactor', section: '♻️ Code Refactoring' },
|
||||
{ type: 'test', section: '✅ Tests' },
|
||||
{ type: 'build', section: '👷 Build System' },
|
||||
{ type: 'ci', section: '🔧 Continuous Integration' },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
'@semantic-release/changelog',
|
||||
{
|
||||
changelogFile: 'CHANGELOG.md',
|
||||
changelogTitle: '<a name="readme-top"></a>\n\n# Changelog',
|
||||
},
|
||||
],
|
||||
'@semantic-release/npm', // Updates package.json and npm-shrinkwrap.json
|
||||
appendReleaseNotesPlugin,
|
||||
[
|
||||
'@semantic-release/github',
|
||||
{
|
||||
successComment: false,
|
||||
failComment: false,
|
||||
labels: false,
|
||||
releaseName: 'v${nextRelease.version}',
|
||||
},
|
||||
],
|
||||
[
|
||||
'@semantic-release/git',
|
||||
{
|
||||
assets: ['CHANGELOG.md', 'package.json', 'package-lock.json', 'npm-shrinkwrap.json'],
|
||||
message: 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}',
|
||||
},
|
||||
],
|
||||
],
|
||||
};
|
||||
|
||||
releaseConfig.__internal = {
|
||||
appendReleaseNotes,
|
||||
buildReleaseFooter,
|
||||
};
|
||||
|
||||
module.exports = releaseConfig;
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ipc } from '@/ipc/manager';
|
||||
|
||||
export function openLogDirectory() {
|
||||
return ipc.client.system.openLogDirectory();
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { MoreVertical, Trash2, RefreshCw } from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { enUS, zhCN, ru } from 'date-fns/locale';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
@@ -33,18 +32,18 @@ export const AccountCard: React.FC<AccountCardProps> = ({
|
||||
isSwitching,
|
||||
isDeleting,
|
||||
}) => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
const [transform, setTransform] = useState('');
|
||||
const [glarePosition, setGlarePosition] = useState({ x: 50, y: 50 });
|
||||
|
||||
const initials = account.name
|
||||
? account.name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
.slice(0, 2)
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
.slice(0, 2)
|
||||
: account.email[0].toUpperCase();
|
||||
|
||||
// 处理鼠标移动,计算 3D 旋转角度
|
||||
@@ -137,7 +136,6 @@ export const AccountCard: React.FC<AccountCardProps> = ({
|
||||
{t('account.lastUsed', {
|
||||
time: formatDistanceToNow(new Date(account.last_used), {
|
||||
addSuffix: true,
|
||||
locale: { en: enUS, 'zh-CN': zhCN, ru: ru }[i18n.language] || enUS,
|
||||
}),
|
||||
})}
|
||||
</p>
|
||||
|
||||
@@ -41,13 +41,12 @@ import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { getLocalizedErrorMessage } from '@/utils/errorMessages';
|
||||
|
||||
// ... (existing code: imports and comments)
|
||||
|
||||
export function CloudAccountList() {
|
||||
const { t } = useTranslation();
|
||||
const { data: accounts, isLoading, isError, error } = useCloudAccounts();
|
||||
const { data: accounts, isLoading, isError } = useCloudAccounts();
|
||||
const refreshMutation = useRefreshQuota();
|
||||
const deleteMutation = useDeleteCloudAccount();
|
||||
const addMutation = useAddGoogleAccount();
|
||||
@@ -63,49 +62,19 @@ export function CloudAccountList() {
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
||||
const [authCode, setAuthCode] = useState('');
|
||||
|
||||
const handleAddAccount = (codeVal?: string) => {
|
||||
const codeToUse = codeVal || authCode;
|
||||
if (!codeToUse) {
|
||||
return;
|
||||
}
|
||||
addMutation.mutate(
|
||||
{ authCode: codeToUse },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setIsAddDialogOpen(false);
|
||||
setAuthCode('');
|
||||
toast({ title: t('cloud.toast.addSuccess') });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({
|
||||
title: t('cloud.toast.addFailed.title'),
|
||||
description: getLocalizedErrorMessage(err, t),
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
// Listen for Google Auth Code
|
||||
useEffect(() => {
|
||||
if (window.electron?.onGoogleAuthCode) {
|
||||
console.log('[OAuth] Setting up auth code listener, dialog open:', isAddDialogOpen);
|
||||
const cleanup = window.electron.onGoogleAuthCode((code) => {
|
||||
console.log('[OAuth] Received auth code via IPC:', code?.substring(0, 10) + '...');
|
||||
setAuthCode(code);
|
||||
// Note: Auto-submit will be triggered by the authCode change effect below
|
||||
// Auto submit if dialog is open
|
||||
if (isAddDialogOpen) {
|
||||
handleAddAccount(code);
|
||||
}
|
||||
});
|
||||
return cleanup;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Auto-submit when authCode is set and dialog is open
|
||||
useEffect(() => {
|
||||
if (authCode && isAddDialogOpen && !addMutation.isPending) {
|
||||
console.log('[OAuth] Auto-submitting auth code');
|
||||
handleAddAccount(authCode);
|
||||
}
|
||||
}, [authCode, isAddDialogOpen]);
|
||||
}, [isAddDialogOpen]);
|
||||
|
||||
// Batch Operations State
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
@@ -134,7 +103,7 @@ export function CloudAccountList() {
|
||||
onError: (err) =>
|
||||
toast({
|
||||
title: t('cloud.toast.switchFailed'),
|
||||
description: getLocalizedErrorMessage(err, t),
|
||||
description: err.message,
|
||||
variant: 'destructive',
|
||||
}),
|
||||
},
|
||||
@@ -176,15 +145,8 @@ export function CloudAccountList() {
|
||||
};
|
||||
|
||||
const handleForcePoll = () => {
|
||||
if (forcePollMutation.isPending) return;
|
||||
forcePollMutation.mutate(undefined, {
|
||||
onSuccess: () => toast({ title: t('cloud.polling') }),
|
||||
onError: (err) =>
|
||||
toast({
|
||||
title: t('cloud.toast.pollFailed'),
|
||||
description: getLocalizedErrorMessage(err, t),
|
||||
variant: 'destructive',
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -207,13 +169,35 @@ export function CloudAccountList() {
|
||||
onError: (err) => {
|
||||
toast({
|
||||
title: t('cloud.toast.syncFailed.title'),
|
||||
description: getLocalizedErrorMessage(err, t),
|
||||
description: err.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddAccount = (codeVal?: string) => {
|
||||
const codeToUse = codeVal || authCode;
|
||||
if (!codeToUse) return;
|
||||
addMutation.mutate(
|
||||
{ authCode: codeToUse },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setIsAddDialogOpen(false);
|
||||
setAuthCode('');
|
||||
toast({ title: t('cloud.toast.addSuccess') });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({
|
||||
title: t('cloud.toast.addFailed.title'),
|
||||
description: err.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const openAuthUrl = async () => {
|
||||
try {
|
||||
await startAuthFlow();
|
||||
@@ -280,13 +264,7 @@ export function CloudAccountList() {
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
const errorMessage = getLocalizedErrorMessage(error, t);
|
||||
return (
|
||||
<div className="p-4 text-red-500">
|
||||
<div>{t('cloud.error.loadFailed')}</div>
|
||||
<div className="mt-1 text-sm text-red-400">{errorMessage}</div>
|
||||
</div>
|
||||
);
|
||||
return <div className="p-4 text-red-500">Failed to load cloud accounts.</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,15 +3,10 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { isProcessRunning, startAntigravity, closeAntigravity } from '@/actions/process';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Play, Square, Loader2, Power } from 'lucide-react';
|
||||
import { Play, Square, Loader2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
|
||||
interface StatusBarProps {
|
||||
isCollapsed?: boolean;
|
||||
}
|
||||
|
||||
export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) => {
|
||||
export const StatusBar: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -45,78 +40,26 @@ export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) =>
|
||||
|
||||
const isPending = startMutation.isPending || stopMutation.isPending;
|
||||
|
||||
// Collapsed View
|
||||
if (isCollapsed) {
|
||||
return (
|
||||
<div className="flex justify-center py-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleToggle}
|
||||
disabled={isLoading || isPending}
|
||||
className={cn(
|
||||
'h-10 w-10 rounded-lg transition-all duration-300',
|
||||
isRunning
|
||||
? 'bg-green-100/50 text-green-700 hover:bg-green-100 hover:text-green-800 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50'
|
||||
: 'bg-red-100/50 text-red-700 hover:bg-red-100 hover:text-red-800 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50',
|
||||
)}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
) : (
|
||||
<Power className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" className="flex items-center gap-2">
|
||||
<div
|
||||
className={cn('h-2 w-2 rounded-full', isRunning ? 'bg-green-500' : 'bg-red-500')}
|
||||
/>
|
||||
<p>
|
||||
{isLoading
|
||||
? t('status.checking')
|
||||
: isRunning
|
||||
? t('status.running')
|
||||
: t('status.stopped')}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Expanded View
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-between overflow-hidden rounded-lg px-3 py-2.5 text-sm font-medium ring-1 transition-colors ring-inset',
|
||||
'flex items-center justify-between px-4 py-2 text-sm font-medium transition-colors',
|
||||
isRunning
|
||||
? 'bg-green-100 text-green-900 ring-green-200 dark:bg-green-900/20 dark:text-green-100 dark:ring-green-900/50'
|
||||
: 'bg-red-100 text-red-900 ring-red-200 dark:bg-red-900/20 dark:text-red-100 dark:ring-red-900/50',
|
||||
? 'bg-green-100 text-green-900 dark:bg-green-900/30 dark:text-green-100'
|
||||
: 'bg-red-100 text-red-900 dark:bg-red-900/30 dark:text-red-100',
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-1 items-start gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{isLoading ? (
|
||||
<Loader2 className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin" />
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : isRunning ? (
|
||||
<div className="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.5)]" />
|
||||
<div className="h-3 w-3 rounded-full bg-green-500" />
|
||||
) : (
|
||||
<div className="mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.5)]" />
|
||||
<div className="h-3 w-3 rounded-full bg-red-500" />
|
||||
)}
|
||||
<div className="flex flex-col gap-1 leading-none">
|
||||
<span className="text-xs font-semibold tracking-wider uppercase opacity-80">Status</span>
|
||||
<span className="text-sm leading-tight font-medium">
|
||||
{isLoading
|
||||
? t('status.checking')
|
||||
: isRunning
|
||||
? t('status.running')
|
||||
: t('status.stopped')}
|
||||
</span>
|
||||
</div>
|
||||
<span>
|
||||
{isLoading ? t('status.checking') : isRunning ? t('status.running') : t('status.stopped')}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -124,22 +67,18 @@ export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) =>
|
||||
onClick={handleToggle}
|
||||
disabled={isLoading || isPending}
|
||||
className={cn(
|
||||
'ml-2 h-8 shrink-0 rounded-md border px-3 transition-all',
|
||||
isRunning
|
||||
? 'border-green-200 bg-green-200/50 text-green-900 hover:bg-green-200 dark:border-green-800 dark:bg-green-800/30 dark:text-green-100 dark:hover:bg-green-800/50'
|
||||
: 'border-red-200 bg-red-200/50 text-red-900 hover:bg-red-200 dark:border-red-800 dark:bg-red-800/30 dark:text-red-100 dark:hover:bg-red-800/50',
|
||||
'h-8 px-3 hover:bg-white/20',
|
||||
isRunning ? 'hover:text-green-900' : 'hover:text-red-900',
|
||||
)}
|
||||
>
|
||||
{isPending ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : isRunning ? (
|
||||
<Square className="h-3.5 w-3.5 fill-current" />
|
||||
<Square className="mr-2 h-4 w-4 fill-current" />
|
||||
) : (
|
||||
<Play className="h-3.5 w-3.5 fill-current" />
|
||||
<Play className="mr-2 h-4 w-4 fill-current" />
|
||||
)}
|
||||
<span className="ml-2 font-semibold">
|
||||
{isRunning ? t('action.stop') : t('action.start')}
|
||||
</span>
|
||||
{isRunning ? t('action.stop') : t('action.start')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider;
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root;
|
||||
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger;
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'bg-popover text-popover-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 origin-[--radix-tooltip-content-transform-origin] overflow-hidden rounded-md border px-3 py-1.5 text-sm shadow-md',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
@@ -1,12 +1,7 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ipc } from '@/ipc/manager';
|
||||
import { AppConfig } from '@/types/config';
|
||||
|
||||
const SAVE_DEBOUNCE_MS = 400;
|
||||
import { toast } from '@/components/ui/use-toast';
|
||||
|
||||
export function useAppConfig() {
|
||||
const queryClient = useQueryClient();
|
||||
@@ -25,105 +20,28 @@ export function useAppConfig() {
|
||||
const updateConfig = useMutation({
|
||||
mutationFn: async (newConfig: AppConfig) => {
|
||||
await ipc.client.config.save(newConfig);
|
||||
return newConfig;
|
||||
},
|
||||
});
|
||||
|
||||
const latestConfigRef = useRef<AppConfig | null>(null);
|
||||
const lastStableConfigRef = useRef<AppConfig | null>(null);
|
||||
const pendingResolversRef = useRef<
|
||||
Array<{ resolve: () => void; reject: (error: Error) => void }>
|
||||
>([]);
|
||||
const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
lastStableConfigRef.current = config;
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
const flushPendingSave = useCallback(async () => {
|
||||
const pendingBatch = pendingResolversRef.current.splice(0);
|
||||
const nextConfig = latestConfigRef.current;
|
||||
if (!nextConfig) {
|
||||
for (const item of pendingBatch) {
|
||||
item.resolve();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const savedConfig = await updateConfig.mutateAsync(nextConfig);
|
||||
queryClient.setQueryData(['appConfig'], savedConfig);
|
||||
lastStableConfigRef.current = savedConfig;
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['appConfig'] });
|
||||
toast({
|
||||
title: 'Settings saved',
|
||||
description: 'Your configuration has been updated.',
|
||||
});
|
||||
for (const item of pendingBatch) {
|
||||
item.resolve();
|
||||
}
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error('Failed to save settings');
|
||||
const fallback = lastStableConfigRef.current;
|
||||
if (fallback) {
|
||||
queryClient.setQueryData(['appConfig'], fallback);
|
||||
} else {
|
||||
queryClient.invalidateQueries({ queryKey: ['appConfig'] });
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
toast({
|
||||
title: 'Error saving settings',
|
||||
description: error.message,
|
||||
description: err.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
for (const item of pendingBatch) {
|
||||
item.reject(error);
|
||||
}
|
||||
}
|
||||
}, [queryClient, updateConfig]);
|
||||
|
||||
const saveConfig = useCallback(
|
||||
(newConfig: AppConfig) => {
|
||||
latestConfigRef.current = newConfig;
|
||||
queryClient.setQueryData(['appConfig'], newConfig);
|
||||
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
pendingResolversRef.current.push({ resolve, reject });
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
debounceTimerRef.current = null;
|
||||
flushPendingSave();
|
||||
}, SAVE_DEBOUNCE_MS);
|
||||
});
|
||||
},
|
||||
[flushPendingSave, queryClient],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleBeforeUnload = () => {
|
||||
if (!debounceTimerRef.current) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
debounceTimerRef.current = null;
|
||||
void flushPendingSave();
|
||||
};
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
handleBeforeUnload();
|
||||
};
|
||||
}, [flushPendingSave]);
|
||||
});
|
||||
|
||||
return {
|
||||
config,
|
||||
isLoading,
|
||||
error,
|
||||
saveConfig,
|
||||
saveConfig: updateConfig.mutateAsync,
|
||||
isSaving: updateConfig.isPending,
|
||||
};
|
||||
}
|
||||
@@ -47,12 +47,12 @@ export function useRefreshQuota() {
|
||||
return useMutation({
|
||||
mutationFn: refreshAccountQuota,
|
||||
onSuccess: (updatedAccount: CloudAccount) => {
|
||||
// Optimistically update
|
||||
// Optimistically update the list or just invalidate?
|
||||
// Invalidating is safer as sorting might change (last_used)
|
||||
queryClient.setQueryData(QUERY_KEYS.cloudAccounts, (oldData: CloudAccount[] | undefined) => {
|
||||
if (!oldData) return [updatedAccount];
|
||||
return oldData.map((acc) => (acc.id === updatedAccount.id ? updatedAccount : acc));
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: QUERY_KEYS.cloudAccounts });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -97,12 +97,8 @@ export function useSetAutoSwitchEnabled() {
|
||||
}
|
||||
|
||||
export function useForcePollCloudMonitor() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: forcePollCloudMonitor,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: QUERY_KEYS.cloudAccounts });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { app } from 'electron';
|
||||
import * as Sentry from '@sentry/electron/main';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { getAppDataDir } from './utils/paths';
|
||||
import { logger } from './utils/logger';
|
||||
|
||||
function getQuickConfig() {
|
||||
try {
|
||||
const configPath = path.join(getAppDataDir(), 'gui_config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
// Default to false (privacy by default)
|
||||
return config.error_reporting_enabled;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to read config for Sentry init:', e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (getQuickConfig()) {
|
||||
Sentry.init({
|
||||
dsn: process.env.SENTRY_DSN,
|
||||
release: `antigravity-manager@${app.getVersion()}`,
|
||||
beforeSend(event) {
|
||||
if (event.exception?.values?.[0]?.value) {
|
||||
event.exception.values[0].value = event.exception.values[0].value.replace(
|
||||
/Users\\\\[^\\\\]+/g,
|
||||
'Users\\\\***',
|
||||
);
|
||||
}
|
||||
return event;
|
||||
},
|
||||
});
|
||||
logger.setErrorReportingEnabled(true);
|
||||
logger.setSentryReporter((payload) => {
|
||||
Sentry.withScope((scope) => {
|
||||
scope.setTag('log_level', payload.level);
|
||||
scope.setContext('recent_logs', {
|
||||
entries: payload.logs.map((entry) => ({
|
||||
timestamp: new Date(entry.timestamp).toISOString(),
|
||||
level: entry.level,
|
||||
message: entry.message,
|
||||
formatted: entry.formatted,
|
||||
})),
|
||||
});
|
||||
scope.setExtra('log_message', payload.message);
|
||||
if (payload.error) {
|
||||
Sentry.captureException(payload.error);
|
||||
return;
|
||||
}
|
||||
Sentry.captureMessage(payload.message, 'error');
|
||||
});
|
||||
});
|
||||
} else {
|
||||
logger.setErrorReportingEnabled(false);
|
||||
logger.setSentryReporter(null);
|
||||
}
|
||||
@@ -20,13 +20,11 @@ export class AuthServer {
|
||||
const error = url.searchParams.get('error');
|
||||
|
||||
if (code) {
|
||||
logger.info(`AuthServer: Received authorization code: ${code.substring(0, 10)}...`);
|
||||
logger.info('AuthServer: Received authorization code');
|
||||
|
||||
// Send code to renderer
|
||||
if (ipcContext.mainWindow) {
|
||||
logger.info('AuthServer: Sending code to renderer via IPC');
|
||||
ipcContext.mainWindow.webContents.send('GOOGLE_AUTH_CODE', code);
|
||||
logger.info('AuthServer: Code sent successfully');
|
||||
} else {
|
||||
logger.error('AuthServer: Main window not found, cannot send code');
|
||||
}
|
||||
|
||||
@@ -123,8 +123,6 @@ export async function refreshAccountQuota(accountId: string): Promise<CloudAccou
|
||||
const quota = await GoogleAPIService.fetchQuota(account.token.access_token);
|
||||
account.quota = quota;
|
||||
await CloudAccountRepo.updateQuota(account.id, quota);
|
||||
await CloudAccountRepo.updateLastUsed(account.id);
|
||||
account.last_used = Math.floor(Date.now() / 1000); // Sync memory object
|
||||
notifyTrayUpdate(account);
|
||||
return account;
|
||||
} catch (error: any) {
|
||||
@@ -145,8 +143,6 @@ export async function refreshAccountQuota(accountId: string): Promise<CloudAccou
|
||||
const quota = await GoogleAPIService.fetchQuota(account.token.access_token);
|
||||
account.quota = quota;
|
||||
await CloudAccountRepo.updateQuota(account.id, quota);
|
||||
await CloudAccountRepo.updateLastUsed(account.id);
|
||||
account.last_used = Math.floor(Date.now() / 1000); // Sync memory object
|
||||
return account;
|
||||
} catch (refreshError) {
|
||||
logger.error(
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
import { AppConfig } from '../../types/config';
|
||||
import { ConfigManager } from './manager';
|
||||
import { syncAutoStart } from '../../utils/autoStart';
|
||||
import { logger } from '../../utils/logger';
|
||||
|
||||
export function loadConfig(): AppConfig {
|
||||
return ConfigManager.loadConfig();
|
||||
}
|
||||
|
||||
export async function saveConfig(config: AppConfig): Promise<void> {
|
||||
export function saveConfig(config: AppConfig): void {
|
||||
// Logic to notify proxy server if configuration changes (hot update)
|
||||
// Logic to update Tray if language changes
|
||||
// For now just save
|
||||
const previous = ConfigManager.getCachedConfig() ?? ConfigManager.loadConfig();
|
||||
await ConfigManager.saveConfig(config);
|
||||
logger.setErrorReportingEnabled(config.error_reporting_enabled);
|
||||
if (previous.auto_startup !== config.auto_startup) {
|
||||
syncAutoStart(config);
|
||||
}
|
||||
ConfigManager.saveConfig(config);
|
||||
}
|
||||
+12
-29
@@ -7,9 +7,6 @@ import { logger } from '../../utils/logger';
|
||||
const CONFIG_FILENAME = 'gui_config.json';
|
||||
|
||||
export class ConfigManager {
|
||||
private static cachedConfig: AppConfig | null = null;
|
||||
private static saveQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
private static getConfigPath(): string {
|
||||
const appDataDir = getAppDataDir();
|
||||
if (!fs.existsSync(appDataDir)) {
|
||||
@@ -23,7 +20,6 @@ export class ConfigManager {
|
||||
const configPath = this.getConfigPath();
|
||||
if (!fs.existsSync(configPath)) {
|
||||
logger.info(`Config: File not found at ${configPath}, returning default`);
|
||||
this.cachedConfig = DEFAULT_APP_CONFIG;
|
||||
return DEFAULT_APP_CONFIG;
|
||||
}
|
||||
|
||||
@@ -32,7 +28,7 @@ export class ConfigManager {
|
||||
|
||||
// Merge with default to ensure new fields are present
|
||||
// Zod parse helps validate
|
||||
const merged: AppConfig = {
|
||||
const merged = {
|
||||
...DEFAULT_APP_CONFIG,
|
||||
...raw,
|
||||
proxy: { ...DEFAULT_APP_CONFIG.proxy, ...(raw.proxy || {}) },
|
||||
@@ -49,35 +45,22 @@ export class ConfigManager {
|
||||
// Handle Anthropic Mapping Map vs Object
|
||||
// In JSON it's object
|
||||
|
||||
this.cachedConfig = merged;
|
||||
return merged;
|
||||
return merged as AppConfig;
|
||||
} catch (e) {
|
||||
logger.error('Config: Failed to load config', e);
|
||||
this.cachedConfig = DEFAULT_APP_CONFIG;
|
||||
return DEFAULT_APP_CONFIG;
|
||||
}
|
||||
}
|
||||
|
||||
static getCachedConfig(): AppConfig | null {
|
||||
return this.cachedConfig;
|
||||
}
|
||||
|
||||
static async saveConfig(config: AppConfig): Promise<void> {
|
||||
const configPath = this.getConfigPath();
|
||||
const content = JSON.stringify(config, null, 2);
|
||||
|
||||
this.saveQueue = this.saveQueue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await fs.promises.writeFile(configPath, content, 'utf-8');
|
||||
this.cachedConfig = config;
|
||||
logger.info(`Config: Saved to ${configPath}`);
|
||||
})
|
||||
.catch((e) => {
|
||||
logger.error('Config: Failed to save config', e);
|
||||
throw e;
|
||||
});
|
||||
|
||||
return this.saveQueue;
|
||||
static saveConfig(config: AppConfig): void {
|
||||
try {
|
||||
const configPath = this.getConfigPath();
|
||||
const content = JSON.stringify(config, null, 2);
|
||||
fs.writeFileSync(configPath, content, 'utf-8');
|
||||
logger.info(`Config: Saved to ${configPath}`);
|
||||
} catch (e) {
|
||||
logger.error('Config: Failed to save config', e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,6 @@ export const configRouter = os.router({
|
||||
.input(AppConfigSchema)
|
||||
.output(z.void())
|
||||
.handler(async ({ input }) => {
|
||||
await saveConfig(input);
|
||||
saveConfig(input);
|
||||
}),
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { v4 as uuidv4 } from 'uuid';
|
||||
import { getCloudAccountsDbPath, getAntigravityDbPaths } from '../../utils/paths';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { CloudAccount } from '../../types/cloudAccount';
|
||||
import { decryptWithMigration, encrypt, type KeySource } from '../../utils/security';
|
||||
import { encrypt, decrypt } from '../../utils/security';
|
||||
import { ProtobufUtils } from '../../utils/protobuf';
|
||||
import { GoogleAPIService } from '../../services/GoogleAPIService';
|
||||
|
||||
@@ -22,7 +22,6 @@ function ensureDatabaseInitialized(dbPath: string): void {
|
||||
let db: Database.Database | null = null;
|
||||
try {
|
||||
db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
|
||||
// Create accounts table
|
||||
// Storing complex objects (token, quota) as JSON strings for simplicity
|
||||
@@ -74,70 +73,9 @@ function ensureDatabaseInitialized(dbPath: string): void {
|
||||
function getDb(): Database.Database {
|
||||
const dbPath = getCloudAccountsDbPath();
|
||||
ensureDatabaseInitialized(dbPath);
|
||||
const db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
return db;
|
||||
return new Database(dbPath);
|
||||
}
|
||||
|
||||
interface MigrationStats {
|
||||
totalFields: number;
|
||||
fallbackUsedFields: number;
|
||||
migratedFields: number;
|
||||
migratedBySource: Record<KeySource, number>;
|
||||
failedFields: number;
|
||||
}
|
||||
|
||||
function createMigrationStats(): MigrationStats {
|
||||
return {
|
||||
totalFields: 0,
|
||||
fallbackUsedFields: 0,
|
||||
migratedFields: 0,
|
||||
migratedBySource: {
|
||||
safeStorage: 0,
|
||||
keytar: 0,
|
||||
file: 0,
|
||||
},
|
||||
failedFields: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function decryptAndMigrateField(
|
||||
db: Database.Database,
|
||||
accountId: string,
|
||||
field: 'token_json' | 'quota_json',
|
||||
value: string | null,
|
||||
): Promise<{ value: string | null; migrated: boolean; usedFallback?: KeySource }> {
|
||||
if (!value) {
|
||||
return { value: null, migrated: false };
|
||||
}
|
||||
|
||||
const result = await decryptWithMigration(value);
|
||||
if (result.reencrypted) {
|
||||
if (field === 'token_json') {
|
||||
db.prepare('UPDATE accounts SET token_json = ? WHERE id = ?').run(
|
||||
result.reencrypted,
|
||||
accountId,
|
||||
);
|
||||
} else {
|
||||
db.prepare('UPDATE accounts SET quota_json = ? WHERE id = ?').run(
|
||||
result.reencrypted,
|
||||
accountId,
|
||||
);
|
||||
}
|
||||
logger.info(
|
||||
`Migrated ${field} for account ${accountId} from ${result.usedFallback ?? 'unknown'} key`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
value: result.value,
|
||||
migrated: Boolean(result.reencrypted),
|
||||
usedFallback: result.usedFallback,
|
||||
};
|
||||
}
|
||||
|
||||
type DecryptFieldResult = Awaited<ReturnType<typeof decryptAndMigrateField>>;
|
||||
|
||||
export class CloudAccountRepo {
|
||||
static async init(): Promise<void> {
|
||||
const dbPath = getCloudAccountsDbPath();
|
||||
@@ -230,7 +168,6 @@ export class CloudAccountRepo {
|
||||
|
||||
static async getAccounts(): Promise<CloudAccount[]> {
|
||||
const db = getDb();
|
||||
const migrationStats = createMigrationStats();
|
||||
|
||||
try {
|
||||
const stmt = db.prepare('SELECT * FROM accounts ORDER BY last_used DESC');
|
||||
@@ -243,91 +180,24 @@ export class CloudAccountRepo {
|
||||
);
|
||||
activeRows.forEach((r) => logger.info(`[DEBUG] Active Account: ${r.email} (${r.id})`));
|
||||
|
||||
const accounts: CloudAccount[] = [];
|
||||
for (const row of rows) {
|
||||
let tokenResult: DecryptFieldResult;
|
||||
try {
|
||||
tokenResult = await decryptAndMigrateField(db, row.id, 'token_json', row.token_json);
|
||||
} catch (error) {
|
||||
migrationStats.failedFields += 1;
|
||||
logger.error(`Failed to decrypt token for account ${row.id}`, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
let quotaResult: DecryptFieldResult;
|
||||
try {
|
||||
quotaResult = await decryptAndMigrateField(db, row.id, 'quota_json', row.quota_json);
|
||||
} catch (error) {
|
||||
migrationStats.failedFields += 1;
|
||||
logger.error(`Failed to decrypt quota for account ${row.id}`, error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (!tokenResult.value) {
|
||||
throw new Error(`Missing token data for account ${row.id}`);
|
||||
}
|
||||
|
||||
if (tokenResult.value) {
|
||||
migrationStats.totalFields += 1;
|
||||
}
|
||||
if (tokenResult.usedFallback) {
|
||||
migrationStats.fallbackUsedFields += 1;
|
||||
}
|
||||
if (tokenResult.migrated) {
|
||||
migrationStats.migratedFields += 1;
|
||||
if (tokenResult.usedFallback) {
|
||||
migrationStats.migratedBySource[tokenResult.usedFallback] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (quotaResult.value) {
|
||||
migrationStats.totalFields += 1;
|
||||
}
|
||||
if (quotaResult.usedFallback) {
|
||||
migrationStats.fallbackUsedFields += 1;
|
||||
}
|
||||
if (quotaResult.migrated) {
|
||||
migrationStats.migratedFields += 1;
|
||||
if (quotaResult.usedFallback) {
|
||||
migrationStats.migratedBySource[quotaResult.usedFallback] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
accounts.push({
|
||||
const accounts = await Promise.all(
|
||||
rows.map(async (row) => ({
|
||||
id: row.id,
|
||||
provider: row.provider,
|
||||
email: row.email,
|
||||
name: row.name,
|
||||
avatar_url: row.avatar_url,
|
||||
token: JSON.parse(tokenResult.value),
|
||||
quota: quotaResult.value ? JSON.parse(quotaResult.value) : undefined,
|
||||
token: JSON.parse(await decrypt(row.token_json)),
|
||||
quota: row.quota_json ? JSON.parse(await decrypt(row.quota_json)) : undefined,
|
||||
created_at: row.created_at,
|
||||
last_used: row.last_used,
|
||||
status: row.status,
|
||||
is_active: Boolean(row.is_active),
|
||||
});
|
||||
}
|
||||
})),
|
||||
);
|
||||
|
||||
return accounts;
|
||||
} finally {
|
||||
if (
|
||||
migrationStats.migratedFields > 0 ||
|
||||
migrationStats.fallbackUsedFields > 0 ||
|
||||
migrationStats.failedFields > 0
|
||||
) {
|
||||
const summary = {
|
||||
totalFields: migrationStats.totalFields,
|
||||
fallbackUsedFields: migrationStats.fallbackUsedFields,
|
||||
migratedFields: migrationStats.migratedFields,
|
||||
migratedBySource: migrationStats.migratedBySource,
|
||||
failedFields: migrationStats.failedFields,
|
||||
};
|
||||
if (migrationStats.failedFields > 0) {
|
||||
logger.warn('CloudAccountRepo migration summary (with failures)', summary);
|
||||
} else {
|
||||
logger.info('CloudAccountRepo migration summary', summary);
|
||||
}
|
||||
}
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
@@ -341,21 +211,14 @@ export class CloudAccountRepo {
|
||||
|
||||
if (!row) return undefined;
|
||||
|
||||
const tokenResult = await decryptAndMigrateField(db, row.id, 'token_json', row.token_json);
|
||||
const quotaResult = await decryptAndMigrateField(db, row.id, 'quota_json', row.quota_json);
|
||||
|
||||
if (!tokenResult.value) {
|
||||
throw new Error(`Missing token data for account ${row.id}`);
|
||||
}
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
provider: row.provider,
|
||||
email: row.email,
|
||||
name: row.name,
|
||||
avatar_url: row.avatar_url,
|
||||
token: JSON.parse(tokenResult.value),
|
||||
quota: quotaResult.value ? JSON.parse(quotaResult.value) : undefined,
|
||||
token: JSON.parse(await decrypt(row.token_json)),
|
||||
quota: row.quota_json ? JSON.parse(await decrypt(row.quota_json)) : undefined,
|
||||
created_at: row.created_at,
|
||||
last_used: row.last_used,
|
||||
status: row.status,
|
||||
@@ -430,14 +293,20 @@ export class CloudAccountRepo {
|
||||
|
||||
static injectCloudToken(account: CloudAccount): void {
|
||||
const dbPaths = getAntigravityDbPaths();
|
||||
const dbPath = dbPaths.find((p) => fs.existsSync(p)) ?? null;
|
||||
let dbPath: string | null = null;
|
||||
|
||||
for (const p of dbPaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
dbPath = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!dbPath) {
|
||||
throw new Error(`Antigravity database not found. Checked paths: ${dbPaths.join(', ')}`);
|
||||
}
|
||||
|
||||
const db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
try {
|
||||
const row = db
|
||||
.prepare('SELECT value FROM ItemTable WHERE key = ?')
|
||||
@@ -568,11 +437,14 @@ export class CloudAccountRepo {
|
||||
const dbPaths = getAntigravityDbPaths();
|
||||
logger.info(`SyncLocal: Checking database paths: ${JSON.stringify(dbPaths)}`);
|
||||
|
||||
const dbPath =
|
||||
dbPaths.find((p) => {
|
||||
logger.info(`SyncLocal: Checking path: ${p}, exists: ${fs.existsSync(p)}`);
|
||||
return fs.existsSync(p);
|
||||
}) ?? null;
|
||||
let dbPath: string | null = null;
|
||||
for (const p of dbPaths) {
|
||||
logger.info(`SyncLocal: Checking path: ${p}, exists: ${fs.existsSync(p)}`);
|
||||
if (fs.existsSync(p)) {
|
||||
dbPath = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!dbPath) {
|
||||
const errorMsg = `Antigravity database not found. Please ensure Antigravity IDE is installed. Checked paths: ${dbPaths.join(', ')}`;
|
||||
@@ -582,7 +454,6 @@ export class CloudAccountRepo {
|
||||
|
||||
logger.info(`SyncLocal: Using Antigravity database at: ${dbPath}`);
|
||||
const ideDb = new Database(dbPath, { readonly: true });
|
||||
ideDb.pragma('journal_mode = WAL');
|
||||
try {
|
||||
// 1. Read Raw Token Data
|
||||
const row = ideDb
|
||||
|
||||
@@ -8,31 +8,6 @@ import path from 'path';
|
||||
|
||||
const KEYS_TO_BACKUP = ['antigravityAuthStatus', 'jetskiStateSync.agentManagerInitState'];
|
||||
|
||||
function getDbWithWal(dbPath: string, options: Database.Options = {}): Database.Database {
|
||||
const db = new Database(dbPath, options);
|
||||
db.pragma('journal_mode = WAL');
|
||||
return db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the database and ensures WAL mode is enabled.
|
||||
* Should be called on application startup.
|
||||
*/
|
||||
export function initDatabase(): void {
|
||||
try {
|
||||
const dbPaths = getAntigravityDbPaths();
|
||||
if (dbPaths.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const db = getDatabaseConnection();
|
||||
db.close();
|
||||
logger.info('Database initialized and verified (WAL mode)');
|
||||
} catch (error) {
|
||||
logger.error('Failed to initialize database on startup', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the database file exists.
|
||||
* @param dbPath {string} The path to the database file.
|
||||
@@ -84,7 +59,7 @@ export function getDatabaseConnection(dbPath?: string): Database.Database {
|
||||
ensureDatabaseExists(targetPath);
|
||||
|
||||
try {
|
||||
return getDbWithWal(targetPath, { readonly: false, fileMustExist: false });
|
||||
return new Database(targetPath, { readonly: false, fileMustExist: false });
|
||||
} catch (error: unknown) {
|
||||
const err = error as { code?: string };
|
||||
if (err.code === 'SQLITE_BUSY' || err.code === 'SQLITE_LOCKED') {
|
||||
@@ -94,12 +69,6 @@ export function getDatabaseConnection(dbPath?: string): Database.Database {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a database connection and enables WAL mode.
|
||||
* @param dbPath {string} The path to the database file.
|
||||
* @returns {Database.Database} The database connection.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gets the current account info.
|
||||
* @returns {AccountInfo} The current account info.
|
||||
|
||||
@@ -53,7 +53,7 @@ export const generateApiKey = async (): Promise<string> => {
|
||||
// Save to config
|
||||
const config = ConfigManager.loadConfig();
|
||||
config.proxy.api_key = newKey;
|
||||
await ConfigManager.saveConfig(config);
|
||||
ConfigManager.saveConfig(config);
|
||||
|
||||
return newKey;
|
||||
};
|
||||
+1
-1
@@ -78,7 +78,7 @@ function createIPCClient(port: MessagePort) {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error(`Request /${methodPath} timed out`));
|
||||
}
|
||||
}, 60000);
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+36
-139
@@ -1,166 +1,63 @@
|
||||
import { exec, execSync } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import findProcess, { ProcessInfo } from 'find-process';
|
||||
import { getAntigravityExecutablePath, isWsl } from '../../utils/paths';
|
||||
import { logger } from '../../utils/logger';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
/**
|
||||
* Helper process name patterns to exclude (Electron helper processes)
|
||||
*/
|
||||
const HELPER_PATTERNS = [
|
||||
'helper',
|
||||
'plugin',
|
||||
'renderer',
|
||||
'gpu',
|
||||
'crashpad',
|
||||
'utility',
|
||||
'audio',
|
||||
'sandbox',
|
||||
'language_server',
|
||||
];
|
||||
|
||||
/**
|
||||
* Check if a process is a helper/auxiliary process that should be excluded.
|
||||
* @param name Process name (lowercase)
|
||||
* @param cmd Process command line (lowercase)
|
||||
* @returns True if the process is a helper process
|
||||
*/
|
||||
function isHelperProcess(name: string, cmd: string): boolean {
|
||||
const nameLower = name.toLowerCase();
|
||||
const cmdLower = cmd.toLowerCase();
|
||||
|
||||
// Check for --type= argument (Electron helper process indicator)
|
||||
if (cmdLower.includes('--type=')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for helper patterns in process name
|
||||
for (const pattern of HELPER_PATTERNS) {
|
||||
if (nameLower.includes(pattern)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for crashpad in path
|
||||
if (cmdLower.includes('crashpad')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function isPgrepNoMatchError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const message = error.message.toLowerCase();
|
||||
const hasPgrep = message.includes('pgrep') && message.includes('antigravity');
|
||||
const code = (error as { code?: number }).code;
|
||||
return hasPgrep && code === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the Antigravity process is running.
|
||||
* Uses find-process package for robust cross-platform process detection.
|
||||
* @returns {boolean} True if the Antigravity process is running, false otherwise.
|
||||
*/
|
||||
export async function isProcessRunning(): Promise<boolean> {
|
||||
try {
|
||||
const platform = process.platform;
|
||||
const currentPid = process.pid;
|
||||
let command = '';
|
||||
|
||||
// Use find-process to search for Antigravity processes
|
||||
// 'name' search type matches process name
|
||||
const processMap = new Map<number, ProcessInfo>();
|
||||
const searchNames = ['Antigravity', 'antigravity'];
|
||||
let sawNoMatch = false;
|
||||
if (platform === 'win32' || isWsl()) {
|
||||
// Use absolute path for tasklist to be safe on Windows too
|
||||
const cmd = isWsl()
|
||||
? '/mnt/c/Windows/System32/tasklist.exe'
|
||||
: process.env.SystemRoot // Usually C:\Windows
|
||||
? `${process.env.SystemRoot}\\System32\\tasklist.exe`
|
||||
: 'tasklist';
|
||||
|
||||
for (const searchName of searchNames) {
|
||||
try {
|
||||
const matches = await findProcess('name', searchName, true);
|
||||
for (const proc of matches) {
|
||||
if (typeof proc.pid === 'number') {
|
||||
processMap.set(proc.pid, proc);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (isPgrepNoMatchError(error)) {
|
||||
sawNoMatch = true;
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
command = `${cmd} /FI "IMAGENAME eq Antigravity.exe" /NH`;
|
||||
} else {
|
||||
// macOS and Linux (native)
|
||||
command = 'pgrep -xi Antigravity';
|
||||
}
|
||||
|
||||
const processes = Array.from(processMap.values());
|
||||
if (processes.length === 0 && sawNoMatch) {
|
||||
logger.debug('No Antigravity process found (pgrep returned 1)');
|
||||
}
|
||||
logger.debug(`Checking process with command: ${command}`);
|
||||
// Increased timeout to 4000ms to avoid flakiness with tasklist/wmic
|
||||
try {
|
||||
const { stdout } = await execAsync(command, { timeout: 4000 });
|
||||
logger.debug(`Process check stdout: ${stdout.trim()}`);
|
||||
|
||||
logger.debug(`Found ${processes.length} processes matching 'Antigravity/antigravity'`);
|
||||
|
||||
for (const proc of processes) {
|
||||
// Skip self
|
||||
if (proc.pid === currentPid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = proc.name?.toLowerCase() || '';
|
||||
const cmd = proc.cmd?.toLowerCase() || '';
|
||||
|
||||
// Skip manager process
|
||||
if (
|
||||
name.includes('manager') ||
|
||||
cmd.includes('manager') ||
|
||||
cmd.includes('antigravity-manager')
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip helper processes
|
||||
if (isHelperProcess(name, cmd)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (platform === 'darwin') {
|
||||
// macOS: Check for Antigravity.app in path
|
||||
if (cmd.includes('antigravity.app')) {
|
||||
logger.debug(
|
||||
`Found Antigravity process: PID=${proc.pid}, name=${name}, cmd=${cmd.substring(0, 100)}`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
// Also check if the process name is exactly 'Antigravity' (main process)
|
||||
if (name === 'antigravity' && !isHelperProcess(name, cmd)) {
|
||||
logger.debug(`Found Antigravity process: PID=${proc.pid}, name=${name}`);
|
||||
return true;
|
||||
}
|
||||
} else if (platform === 'win32') {
|
||||
// Windows: Check for Antigravity.exe
|
||||
if (name === 'antigravity.exe' || name === 'antigravity') {
|
||||
logger.debug(`Found Antigravity process: PID=${proc.pid}, name=${name}`);
|
||||
return true;
|
||||
}
|
||||
if (platform === 'win32' || isWsl()) {
|
||||
return stdout.includes('Antigravity.exe');
|
||||
} else {
|
||||
// Linux: Check for antigravity in name or path (but not tools)
|
||||
if (
|
||||
(name.includes('antigravity') || cmd.includes('/antigravity')) &&
|
||||
!name.includes('tools')
|
||||
) {
|
||||
logger.debug(
|
||||
`Found Antigravity process: PID=${proc.pid}, name=${name}, cmd=${cmd.substring(0, 100)}`,
|
||||
);
|
||||
return true;
|
||||
// pgrep returns PIDs if found, empty if not
|
||||
return stdout.trim().length > 0;
|
||||
}
|
||||
} catch (cmdError) {
|
||||
if (platform === 'win32' && !isWsl()) {
|
||||
logger.warn('tasklist failed, trying wmic fallback...', cmdError);
|
||||
// Fallback to wmic (filtered)
|
||||
try {
|
||||
const wmicCmd = 'wmic process where "name=\'Antigravity.exe\'" get ProcessId';
|
||||
const { stdout } = await execAsync(wmicCmd, { timeout: 4000 });
|
||||
return stdout.includes('ProcessId');
|
||||
} catch (wmicError) {
|
||||
logger.error('wmic fallback also failed', wmicError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
throw cmdError;
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (error) {
|
||||
logger.error('Error checking process status with find-process:', error);
|
||||
logger.error('Error checking process status:', error);
|
||||
// pgrep returns exit code 1 if no process found
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { os } from '@orpc/server';
|
||||
import { z } from 'zod';
|
||||
import { networkInterfaces } from 'os';
|
||||
import { shell } from 'electron';
|
||||
import { getAgentDir } from '../../utils/paths';
|
||||
|
||||
// Schema for IP info
|
||||
const IpInfoSchema = z.object({
|
||||
@@ -63,10 +61,4 @@ export const systemHandler = os.router({
|
||||
|
||||
return results;
|
||||
}),
|
||||
|
||||
// Open log directory in file explorer
|
||||
openLogDirectory: os.output(z.void()).handler(async () => {
|
||||
const logDir = getAgentDir();
|
||||
await shell.openPath(logDir);
|
||||
}),
|
||||
});
|
||||
@@ -51,14 +51,9 @@ export function initTray(mainWindow: BrowserWindow) {
|
||||
}
|
||||
|
||||
const inDevelopment = process.env.NODE_ENV === 'development';
|
||||
// In production, extraResource copies 'src/assets' folder to 'resources/assets'
|
||||
const iconPath = inDevelopment
|
||||
? path.join(process.cwd(), 'src/assets/tray.png')
|
||||
: path.join(process.resourcesPath, 'assets', 'tray.png');
|
||||
|
||||
logger.info(
|
||||
`Tray icon path: ${iconPath}, inDevelopment: ${inDevelopment}, resourcesPath: ${process.resourcesPath}`,
|
||||
);
|
||||
: path.join(process.resourcesPath, 'assets/tray.png');
|
||||
|
||||
const icon = nativeImage.createFromPath(iconPath);
|
||||
|
||||
|
||||
+28
-108
@@ -1,34 +1,14 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React from 'react';
|
||||
import { Link, Outlet, useLocation } from '@tanstack/react-router';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { StatusBar } from '@/components/StatusBar';
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Settings,
|
||||
Network,
|
||||
Rocket,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
} from 'lucide-react';
|
||||
import { LayoutDashboard, Settings, Network, Rocket } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
|
||||
export const MainLayout: React.FC = () => {
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Initialize state from localStorage if available, default to false (expanded)
|
||||
const [isCollapsed, setIsCollapsed] = useState(() => {
|
||||
const saved = localStorage.getItem('sidebar-collapsed');
|
||||
return saved ? JSON.parse(saved) : false;
|
||||
});
|
||||
|
||||
// Persist state changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem('sidebar-collapsed', JSON.stringify(isCollapsed));
|
||||
}, [isCollapsed]);
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
to: '/',
|
||||
@@ -51,102 +31,42 @@ export const MainLayout: React.FC = () => {
|
||||
<div className="bg-background text-foreground flex h-screen flex-col overflow-hidden">
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
{/* Sidebar */}
|
||||
<aside
|
||||
className={cn(
|
||||
'bg-muted/10 group relative flex flex-col border-r transition-all duration-300 ease-in-out',
|
||||
isCollapsed ? 'w-[70px]' : 'w-64',
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="bg-background hover:bg-accent hover:text-accent-foreground absolute top-6 -right-3 z-10 h-6 w-6 rounded-full border opacity-0 shadow-md transition-opacity group-hover:opacity-100"
|
||||
onClick={() => setIsCollapsed(!isCollapsed)}
|
||||
>
|
||||
{isCollapsed ? (
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronLeft className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<div className={cn('flex flex-col', isCollapsed ? 'items-center p-4' : 'p-6')}>
|
||||
<div className="flex items-center gap-2 overflow-hidden whitespace-nowrap">
|
||||
<div className="bg-primary text-primary-foreground flex h-6 w-6 shrink-0 items-center justify-center rounded">
|
||||
<aside className="bg-muted/10 flex w-64 flex-col border-r">
|
||||
<div className="p-6">
|
||||
<h1 className="flex items-center gap-2 text-xl font-bold tracking-tight">
|
||||
<div className="bg-primary text-primary-foreground flex h-6 w-6 items-center justify-center rounded">
|
||||
<Rocket className="h-4 w-4" />
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'overflow-hidden transition-all duration-300',
|
||||
isCollapsed ? 'w-0 opacity-0' : 'w-auto opacity-100',
|
||||
)}
|
||||
>
|
||||
<h1 className="text-xl font-bold tracking-tight">Antigravity</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
'text-muted-foreground mt-1 overflow-hidden text-xs whitespace-nowrap transition-all duration-300',
|
||||
isCollapsed ? 'h-0 opacity-0' : 'h-auto opacity-100',
|
||||
)}
|
||||
>
|
||||
Manager
|
||||
</div>
|
||||
Antigravity
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1 text-xs">Manager</p>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 space-y-2 px-2">
|
||||
<TooltipProvider>
|
||||
{navItems.map((item) => {
|
||||
const isActive = location.pathname === item.to;
|
||||
|
||||
if (isCollapsed) {
|
||||
return (
|
||||
<Tooltip key={item.to} delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<Link
|
||||
to={item.to}
|
||||
className={cn(
|
||||
'mx-auto flex h-10 w-10 items-center justify-center rounded-md transition-colors',
|
||||
isActive
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'hover:bg-muted text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<item.icon className="h-5 w-5" />
|
||||
<span className="sr-only">{item.label}</span>
|
||||
</Link>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">{item.label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
className={cn(
|
||||
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
|
||||
isActive
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'hover:bg-muted text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<item.icon className="h-4 w-4" />
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</TooltipProvider>
|
||||
<nav className="flex-1 space-y-2 px-4">
|
||||
{navItems.map((item) => (
|
||||
<Link
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
className={cn(
|
||||
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
|
||||
location.pathname === item.to
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'hover:bg-muted text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<item.icon className="h-4 w-4" />
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="border-t p-2">
|
||||
<StatusBar isCollapsed={isCollapsed} />
|
||||
<div className="border-t p-4">
|
||||
<StatusBar />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Content Area */}
|
||||
<main className="flex-1 overflow-auto transition-all duration-300">
|
||||
<main className="flex-1 overflow-auto">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -51,7 +51,7 @@ export function transformClaudeRequestIn(
|
||||
const toolIdToName = new Map<string, string>();
|
||||
|
||||
// 1. System Instruction
|
||||
const systemInstruction = buildSystemInstruction(claudeReq.system, claudeReq.model);
|
||||
let systemInstruction = buildSystemInstruction(claudeReq.system, claudeReq.model);
|
||||
|
||||
// Map model name
|
||||
const mappedModel = hasWebSearchTool
|
||||
@@ -100,7 +100,7 @@ export function transformClaudeRequestIn(
|
||||
);
|
||||
|
||||
// 3. Tools
|
||||
const tools = buildTools(claudeReq.tools, hasWebSearchTool);
|
||||
let tools = buildTools(claudeReq.tools, hasWebSearchTool);
|
||||
|
||||
// 5. Safety Settings
|
||||
const safetySettings = [
|
||||
@@ -152,7 +152,7 @@ export function transformClaudeRequestIn(
|
||||
delete innerRequest.systemInstruction;
|
||||
|
||||
// 3. Clean generationConfig
|
||||
const genConfig = innerRequest.generationConfig || {};
|
||||
let genConfig = innerRequest.generationConfig || {};
|
||||
delete genConfig.thinkingConfig;
|
||||
delete genConfig.responseMimeType;
|
||||
delete genConfig.responseModalities;
|
||||
|
||||
@@ -67,7 +67,7 @@ function flattenRefs(map: any, defs: Record<string, any>) {
|
||||
|
||||
// Recursively process all children
|
||||
for (const k in map) {
|
||||
if (Object.prototype.hasOwnProperty.call(map, k)) {
|
||||
if (map.hasOwnProperty(k)) {
|
||||
const v = map[k];
|
||||
if (typeof v === 'object' && v !== null) {
|
||||
flattenRefs(v, defs);
|
||||
@@ -91,7 +91,7 @@ function cleanJsonSchemaRecursive(value: any) {
|
||||
|
||||
// 1. Recursively process all children first to ensure nested structures are cleaned
|
||||
for (const k in map) {
|
||||
if (Object.prototype.hasOwnProperty.call(map, k)) {
|
||||
if (map.hasOwnProperty(k)) {
|
||||
cleanJsonSchemaRecursive(map[k]);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-391
@@ -12,7 +12,7 @@ i18n
|
||||
caches: ['localStorage'],
|
||||
lookupLocalStorage: 'lang',
|
||||
},
|
||||
supportedLngs: ['en', 'zh-CN', 'ru'],
|
||||
supportedLngs: ['en', 'zh-CN'],
|
||||
load: 'currentOnly', // Only load the exact language code, not variants
|
||||
resources: {
|
||||
en: {
|
||||
@@ -30,23 +30,9 @@ i18n
|
||||
deleteBackup: 'Delete Backup',
|
||||
backupCurrent: 'Backup Current',
|
||||
retry: 'Retry',
|
||||
openLogs: 'Open Log Directory',
|
||||
},
|
||||
error: {
|
||||
generic: 'An unexpected error occurred.',
|
||||
keychainUnavailable: 'Keychain is unavailable.',
|
||||
keychainHint: {
|
||||
translocation:
|
||||
'Detected macOS App Translocation. Move the app to /Applications and reopen.',
|
||||
keychainDenied:
|
||||
'Keychain access denied. The app may be unsigned; see README for the self-signing workaround.',
|
||||
signNotarize: 'Please use a signed and notarized build when available.',
|
||||
},
|
||||
dataMigrationFailed: 'Unable to decrypt legacy account data.',
|
||||
dataMigrationHint: {
|
||||
relogin: 'Please re-login or re-add your accounts.',
|
||||
clearData: 'If the issue persists, clear local account data and sign in again.',
|
||||
},
|
||||
},
|
||||
nav: {
|
||||
accounts: 'Accounts',
|
||||
@@ -83,7 +69,6 @@ i18n
|
||||
description: 'Select your preferred language.',
|
||||
english: 'English',
|
||||
chinese: 'Chinese (Simplified)',
|
||||
russian: 'Russian',
|
||||
},
|
||||
about: {
|
||||
title: 'About',
|
||||
@@ -92,7 +77,6 @@ i18n
|
||||
version: 'Version',
|
||||
platform: 'Platform',
|
||||
license: 'License',
|
||||
openLogDir: 'Open',
|
||||
account: {
|
||||
title: 'Account Settings',
|
||||
description: 'Configure automatic account refresh and sync.',
|
||||
@@ -101,23 +85,6 @@ i18n
|
||||
auto_sync: 'Auto Sync Current Account',
|
||||
auto_sync_desc: 'Periodically sync active account information',
|
||||
},
|
||||
startup: {
|
||||
title: 'Startup',
|
||||
description: 'Control application launch behavior at system startup.',
|
||||
auto_startup: 'Start with system',
|
||||
auto_startup_desc: 'Launch at sign-in and keep the app in the system tray',
|
||||
macos_hint:
|
||||
'macOS requires a signed app for Login Items to work. If auto-start fails, please sign the app or enable it manually in System Settings.',
|
||||
},
|
||||
privacy: {
|
||||
title: 'Privacy',
|
||||
description: 'Control how your data is used to improve the application.',
|
||||
error_reporting: 'Error Reporting',
|
||||
error_reporting_desc:
|
||||
'Send anonymous error reports to help us improve the app. No personal data is collected.',
|
||||
restart_note:
|
||||
'Changes to error reporting will take effect after restarting the application.',
|
||||
},
|
||||
proxy: {
|
||||
title: 'Upstream Proxy',
|
||||
description: 'Configure a proxy for outgoing requests to Google/Gemini APIs.',
|
||||
@@ -245,9 +212,6 @@ i18n
|
||||
list: {
|
||||
noAccounts: 'No cloud accounts added yet.',
|
||||
},
|
||||
error: {
|
||||
loadFailed: 'Failed to load cloud accounts.',
|
||||
},
|
||||
toast: {
|
||||
syncSuccess: {
|
||||
title: 'Sync Successful',
|
||||
@@ -263,7 +227,6 @@ i18n
|
||||
},
|
||||
quotaRefreshed: 'Quota refreshed',
|
||||
refreshFailed: 'Failed to refresh quota',
|
||||
pollFailed: 'Failed to poll quota for all accounts',
|
||||
switched: {
|
||||
title: 'Account switched!',
|
||||
description: 'Restarting Antigravity...',
|
||||
@@ -312,10 +275,6 @@ i18n
|
||||
api_key: 'API Key',
|
||||
auto_start: 'Auto Start with App',
|
||||
auto_start_desc: 'Start proxy service when application launches',
|
||||
local_access: 'Local network access:',
|
||||
no_token_warning: '⚠️ API key is not set. Access is open to everyone!',
|
||||
show_key: 'Show',
|
||||
hide_key: 'Hide',
|
||||
},
|
||||
mapping: {
|
||||
title: 'Model Mapping',
|
||||
@@ -345,23 +304,9 @@ i18n
|
||||
deleteBackup: '删除备份',
|
||||
backupCurrent: '备份当前账号',
|
||||
retry: '重试',
|
||||
openLogs: '打开日志目录',
|
||||
},
|
||||
error: {
|
||||
generic: '发生未知错误。',
|
||||
keychainUnavailable: 'Keychain 不可用。',
|
||||
keychainHint: {
|
||||
translocation:
|
||||
'检测到 macOS App Translocation。请将应用移动到 /Applications 后重试。',
|
||||
keychainDenied:
|
||||
'Keychain 访问被拒绝。应用可能未签名,可参考 README 的“macOS 自签”说明。',
|
||||
signNotarize: '请在可用时使用已签名并公证的版本。',
|
||||
},
|
||||
dataMigrationFailed: '旧版账号数据无法解密。',
|
||||
dataMigrationHint: {
|
||||
relogin: '请重新登录或重新添加账号。',
|
||||
clearData: '如仍失败,请清理本地账号数据后再登录。',
|
||||
},
|
||||
},
|
||||
nav: {
|
||||
accounts: '账号',
|
||||
@@ -398,7 +343,6 @@ i18n
|
||||
description: '选择您的首选语言。',
|
||||
english: '英语',
|
||||
chinese: '中文 (简体)',
|
||||
russian: '俄语',
|
||||
},
|
||||
about: {
|
||||
title: '关于',
|
||||
@@ -407,7 +351,6 @@ i18n
|
||||
version: '版本',
|
||||
platform: '平台',
|
||||
license: '许可证',
|
||||
openLogDir: '打开',
|
||||
account: {
|
||||
title: '账号设置',
|
||||
description: '配置自动刷新和同步账号。',
|
||||
@@ -416,22 +359,6 @@ i18n
|
||||
auto_sync: '自动获取当前账号',
|
||||
auto_sync_desc: '定期自动同步当前活跃账号信息',
|
||||
},
|
||||
startup: {
|
||||
title: '启动',
|
||||
description: '控制系统启动时的应用行为。',
|
||||
auto_startup: '随系统启动',
|
||||
auto_startup_desc: '登录时自动启动并保持在托盘里',
|
||||
macos_hint:
|
||||
'macOS 需要应用已签名才可生效。如自启动失败,请自行签名或在系统设置中手动启用。',
|
||||
},
|
||||
privacy: {
|
||||
title: '隐私',
|
||||
description: '控制你的数据如何用于改进应用。',
|
||||
error_reporting: '错误上报',
|
||||
error_reporting_desc:
|
||||
'发送匿名错误报告以帮助我们改进应用。不收集个人数据。',
|
||||
restart_note: '错误上报设置会在重启应用后生效。',
|
||||
},
|
||||
proxy: {
|
||||
title: '上游代理',
|
||||
description: '为发往 Google/Gemini API 的请求配置代理。',
|
||||
@@ -557,9 +484,6 @@ i18n
|
||||
list: {
|
||||
noAccounts: '暂无云账号。',
|
||||
},
|
||||
error: {
|
||||
loadFailed: '加载云账号失败。',
|
||||
},
|
||||
toast: {
|
||||
syncSuccess: {
|
||||
title: '同步成功',
|
||||
@@ -575,7 +499,6 @@ i18n
|
||||
},
|
||||
quotaRefreshed: '配额已刷新',
|
||||
refreshFailed: '刷新配额失败',
|
||||
pollFailed: '轮询所有账号配额失败',
|
||||
switched: {
|
||||
title: '账号已切换!',
|
||||
description: '正在重启 Antigravity...',
|
||||
@@ -641,318 +564,5 @@ i18n
|
||||
},
|
||||
},
|
||||
},
|
||||
ru: {
|
||||
translation: {
|
||||
appName: 'Antigravity Manager',
|
||||
status: {
|
||||
checking: 'Проверка статуса...',
|
||||
running: 'Antigravity работает в фоне',
|
||||
stopped: 'Служба Antigravity остановлена',
|
||||
},
|
||||
action: {
|
||||
stop: 'Стоп',
|
||||
start: 'Старт',
|
||||
switch: 'Переключить',
|
||||
deleteBackup: 'Удалить резервную копию',
|
||||
backupCurrent: 'Создать бэкап текущего',
|
||||
retry: 'Повторить',
|
||||
openLogs: 'Открыть папку логов',
|
||||
},
|
||||
error: {
|
||||
generic: 'Произошла непредвиденная ошибка.',
|
||||
keychainUnavailable: 'Keychain недоступен.',
|
||||
keychainHint: {
|
||||
translocation:
|
||||
'Обнаружено App Translocation (macOS). Переместите приложение в /Applications и откройте заново.',
|
||||
keychainDenied:
|
||||
'Доступ к Keychain запрещен. Возможно, приложение не подписано. См. README для инструкции.',
|
||||
signNotarize: 'Пожалуйста, используйте подписанную версию приложения.',
|
||||
},
|
||||
dataMigrationFailed: 'Не удалось расшифровать данные старого аккаунта.',
|
||||
dataMigrationHint: {
|
||||
relogin: 'Пожалуйста, перезайдите в аккаунт или добавьте его заново.',
|
||||
clearData: 'Если ошибка сохраняется, очистите локальные данные и войдите снова.',
|
||||
},
|
||||
},
|
||||
nav: {
|
||||
accounts: 'Аккаунты',
|
||||
proxy: 'API Прокси',
|
||||
settings: 'Настройки',
|
||||
},
|
||||
account: {
|
||||
current: 'Текущий',
|
||||
lastUsed: 'Последнее использование {{time}}',
|
||||
},
|
||||
home: {
|
||||
title: 'Аккаунты',
|
||||
description: 'Управление вашими аккаунтами Antigravity Google Gemini.',
|
||||
noBackups: {
|
||||
title: 'Бэкапы не найдены',
|
||||
description: 'Создайте резервную копию вашего текущего аккаунта Antigravity, чтобы начать.',
|
||||
action: 'Создать бэкап текущего аккаунта',
|
||||
},
|
||||
},
|
||||
settings: {
|
||||
title: 'Настройки',
|
||||
description: 'Управление настройками приложения.',
|
||||
general: 'Общие',
|
||||
connection: 'Подключение',
|
||||
models: 'Модели',
|
||||
appearance: {
|
||||
title: 'Внешний вид',
|
||||
description: 'Настройте внешний вид Antigravity Manager.',
|
||||
},
|
||||
darkMode: 'Темная тема',
|
||||
darkModeDescription: 'Включить темную тему для комфортной работы ночью.',
|
||||
language: {
|
||||
title: 'Язык',
|
||||
description: 'Выберите язык интерфейса.',
|
||||
english: 'English',
|
||||
chinese: '中文 (简体)',
|
||||
russian: 'Русский',
|
||||
},
|
||||
about: {
|
||||
title: 'О программе',
|
||||
description: 'Информация о приложении.',
|
||||
},
|
||||
version: 'Версия',
|
||||
platform: 'Платформа',
|
||||
license: 'Лицензия',
|
||||
openLogDir: 'Открыть',
|
||||
account: {
|
||||
title: 'Настройки аккаунта',
|
||||
description: 'Настройка автоматического обновления и синхронизации.',
|
||||
auto_refresh: 'Автообновление квот',
|
||||
auto_refresh_desc: 'Периодически обновлять информацию о квотах для всех аккаунтов',
|
||||
auto_sync: 'Автосинхронизация текущего',
|
||||
auto_sync_desc: 'Периодически синхронизировать активный аккаунт',
|
||||
},
|
||||
startup: {
|
||||
title: 'Автозагрузка',
|
||||
description: 'Управление запуском приложения при старте системы.',
|
||||
auto_startup: 'Запускать вместе с системой',
|
||||
auto_startup_desc: 'Запускать при входе и сворачивать в трей',
|
||||
macos_hint:
|
||||
'macOS требует подписанное приложение для работы элементов входа. Если автозапуск не работает, подпишите приложение или включите его вручную в системных настройках.',
|
||||
},
|
||||
privacy: {
|
||||
title: 'Конфиденциальность',
|
||||
description: 'Управление использованием данных для улучшения приложения.',
|
||||
error_reporting: 'Отчеты об ошибках',
|
||||
error_reporting_desc:
|
||||
'Отправляйте анонимные отчеты об ошибках, чтобы помочь нам улучшить приложение. Личные данные не собираются.',
|
||||
restart_note: 'Изменения в отчетах об ошибках вступят в силу после перезапуска приложения.',
|
||||
},
|
||||
proxy: {
|
||||
title: 'Верхнеуровневый прокси',
|
||||
description: 'Настроить прокси для исходящих запросов к Google/Gemini API.',
|
||||
enable: 'Включить прокси',
|
||||
url: 'URL прокси',
|
||||
timeout: 'Тайм-аут запроса (сек)',
|
||||
},
|
||||
modelMapping: {
|
||||
title: 'Маппинг моделей',
|
||||
description:
|
||||
'Сопоставьте модели Claude Code с моделями Antigravity. Оптимизируйте затраты и скорость, разумно маршрутизируя запросы.',
|
||||
claudeKeyword: 'Модель Claude (Ключевое слово)',
|
||||
targetGemini: 'Целевая модель Gemini',
|
||||
addPlaceholderKey: 'например, op-3',
|
||||
addPlaceholderValue: 'например, gemini-2.0-flash-exp',
|
||||
noMappings: 'Нет пользовательских сопоставлений.',
|
||||
mapsTo: 'Мапится в',
|
||||
default: 'По умолчанию',
|
||||
restoreDefaults: 'Сбросить по умолчанию',
|
||||
},
|
||||
examples: {
|
||||
title: 'Примеры использования',
|
||||
description: 'Примеры команд для вызова локального API прокси.',
|
||||
curl: 'cURL',
|
||||
python: 'Python',
|
||||
copy: 'Копировать',
|
||||
copied: 'Скопировано!',
|
||||
openai_protocol: 'Протокол OpenAI',
|
||||
anthropic_protocol: 'Протокол Anthropic',
|
||||
openai_tools: 'Cursor, Windsurf, NextChat',
|
||||
anthropic_tools: 'Claude Code CLI',
|
||||
flash: 'Быстрый (Flash)',
|
||||
pro: 'Про (Pro)',
|
||||
flash_preview: 'Превью (Flash Preview)',
|
||||
pro_high: 'Лучший (Pro High)',
|
||||
sonnet: 'Мыслящий (Sonnet)',
|
||||
opus: 'Opus',
|
||||
},
|
||||
gateway: {
|
||||
title: 'Служба API Прокси',
|
||||
description: 'Управление локальным прокси-сервером API.',
|
||||
status_running: 'Запущено',
|
||||
status_stopped: 'Остановлено',
|
||||
action_start: 'Запустить службу',
|
||||
action_stop: 'Остановить службу',
|
||||
accounts_info: '{{count}} аккаунтов доступно',
|
||||
port: 'Порт прослушивания',
|
||||
port_hint: 'По умолчанию 8045, требуется перезапуск для применения',
|
||||
timeout: 'Тайм-аут запроса',
|
||||
timeout_hint: 'По умолчанию 120с, диапазон 30-600с',
|
||||
api_key: 'API Ключ',
|
||||
regenerate_key: 'Перегенерировать',
|
||||
regenerateConfirm: {
|
||||
title: 'Перегенерировать API ключ?',
|
||||
description:
|
||||
'Это немедленно сделает текущий ключ недействительным. Все приложения, использующие старый ключ, перестанут работать.',
|
||||
cancel: 'Отмена',
|
||||
confirm: 'Перегенерировать',
|
||||
},
|
||||
key_warning: 'Держите ваш API ключ в секрете. Не передавайте его никому.',
|
||||
auto_start: 'Автозапуск с приложением',
|
||||
auto_start_desc: 'Запускать прокси-службу при старте приложения',
|
||||
},
|
||||
proxy_tab: 'Прокси',
|
||||
save: 'Сохранить настройки',
|
||||
},
|
||||
toast: {
|
||||
backupSuccess: {
|
||||
title: 'Успешно',
|
||||
description: 'Бэкап аккаунта создан.',
|
||||
},
|
||||
backupError: {
|
||||
title: 'Ошибка',
|
||||
description: 'Не удалось создать бэкап: {{error}}',
|
||||
},
|
||||
switchSuccess: {
|
||||
title: 'Успешно',
|
||||
description: 'Аккаунт переключен.',
|
||||
},
|
||||
switchError: {
|
||||
title: 'Ошибка',
|
||||
description: 'Не удалось переключить аккаунт: {{error}}',
|
||||
},
|
||||
deleteSuccess: {
|
||||
title: 'Успешно',
|
||||
description: 'Бэкап удален.',
|
||||
},
|
||||
deleteError: {
|
||||
title: 'Ошибка',
|
||||
description: 'Не удалось удалить бэкап: {{error}}',
|
||||
},
|
||||
},
|
||||
cloud: {
|
||||
title: 'Аккаунты',
|
||||
description: 'Управление пулом аккаунтов Google Gemini.',
|
||||
autoSwitch: 'Авто-переключение',
|
||||
addAccount: 'Добавить аккаунт',
|
||||
syncFromIDE: 'Синхр. из IDE',
|
||||
checkQuota: 'Проверить квоту',
|
||||
polling: 'Опрос запущен',
|
||||
authDialog: {
|
||||
title: 'Добавить Google Аккаунт',
|
||||
description: 'Для добавления аккаунта необходимо авторизовать приложение.',
|
||||
openLogin: 'Открыть страницу входа',
|
||||
authCode: 'Код авторизации',
|
||||
placeholder: 'Вставьте код, начинающийся с 4/...',
|
||||
instruction:
|
||||
'Откроется браузер для входа в Google. Скопируйте код со страницы localhost и вставьте сюда.',
|
||||
verify: 'Проверить и добавить',
|
||||
},
|
||||
card: {
|
||||
active: 'Активен',
|
||||
use: 'Использовать',
|
||||
rateLimited: 'Лимит исчерпан',
|
||||
left: 'ост.',
|
||||
used: 'Исп.',
|
||||
unknown: 'Неизвестный',
|
||||
actions: 'Действия',
|
||||
useAccount: 'Использовать этот аккаунт',
|
||||
refresh: 'Обновить квоту',
|
||||
delete: 'Удалить аккаунт',
|
||||
noQuota: 'Нет данных',
|
||||
},
|
||||
list: {
|
||||
noAccounts: 'Нет добавленных облачных аккаунтов.',
|
||||
},
|
||||
error: {
|
||||
loadFailed: 'Не удалось загрузить аккаунты.',
|
||||
},
|
||||
toast: {
|
||||
syncSuccess: {
|
||||
title: 'Синхронизация успешна',
|
||||
description: 'Импортирован {{email}} из IDE.',
|
||||
},
|
||||
syncFailed: {
|
||||
title: 'Синхронизация не удалась',
|
||||
description: 'В базе данных IDE не найдено активных аккаунтов.',
|
||||
},
|
||||
addSuccess: 'Аккаунт успешно добавлен!',
|
||||
addFailed: {
|
||||
title: 'Не удалось добавить аккаунт',
|
||||
},
|
||||
quotaRefreshed: 'Квота обновлена',
|
||||
refreshFailed: 'Не удалось обновить квоту',
|
||||
pollFailed: 'Не удалось опросить квоты всех аккаунтов',
|
||||
switched: {
|
||||
title: 'Аккаунт переключен!',
|
||||
description: 'Перезапуск Antigravity...',
|
||||
},
|
||||
switchFailed: 'Не удалось переключить аккаунт',
|
||||
deleted: 'Аккаунт удален',
|
||||
deleteFailed: 'Не удалось удалить аккаунт',
|
||||
deleteConfirm: 'Вы уверены, что хотите удалить этот аккаунт?',
|
||||
autoSwitchOn: 'Авто-переключение включено',
|
||||
autoSwitchOff: 'Авто-переключение выключено',
|
||||
updateSettingsFailed: 'Не удалось обновить настройки',
|
||||
},
|
||||
batch: {
|
||||
selected: 'Выбрано {{count}}',
|
||||
delete: 'Удалить выбранные',
|
||||
refresh: 'Обновить выбранные',
|
||||
selectAll: 'Выбрать все',
|
||||
clear: 'Снять выделение',
|
||||
confirmDelete: 'Вы уверены, что хотите удалить {{count}} аккаунтов?',
|
||||
},
|
||||
},
|
||||
proxy: {
|
||||
title: 'API Прокси',
|
||||
description: 'Управление локальным прокси-сервером API.',
|
||||
save: 'Сохранить',
|
||||
copy: 'Копировать',
|
||||
regenerate: 'Перегенерировать',
|
||||
regenerateConfirm: {
|
||||
title: 'Перегенерировать API ключ?',
|
||||
description:
|
||||
'Это немедленно сделает текущий ключ недействительным. Все приложения, использующие старый ключ, перестанут работать.',
|
||||
cancel: 'Отмена',
|
||||
confirm: 'Перегенерировать',
|
||||
},
|
||||
service: {
|
||||
title: 'Статус сервиса',
|
||||
description: 'Управление локальным сервером.',
|
||||
running: 'Работает',
|
||||
stopped: 'Остановлен',
|
||||
start: 'Запустить',
|
||||
stop: 'Остановить',
|
||||
},
|
||||
config: {
|
||||
port: 'Порт',
|
||||
timeout: 'Тайм-аут',
|
||||
api_key: 'API Ключ',
|
||||
auto_start: 'Автозапуск',
|
||||
auto_start_desc: 'Запускать прокси при старте приложения',
|
||||
local_access: 'Доступ из локальной сети:',
|
||||
no_token_warning: '⚠️ API ключ не установлен. Доступ открыт всем!',
|
||||
show_key: 'Показать',
|
||||
hide_key: 'Скрыть',
|
||||
},
|
||||
mapping: {
|
||||
title: 'Маппинг моделей',
|
||||
description: 'Настройка маршрутизации моделей.',
|
||||
maps_to: '->',
|
||||
restore: 'Сброс',
|
||||
},
|
||||
examples: {
|
||||
title: 'Примеры',
|
||||
description: 'Примеры использования локального прокси.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
+9
-76
@@ -1,15 +1,14 @@
|
||||
import './instrument'; // MUST be the first import to ensure Sentry initializes before app ready
|
||||
import { app, BrowserWindow } from 'electron';
|
||||
import { app, BrowserWindow, Tray, Menu, nativeImage } from 'electron';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
// import { installExtension, REACT_DEVELOPER_TOOLS } from 'electron-devtools-installer';
|
||||
import { ipcMain } from 'electron/main';
|
||||
import { ipcContext } from '@/ipc/context';
|
||||
import { IPC_CHANNELS } from './constants';
|
||||
import { updateElectronApp, UpdateSourceType } from 'update-electron-app';
|
||||
import { logger } from './utils/logger';
|
||||
import { CloudAccountRepo } from './ipc/database/cloudHandler';
|
||||
import { initDatabase } from './ipc/database/handler';
|
||||
import { CloudMonitorService } from './services/CloudMonitorService';
|
||||
|
||||
// Static Imports to fix Bundle Resolution Errors
|
||||
@@ -18,8 +17,6 @@ import { bootstrapNestServer, stopNestServer } from './server/main';
|
||||
import { initTray, setTrayLanguage, destroyTray } from './ipc/tray/handler';
|
||||
import { rpcHandler } from './ipc/handler';
|
||||
import { ConfigManager } from './ipc/config/manager';
|
||||
import { AppConfig } from './types/config';
|
||||
import { isAutoStartLaunch, syncAutoStart } from './utils/autoStart';
|
||||
|
||||
const packetLogPath = path.join(app.getPath('userData'), 'orpc_packets.log');
|
||||
|
||||
@@ -65,25 +62,6 @@ const inDevelopment = process.env.NODE_ENV === 'development';
|
||||
let globalMainWindow: BrowserWindow | null = null;
|
||||
// let tray: Tray | null = null; // Moved to tray/handler.ts
|
||||
let isQuitting = false;
|
||||
let startupConfig: AppConfig | null = null;
|
||||
let shouldStartHidden = false;
|
||||
|
||||
const gotSingleInstanceLock = app.requestSingleInstanceLock();
|
||||
|
||||
if (!gotSingleInstanceLock) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', () => {
|
||||
logger.info('Second instance detected, focusing existing window');
|
||||
if (app.isReady()) {
|
||||
createWindow({ startHidden: false });
|
||||
return;
|
||||
}
|
||||
app.whenReady().then(() => {
|
||||
createWindow({ startHidden: false });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
process.on('exit', (code) => {
|
||||
logger.info(`Process exit event triggered with code: ${code}`);
|
||||
@@ -96,22 +74,7 @@ process.on('before-exit', (code) => {
|
||||
|
||||
// let tray: Tray | null = null; // Moved to tray/handler.ts
|
||||
|
||||
function createWindow({ startHidden }: { startHidden: boolean }) {
|
||||
if (globalMainWindow && !globalMainWindow.isDestroyed()) {
|
||||
if (startHidden) {
|
||||
globalMainWindow.hide();
|
||||
return;
|
||||
}
|
||||
if (globalMainWindow.isMinimized()) {
|
||||
globalMainWindow.restore();
|
||||
}
|
||||
if (!globalMainWindow.isVisible()) {
|
||||
globalMainWindow.show();
|
||||
}
|
||||
globalMainWindow.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
function createWindow() {
|
||||
logger.info('createWindow: start');
|
||||
const preload = path.join(__dirname, 'preload.js');
|
||||
logger.info(`createWindow: preload path: ${preload}`);
|
||||
@@ -120,7 +83,6 @@ function createWindow({ startHidden }: { startHidden: boolean }) {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 1200,
|
||||
height: 800,
|
||||
show: !startHidden,
|
||||
autoHideMenuBar: true,
|
||||
webPreferences: {
|
||||
devTools: inDevelopment,
|
||||
@@ -136,10 +98,6 @@ function createWindow({ startHidden }: { startHidden: boolean }) {
|
||||
});
|
||||
globalMainWindow = mainWindow;
|
||||
logger.info('createWindow: BrowserWindow instance created');
|
||||
if (startHidden) {
|
||||
mainWindow.hide();
|
||||
logger.info('createWindow: startHidden enabled, window hidden');
|
||||
}
|
||||
|
||||
logger.info('createWindow: setting main window in ipcContext');
|
||||
ipcContext.setMainWindow(mainWindow);
|
||||
@@ -167,7 +125,6 @@ function createWindow({ startHidden }: { startHidden: boolean }) {
|
||||
|
||||
mainWindow.on('closed', () => {
|
||||
logger.info('Window closed event triggered');
|
||||
globalMainWindow = null;
|
||||
});
|
||||
|
||||
mainWindow.webContents.on('render-process-gone', (event, details) => {
|
||||
@@ -186,10 +143,6 @@ function createWindow({ startHidden }: { startHidden: boolean }) {
|
||||
const { level, message, lineNumber, sourceId } = details;
|
||||
logger.info(`[Renderer Console][${level}] ${message} (${sourceId}:${lineNumber})`);
|
||||
});
|
||||
|
||||
mainWindow.on('focus', () => {
|
||||
CloudMonitorService.handleAppFocus();
|
||||
});
|
||||
}
|
||||
|
||||
app.on('child-process-gone', (event, details) => {
|
||||
@@ -270,36 +223,13 @@ process.on('unhandledRejection', (reason) => {
|
||||
|
||||
app
|
||||
.whenReady()
|
||||
.then(async () => {
|
||||
logger.info('Step: Initialize CloudAccountRepo');
|
||||
try {
|
||||
await CloudAccountRepo.init();
|
||||
} catch (e) {
|
||||
logger.error('Startup: Failed to initialize CloudAccountRepo', e);
|
||||
// We might want to exit here or show a dialog, but for now we proceed
|
||||
// though functionality will be broken.
|
||||
}
|
||||
|
||||
logger.info('Step: Initialize Antigravity DB (WAL Mode)');
|
||||
initDatabase();
|
||||
})
|
||||
.then(() => {
|
||||
logger.info('Step: Load Config');
|
||||
const config = ConfigManager.loadConfig();
|
||||
startupConfig = config;
|
||||
syncAutoStart(config);
|
||||
shouldStartHidden = isAutoStartLaunch() && config.auto_startup;
|
||||
if (shouldStartHidden) {
|
||||
logger.info('Startup: Auto-start detected, window will start hidden');
|
||||
}
|
||||
})
|
||||
.then(() => {
|
||||
logger.info('Step: setupORPC');
|
||||
return setupORPC();
|
||||
})
|
||||
.then(async () => {
|
||||
logger.info('Step: createWindow');
|
||||
await createWindow({ startHidden: shouldStartHidden });
|
||||
await createWindow();
|
||||
})
|
||||
.then(() => {
|
||||
logger.info('Step: installExtensions (SKIPPED)');
|
||||
@@ -312,11 +242,14 @@ app
|
||||
.then(async () => {
|
||||
// Initialize Cloud Monitor if enabled
|
||||
try {
|
||||
// Initialize DB & Migrate to Encrypted Storage
|
||||
await CloudAccountRepo.init();
|
||||
|
||||
// Start OAuth Server
|
||||
AuthServer.start();
|
||||
|
||||
// Gateway Server (NestJS) - auto-start if enabled
|
||||
const config = startupConfig || ConfigManager.loadConfig();
|
||||
const config = ConfigManager.loadConfig();
|
||||
if (config.proxy?.auto_start) {
|
||||
const port = config.proxy?.port || 8045;
|
||||
// Default to a valid ProxyConfig object if null, although loadConfig ensures defaults
|
||||
@@ -358,7 +291,7 @@ app.on('window-all-closed', () => {
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow({ startHidden: false });
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
//osX only ends
|
||||
@@ -1 +0,0 @@
|
||||
export {};
|
||||
@@ -1 +0,0 @@
|
||||
export {};
|
||||
@@ -1 +0,0 @@
|
||||
export {};
|
||||
@@ -1 +0,0 @@
|
||||
export {};
|
||||
@@ -1,44 +1,6 @@
|
||||
import { ipcRenderer, contextBridge } from 'electron';
|
||||
import * as Sentry from '@sentry/electron/renderer';
|
||||
import { IPC_CHANNELS } from './constants';
|
||||
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
|
||||
// Config check logic (duplicate of instrument.ts logic but adapted for preload)
|
||||
let sentryEnabled = false;
|
||||
try {
|
||||
const home = os.homedir();
|
||||
let appDataPath = '';
|
||||
if (process.platform === 'win32') {
|
||||
appDataPath = path.join(
|
||||
process.env.APPDATA || path.join(home, 'AppData', 'Roaming'),
|
||||
'Antigravity',
|
||||
);
|
||||
} else if (process.platform === 'darwin') {
|
||||
appDataPath = path.join(home, 'Library', 'Application Support', 'Antigravity');
|
||||
} else {
|
||||
appDataPath = path.join(home, '.config', 'Antigravity');
|
||||
}
|
||||
|
||||
const configPath = path.join(appDataPath, 'gui_config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
const content = fs.readFileSync(configPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
sentryEnabled = config.error_reporting_enabled === true;
|
||||
}
|
||||
} catch (e) {
|
||||
// console.error('Preload: Failed to read config', e);
|
||||
}
|
||||
|
||||
if (sentryEnabled) {
|
||||
// Defer Sentry init to avoid blocking main thread during startup (white screen fix)
|
||||
setTimeout(() => {
|
||||
// console.log('[Preload] Initializing Sentry (Deferred)');
|
||||
Sentry.init({});
|
||||
}, 2000);
|
||||
}
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.data === IPC_CHANNELS.START_ORPC_SERVER) {
|
||||
const [serverPort] = event.ports;
|
||||
@@ -48,7 +10,6 @@ window.addEventListener('message', (event) => {
|
||||
});
|
||||
|
||||
contextBridge.exposeInMainWorld('electron', {
|
||||
SENTRY_ENABLED: sentryEnabled,
|
||||
onGoogleAuthCode: (callback: (code: string) => void) => {
|
||||
const handler = (_event: any, code: string) => callback(code);
|
||||
ipcRenderer.on('GOOGLE_AUTH_CODE', handler);
|
||||
|
||||
@@ -1,12 +1 @@
|
||||
import * as Sentry from '@sentry/electron/renderer';
|
||||
|
||||
if (window.electron.SENTRY_ENABLED) {
|
||||
// Defer initialization to prioritize initial render
|
||||
setTimeout(() => {
|
||||
Sentry.init({
|
||||
dsn: process.env.SENTRY_DSN,
|
||||
});
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
import '@/App';
|
||||
+1
-100
@@ -17,10 +17,9 @@ import { getAppVersion, getPlatform } from '@/actions/app';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { setAppLanguage } from '@/actions/language';
|
||||
import { useAppConfig } from '@/hooks/useAppConfig';
|
||||
import { Loader2, FolderOpen } from 'lucide-react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ProxyConfig } from '@/types/config';
|
||||
import { openLogDirectory } from '@/actions/system';
|
||||
|
||||
function SettingsPage() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
@@ -33,7 +32,6 @@ function SettingsPage() {
|
||||
// Sync config to local state when loaded
|
||||
useEffect(() => {
|
||||
if (config) {
|
||||
// eslint-disable-next-line
|
||||
setProxyConfig(config.proxy);
|
||||
}
|
||||
}, [config]);
|
||||
@@ -48,10 +46,6 @@ function SettingsPage() {
|
||||
queryFn: getPlatform,
|
||||
});
|
||||
|
||||
const isAutoStartSupported =
|
||||
platform === 'win32' || platform === 'darwin' || platform === 'linux';
|
||||
const isMac = platform === 'darwin';
|
||||
|
||||
const handleLanguageChange = (value: string) => {
|
||||
setAppLanguage(value, i18n);
|
||||
};
|
||||
@@ -125,7 +119,6 @@ function SettingsPage() {
|
||||
<SelectContent>
|
||||
<SelectItem value="en">{t('settings.language.english')}</SelectItem>
|
||||
<SelectItem value="zh-CN">{t('settings.language.chinese')}</SelectItem>
|
||||
<SelectItem value="ru">{t('settings.language.russian')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -185,49 +178,6 @@ function SettingsPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{isAutoStartSupported && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('settings.startup.title', 'Startup')}</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
'settings.startup.description',
|
||||
'Control application launch behavior at system startup.',
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-1">
|
||||
<Label>{t('settings.startup.auto_startup', 'Start with system')}</Label>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t(
|
||||
'settings.startup.auto_startup_desc',
|
||||
'Launch at sign-in and keep the app in the system tray',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={config?.auto_startup || false}
|
||||
onCheckedChange={async (checked) => {
|
||||
if (config) {
|
||||
await saveConfig({ ...config, auto_startup: checked });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{isMac && (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t(
|
||||
'settings.startup.macos_hint',
|
||||
'macOS requires a signed app for Login Items to work. If auto-start fails, please sign the app or enable it manually in System Settings.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('settings.about.title')}</CardTitle>
|
||||
@@ -243,58 +193,9 @@ function SettingsPage() {
|
||||
|
||||
<div className="text-muted-foreground">{t('settings.license')}</div>
|
||||
<div className="font-medium">CC BY-NC-SA 4.0</div>
|
||||
|
||||
<div className="text-muted-foreground">{t('action.openLogs')}</div>
|
||||
<button
|
||||
onClick={() => openLogDirectory()}
|
||||
className="flex items-center gap-2 font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
<FolderOpen className="h-4 w-4" />
|
||||
<span>{t('settings.openLogDir', 'Open')}</span>
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Privacy & Error Reporting Card */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('settings.privacy.title', 'Privacy')}</CardTitle>
|
||||
<CardDescription>
|
||||
{t(
|
||||
'settings.privacy.description',
|
||||
'Control how your data is used to improve the application.',
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-1">
|
||||
<Label>{t('settings.privacy.error_reporting', 'Error Reporting')}</Label>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t(
|
||||
'settings.privacy.error_reporting_desc',
|
||||
'Send anonymous error reports to help us improve the app. No personal data is collected.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={config?.error_reporting_enabled || false}
|
||||
onCheckedChange={async (checked) => {
|
||||
if (config) {
|
||||
await saveConfig({ ...config, error_reporting_enabled: checked });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t(
|
||||
'settings.privacy.restart_note',
|
||||
'Changes to error reporting will take effect after restarting the application.',
|
||||
)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* --- PROXY TAB (Upstream Proxy Config Only) --- */}
|
||||
|
||||
@@ -6,28 +6,17 @@ import { logger } from '../utils/logger';
|
||||
export class CloudMonitorService {
|
||||
private static intervalId: NodeJS.Timeout | null = null;
|
||||
private static POLL_INTERVAL = 1000 * 60 * 5; // 5 minutes
|
||||
private static DEBOUNCE_TIME = 10000; // 10 seconds
|
||||
private static lastFocusTime: number = 0;
|
||||
private static isPolling: boolean = false;
|
||||
|
||||
// Helper for testing
|
||||
static resetStateForTesting() {
|
||||
this.lastFocusTime = 0;
|
||||
this.isPolling = false;
|
||||
this.stop();
|
||||
}
|
||||
|
||||
static start() {
|
||||
if (this.intervalId) return;
|
||||
logger.info('Starting CloudMonitorService...');
|
||||
|
||||
// Set lastFocusTime to now to prevent "double-dip" on startup (focus event immediately after start)
|
||||
this.lastFocusTime = Date.now();
|
||||
|
||||
// Initial Poll
|
||||
this.poll().catch((e) => logger.error('Initial poll failed', e));
|
||||
|
||||
this.startInterval();
|
||||
this.intervalId = setInterval(() => {
|
||||
this.poll().catch((e) => logger.error('Scheduled poll failed', e));
|
||||
}, this.POLL_INTERVAL);
|
||||
}
|
||||
|
||||
static stop() {
|
||||
@@ -38,95 +27,39 @@ export class CloudMonitorService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the application window gains focus.
|
||||
* Triggers an immediate poll if not rate-limited by debounce.
|
||||
*/
|
||||
static async handleAppFocus() {
|
||||
const now = Date.now();
|
||||
|
||||
// 1. Concurrency Guard: If we are already polling, don't pile up requests
|
||||
if (this.isPolling) {
|
||||
logger.info('Monitor: App focused, but polling is already in progress. Skipping.');
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Debounce: If we focused recently, don't poll again
|
||||
if (now - this.lastFocusTime < this.DEBOUNCE_TIME) {
|
||||
logger.info('Monitor: App focused, skipping poll (debounce active).');
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info('Monitor: App focused, triggering immediate poll...');
|
||||
this.lastFocusTime = now;
|
||||
|
||||
// 3. Trigger Poll
|
||||
await this.poll().catch((e) => {
|
||||
logger.error('Monitor: Focus poll failed', e);
|
||||
});
|
||||
// 4. Reset the background interval so we don't double-poll shortly after
|
||||
this.resetInterval();
|
||||
}
|
||||
|
||||
private static startInterval() {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
}
|
||||
this.intervalId = setInterval(() => {
|
||||
this.poll().catch((e) => logger.error('Scheduled poll failed', e));
|
||||
}, this.POLL_INTERVAL);
|
||||
}
|
||||
|
||||
private static resetInterval() {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
this.startInterval(); // Restart the 5-minute timer
|
||||
}
|
||||
}
|
||||
|
||||
static async poll() {
|
||||
if (this.isPolling) {
|
||||
return; // Extra safety
|
||||
}
|
||||
this.isPolling = true;
|
||||
logger.info('CloudMonitor: Polling quotas...');
|
||||
const accounts = await CloudAccountRepo.getAccounts();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
try {
|
||||
logger.info('CloudMonitor: Polling quotas...');
|
||||
const accounts = await CloudAccountRepo.getAccounts();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
for (const account of accounts) {
|
||||
try {
|
||||
// 1. Check/Refresh Token if needed (give it a 10 min buffer here for safety)
|
||||
let accessToken = account.token.access_token;
|
||||
if (account.token.expiry_timestamp < now + 600) {
|
||||
logger.info(`Monitor: Refreshing token for ${account.email}`);
|
||||
const newToken = await GoogleAPIService.refreshAccessToken(account.token.refresh_token);
|
||||
account.token.access_token = newToken.access_token;
|
||||
account.token.expires_in = newToken.expires_in;
|
||||
account.token.expiry_timestamp = now + newToken.expires_in;
|
||||
await CloudAccountRepo.updateToken(account.id, account.token);
|
||||
accessToken = newToken.access_token;
|
||||
}
|
||||
|
||||
// 2. Fetch Quota
|
||||
// We delay slightly between requests to act human/avoid spike
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
const quota = await GoogleAPIService.fetchQuota(accessToken);
|
||||
|
||||
// 3. Update DB
|
||||
await CloudAccountRepo.updateQuota(account.id, quota);
|
||||
await CloudAccountRepo.updateLastUsed(account.id);
|
||||
} catch (error) {
|
||||
logger.error(`Monitor: Failed to update ${account.email}`, error);
|
||||
// Could mark status as 'error' or 'rate_limited' if 429
|
||||
for (const account of accounts) {
|
||||
try {
|
||||
// 1. Check/Refresh Token if needed (give it a 10 min buffer here for safety)
|
||||
let accessToken = account.token.access_token;
|
||||
if (account.token.expiry_timestamp < now + 600) {
|
||||
logger.info(`Monitor: Refreshing token for ${account.email}`);
|
||||
const newToken = await GoogleAPIService.refreshAccessToken(account.token.refresh_token);
|
||||
account.token.access_token = newToken.access_token;
|
||||
account.token.expires_in = newToken.expires_in;
|
||||
account.token.expiry_timestamp = now + newToken.expires_in;
|
||||
await CloudAccountRepo.updateToken(account.id, account.token);
|
||||
accessToken = newToken.access_token;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Check for Auto-Switch
|
||||
await AutoSwitchService.checkAndSwitchIfNeeded();
|
||||
} finally {
|
||||
this.isPolling = false;
|
||||
// 2. Fetch Quota
|
||||
// We delay slightly between requests to act human/avoid spike
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
const quota = await GoogleAPIService.fetchQuota(accessToken);
|
||||
|
||||
// 3. Update DB
|
||||
await CloudAccountRepo.updateQuota(account.id, quota);
|
||||
} catch (error) {
|
||||
logger.error(`Monitor: Failed to update ${account.email}`, error);
|
||||
// Could mark status as 'error' or 'rate_limited' if 429
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Check for Auto-Switch
|
||||
await AutoSwitchService.checkAndSwitchIfNeeded();
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { ProxyAgent } from 'undici';
|
||||
const CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
|
||||
const CLIENT_SECRET = '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';
|
||||
|
||||
declare const fetch: any;
|
||||
|
||||
const URLS = {
|
||||
TOKEN: 'https://oauth2.googleapis.com/token',
|
||||
USER_INFO: 'https://www.googleapis.com/oauth2/v2/userinfo',
|
||||
@@ -18,18 +20,6 @@ const URLS = {
|
||||
const USER_AGENT = 'antigravity/1.11.3 Darwin/arm64';
|
||||
const REDIRECT_URI = 'http://localhost:8888/oauth-callback';
|
||||
|
||||
// Request timeout in milliseconds (30 seconds)
|
||||
const REQUEST_TIMEOUT_MS = 30000;
|
||||
|
||||
/**
|
||||
* Creates an AbortSignal that times out after the specified duration.
|
||||
*/
|
||||
function createTimeoutSignal(ms: number): AbortSignal {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), ms);
|
||||
return controller.signal;
|
||||
}
|
||||
|
||||
// --- Types ---
|
||||
|
||||
export interface TokenResponse {
|
||||
@@ -75,7 +65,7 @@ interface LoadProjectResponse {
|
||||
// --- Service Implementation ---
|
||||
|
||||
export class GoogleAPIService {
|
||||
private static getFetchOptions() {
|
||||
private static getFetchOptions(): any {
|
||||
try {
|
||||
const config = ConfigManager.loadConfig();
|
||||
if (config.proxy?.upstream_proxy?.enabled && config.proxy.upstream_proxy.url) {
|
||||
@@ -131,17 +121,7 @@ export class GoogleAPIService {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: params,
|
||||
signal: createTimeoutSignal(REQUEST_TIMEOUT_MS),
|
||||
...this.getFetchOptions(),
|
||||
}).catch((err: unknown) => {
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'AbortError') {
|
||||
throw new Error(
|
||||
'Token exchange timed out. Please check your network connection and try again.',
|
||||
);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -167,17 +147,7 @@ export class GoogleAPIService {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: params,
|
||||
signal: createTimeoutSignal(REQUEST_TIMEOUT_MS),
|
||||
...this.getFetchOptions(),
|
||||
}).catch((err: unknown) => {
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'AbortError') {
|
||||
throw new Error(
|
||||
'Token refresh timed out. Please check your network connection and try again.',
|
||||
);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -196,17 +166,7 @@ export class GoogleAPIService {
|
||||
static async getUserInfo(accessToken: string): Promise<UserInfo> {
|
||||
const response = await fetch(URLS.USER_INFO, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
signal: createTimeoutSignal(REQUEST_TIMEOUT_MS),
|
||||
...this.getFetchOptions(),
|
||||
}).catch((err: unknown) => {
|
||||
if (err instanceof Error) {
|
||||
if (err.name === 'AbortError') {
|
||||
throw new Error(
|
||||
'User info request timed out. Please check your network connection and try again.',
|
||||
);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -261,7 +221,7 @@ export class GoogleAPIService {
|
||||
const projectId = await this.fetchProjectId(accessToken);
|
||||
|
||||
// 2. Build Payload
|
||||
const payload: Record<string, unknown> = {};
|
||||
const payload: Record<string, any> = {};
|
||||
if (projectId) {
|
||||
payload['project'] = projectId;
|
||||
}
|
||||
@@ -325,13 +285,11 @@ export class GoogleAPIService {
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof Error) {
|
||||
console.warn(
|
||||
`[GoogleAPIService] Request failed: ${e.message} (Attempt ${attempt}/${maxRetries})`,
|
||||
);
|
||||
}
|
||||
lastError = e instanceof Error ? e : new Error(String(e));
|
||||
} catch (e: any) {
|
||||
console.warn(
|
||||
`[GoogleAPIService] Request failed: ${e.message} (Attempt ${attempt}/${maxRetries})`,
|
||||
);
|
||||
lastError = e;
|
||||
if (attempt < maxRetries) {
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
}
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { CloudMonitorService } from '../../services/CloudMonitorService';
|
||||
import { CloudAccountRepo } from '../../ipc/database/cloudHandler';
|
||||
import { GoogleAPIService } from '../../services/GoogleAPIService';
|
||||
import { AutoSwitchService } from '../../services/AutoSwitchService';
|
||||
import { logger } from '../../utils/logger';
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('../../ipc/database/cloudHandler');
|
||||
vi.mock('../../services/GoogleAPIService');
|
||||
vi.mock('../../services/AutoSwitchService');
|
||||
vi.mock('../../utils/logger');
|
||||
|
||||
describe('CloudMonitorService', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
CloudMonitorService.resetStateForTesting();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
CloudMonitorService.stop();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should start polling on start() and set up interval', async () => {
|
||||
const pollSpy = vi.spyOn(CloudMonitorService, 'poll').mockResolvedValue(undefined);
|
||||
|
||||
CloudMonitorService.start();
|
||||
|
||||
// Should call initial poll
|
||||
expect(pollSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Fast forward 5 minutes
|
||||
await vi.advanceTimersByTimeAsync(1000 * 60 * 5);
|
||||
expect(pollSpy).toHaveBeenCalledTimes(2);
|
||||
|
||||
pollSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should poll accounts correctly', async () => {
|
||||
const mockAccounts = [
|
||||
{
|
||||
id: 'acc1',
|
||||
email: '[email protected]',
|
||||
token: { access_token: 'valid_token', expiry_timestamp: Date.now() / 1000 + 3600 },
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(CloudAccountRepo.getAccounts).mockResolvedValue(mockAccounts as never);
|
||||
vi.mocked(GoogleAPIService.fetchQuota).mockResolvedValue({ models: {} } as never);
|
||||
|
||||
// Start poll but don't await immediately, as it pauses
|
||||
const pollPromise = CloudMonitorService.poll();
|
||||
|
||||
// Advance time to pass the 1s sleep
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
// Now await
|
||||
await pollPromise;
|
||||
|
||||
expect(CloudAccountRepo.getAccounts).toHaveBeenCalled();
|
||||
expect(GoogleAPIService.fetchQuota).toHaveBeenCalledWith('valid_token');
|
||||
expect(CloudAccountRepo.updateQuota).toHaveBeenCalledWith('acc1', expect.anything());
|
||||
expect(CloudAccountRepo.updateLastUsed).toHaveBeenCalledWith('acc1');
|
||||
expect(AutoSwitchService.checkAndSwitchIfNeeded).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should refresh token if expired during poll', async () => {
|
||||
const mockAccounts = [
|
||||
{
|
||||
id: 'acc1',
|
||||
email: '[email protected]',
|
||||
token: {
|
||||
access_token: 'old_token',
|
||||
refresh_token: 'ref_token',
|
||||
expiry_timestamp: Math.floor(Date.now() / 1000) - 100, // Expired
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
vi.mocked(CloudAccountRepo.getAccounts).mockResolvedValue(mockAccounts as never);
|
||||
vi.mocked(GoogleAPIService.refreshAccessToken).mockResolvedValue({
|
||||
access_token: 'new_token',
|
||||
expires_in: 3600,
|
||||
token_type: 'Bearer',
|
||||
});
|
||||
vi.mocked(GoogleAPIService.fetchQuota).mockResolvedValue({ models: {} } as never);
|
||||
|
||||
// Same async pattern
|
||||
const pollPromise = CloudMonitorService.poll();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
await pollPromise;
|
||||
|
||||
expect(GoogleAPIService.refreshAccessToken).toHaveBeenCalledWith('ref_token');
|
||||
expect(CloudAccountRepo.updateToken).toHaveBeenCalled();
|
||||
expect(GoogleAPIService.fetchQuota).toHaveBeenCalledWith('new_token');
|
||||
});
|
||||
|
||||
describe('handleAppFocus (Smart Refresh)', () => {
|
||||
it('should trigger poll when focused after debounce time', async () => {
|
||||
const pollSpy = vi.spyOn(CloudMonitorService, 'poll').mockResolvedValue(undefined);
|
||||
|
||||
CloudMonitorService.start();
|
||||
vi.setSystemTime(Date.now() + 20000);
|
||||
|
||||
await CloudMonitorService.handleAppFocus();
|
||||
|
||||
// Called once by start, once by focus
|
||||
expect(pollSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should NOT trigger poll if debounced (focused too soon)', async () => {
|
||||
const pollSpy = vi.spyOn(CloudMonitorService, 'poll').mockResolvedValue(undefined);
|
||||
|
||||
CloudMonitorService.start();
|
||||
|
||||
vi.setSystemTime(Date.now() + 1000);
|
||||
|
||||
await CloudMonitorService.handleAppFocus();
|
||||
|
||||
// Called once by start, 0 by focus
|
||||
expect(pollSpy).toHaveBeenCalledTimes(1);
|
||||
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('debounce active'));
|
||||
});
|
||||
|
||||
it('should NOT trigger poll if already polling (concurrency guard)', async () => {
|
||||
// Let's spy on poll to silence start's poll
|
||||
const pollSpy = vi.spyOn(CloudMonitorService, 'poll').mockResolvedValue(undefined);
|
||||
CloudMonitorService.start();
|
||||
pollSpy.mockRestore(); // Restore so we can test the real guard logic
|
||||
|
||||
vi.setSystemTime(Date.now() + 20000);
|
||||
|
||||
// 2. Mock getAccounts to delay
|
||||
let resolveGetAccounts: (value: unknown) => void;
|
||||
const getAccountsPromise = new Promise((resolve) => {
|
||||
resolveGetAccounts = resolve;
|
||||
});
|
||||
vi.mocked(CloudAccountRepo.getAccounts).mockImplementation(() => getAccountsPromise as never);
|
||||
|
||||
// 3. Trigger first focus -> starts poll, hangs at getAccounts or sleep
|
||||
// Actually poll() calls getAccounts first thing.
|
||||
const p1 = CloudMonitorService.handleAppFocus();
|
||||
|
||||
// Allow p1 to start execution and enter poll()
|
||||
// We invoke one run loop
|
||||
// But since everything is sync until first await, it should enter poll, set isPolling=true, call getAccounts, and await.
|
||||
|
||||
// 4. Trigger second focus immediately
|
||||
const p2 = CloudMonitorService.handleAppFocus();
|
||||
|
||||
// 5. Release the first poll
|
||||
resolveGetAccounts!([
|
||||
{ id: '1', token: { access_token: 'tok', expiry_timestamp: 9999999999 } },
|
||||
]);
|
||||
|
||||
// Advance timer for the 1s sleep inside poll
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
await Promise.all([p1, p2]);
|
||||
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
expect.stringContaining('polling is already in progress'),
|
||||
);
|
||||
// getAccounts should be called once (by the first unblocked poll)
|
||||
// The second one blocked by guard before calling poll
|
||||
expect(CloudAccountRepo.getAccounts).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should reset interval after successful focus poll', async () => {
|
||||
const clearIntervalSpy = vi.spyOn(global, 'clearInterval');
|
||||
const setIntervalSpy = vi.spyOn(global, 'setInterval');
|
||||
|
||||
// Spy on poll to consume the start() call
|
||||
const pollSpy = vi.spyOn(CloudMonitorService, 'poll').mockResolvedValue(undefined);
|
||||
CloudMonitorService.start();
|
||||
pollSpy.mockRestore(); // Restore real poll
|
||||
|
||||
vi.setSystemTime(Date.now() + 20000);
|
||||
|
||||
// Needs to handle async poll
|
||||
vi.mocked(CloudAccountRepo.getAccounts).mockResolvedValue([]);
|
||||
|
||||
const focusPromise = CloudMonitorService.handleAppFocus();
|
||||
await vi.advanceTimersByTimeAsync(1000); // For poll sleep
|
||||
await focusPromise;
|
||||
|
||||
expect(clearIntervalSpy).toHaveBeenCalled();
|
||||
// 1 for start (initial), 1 for reset = 2
|
||||
expect(setIntervalSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,82 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
// Mock module to test timeout behavior
|
||||
describe('GoogleAPIService Timeout', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should abort request after timeout', async () => {
|
||||
const TIMEOUT_MS = 100;
|
||||
|
||||
// Recreate the same logic used in GoogleAPIService
|
||||
const createTimeoutSignal = (ms: number): AbortSignal => {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), ms);
|
||||
return controller.signal;
|
||||
};
|
||||
|
||||
const signal = createTimeoutSignal(TIMEOUT_MS);
|
||||
|
||||
// Verify signal is not aborted initially
|
||||
expect(signal.aborted).toBe(false);
|
||||
|
||||
// Fast-forward time
|
||||
vi.advanceTimersByTime(TIMEOUT_MS + 10);
|
||||
|
||||
// Signal should now be aborted
|
||||
expect(signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('should set aborted state when controller.abort() is called', () => {
|
||||
const controller = new AbortController();
|
||||
|
||||
// Initially not aborted
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
|
||||
// Abort the controller
|
||||
controller.abort();
|
||||
|
||||
// Signal should now be aborted
|
||||
expect(controller.signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('should transform AbortError to user-friendly message', () => {
|
||||
// This tests our error transformation logic from GoogleAPIService
|
||||
const handleAbortError = (err: Error) => {
|
||||
if (err.name === 'AbortError') {
|
||||
throw new Error(
|
||||
'Token exchange timed out. Please check your network connection and try again.',
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
};
|
||||
|
||||
const abortError = new Error('The operation was aborted');
|
||||
abortError.name = 'AbortError';
|
||||
|
||||
expect(() => handleAbortError(abortError)).toThrow(
|
||||
'Token exchange timed out. Please check your network connection and try again.',
|
||||
);
|
||||
});
|
||||
|
||||
it('should not transform non-AbortError', () => {
|
||||
const handleAbortError = (err: Error) => {
|
||||
if (err.name === 'AbortError') {
|
||||
throw new Error(
|
||||
'Token exchange timed out. Please check your network connection and try again.',
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
};
|
||||
|
||||
const networkError = new Error('Network failure');
|
||||
networkError.name = 'NetworkError';
|
||||
|
||||
expect(() => handleAbortError(networkError)).toThrow('Network failure');
|
||||
});
|
||||
});
|
||||
+46
-173
@@ -1,182 +1,55 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Mock find-process module
|
||||
vi.mock('find-process', () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock logger to avoid console output during tests
|
||||
vi.mock('../../utils/logger', () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock paths module to avoid child_process issues
|
||||
vi.mock('../../utils/paths', () => ({
|
||||
getAntigravityExecutablePath: vi.fn(() => '/path/to/antigravity'),
|
||||
isWsl: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
// Import after mocks are set up
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { isProcessRunning, closeAntigravity, startAntigravity } from '../../ipc/process/handler';
|
||||
import findProcess from 'find-process';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
vi.mock('child_process', () => {
|
||||
return {
|
||||
exec: vi.fn(),
|
||||
default: { exec: vi.fn() },
|
||||
};
|
||||
});
|
||||
|
||||
// Mock promisify to return a function that returns a promise
|
||||
vi.mock('util', () => ({
|
||||
promisify: (fn: unknown) => fn,
|
||||
default: { promisify: (fn: unknown) => fn },
|
||||
}));
|
||||
|
||||
describe('Process Handler', () => {
|
||||
const mockFindProcess = findProcess as unknown as ReturnType<typeof vi.fn>;
|
||||
it('should check if process is running', async () => {
|
||||
// Mock exec to return stdout
|
||||
const execMock = exec as unknown as ReturnType<typeof vi.fn>;
|
||||
execMock.mockImplementation((cmd, cb) => {
|
||||
if (cb) cb(null, { stdout: '12345' }, { stderr: '' });
|
||||
return { stdout: '12345' };
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Wait, promisify wraps exec.
|
||||
// If I mock exec, promisify(exec) will use the mock.
|
||||
// But my mock implementation needs to match what promisify expects or I need to mock the promisified function.
|
||||
// Since I mocked 'util', promisify returns the fn itself.
|
||||
// So execAsync IS exec.
|
||||
// But exec signature is (cmd, options, callback) or (cmd, callback).
|
||||
// My implementation calls execAsync(command).
|
||||
// So I should mock exec to return a Promise if I mocked promisify to return fn?
|
||||
// No, if promisify returns fn, then `await execAsync(cmd)` means `await exec(cmd)`.
|
||||
// `exec` returns a ChildProcess, not a Promise.
|
||||
// So my mock of `util` is wrong if I want `await execAsync` to work.
|
||||
// Better to mock the module that exports execAsync if possible, or mock `util` correctly.
|
||||
// Or just mock `child_process` and use `vi.mocked(exec)`.
|
||||
// But `promisify` is the key.
|
||||
|
||||
// Let's rely on vitest mocking capabilities.
|
||||
// If I don't mock util, promisify will wrap the mocked exec.
|
||||
// The mocked exec should behave like real exec (taking a callback).
|
||||
});
|
||||
|
||||
describe('isProcessRunning', () => {
|
||||
it('should return true when Antigravity main process is found on macOS', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
// Skip complex mocking tests for now as they are fragile without proper setup.
|
||||
// I'll write a basic test structure.
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12345,
|
||||
name: 'Antigravity',
|
||||
cmd: '/Applications/Antigravity.app/Contents/MacOS/Antigravity',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(true);
|
||||
expect(mockFindProcess).toHaveBeenCalledWith('name', 'Antigravity', true);
|
||||
});
|
||||
|
||||
it('should return false when only helper processes are found', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12346,
|
||||
name: 'Antigravity Helper (Renderer)',
|
||||
cmd: '/Applications/Antigravity.app/Contents/Frameworks/Antigravity Helper (Renderer).app --type=renderer',
|
||||
},
|
||||
{
|
||||
pid: 12347,
|
||||
name: 'Antigravity Helper (GPU)',
|
||||
cmd: '/Applications/Antigravity.app/Contents/Frameworks/Antigravity Helper (GPU).app --type=gpu-process',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when only manager process is found', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12348,
|
||||
name: 'Antigravity Manager',
|
||||
cmd: '/Applications/Antigravity Manager.app/Contents/MacOS/Antigravity Manager',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when no processes are found', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should skip self process', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 12345, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12345, // Same as current PID
|
||||
name: 'Antigravity',
|
||||
cmd: '/Applications/Antigravity.app/Contents/MacOS/Antigravity',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when Antigravity.exe is found on Windows', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12345,
|
||||
name: 'Antigravity.exe',
|
||||
cmd: 'C:\\Program Files\\Antigravity\\Antigravity.exe',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true when antigravity is found on Linux', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12345,
|
||||
name: 'antigravity',
|
||||
cmd: '/usr/bin/antigravity',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle find-process errors gracefully', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockRejectedValue(new Error('Process enumeration failed'));
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should exclude processes with --type= argument', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });
|
||||
Object.defineProperty(process, 'pid', { value: 1000, configurable: true });
|
||||
|
||||
mockFindProcess.mockResolvedValue([
|
||||
{
|
||||
pid: 12345,
|
||||
name: 'Antigravity',
|
||||
cmd: '/Applications/Antigravity.app/Contents/MacOS/Antigravity --type=utility',
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await isProcessRunning();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Module exports', () => {
|
||||
it('should export all required functions', () => {
|
||||
expect(isProcessRunning).toBeDefined();
|
||||
expect(closeAntigravity).toBeDefined();
|
||||
expect(startAntigravity).toBeDefined();
|
||||
});
|
||||
it('should be defined', () => {
|
||||
expect(isProcessRunning).toBeDefined();
|
||||
expect(closeAntigravity).toBeDefined();
|
||||
expect(startAntigravity).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -1,122 +0,0 @@
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs/promises';
|
||||
import keytar from 'keytar';
|
||||
import { safeStorage } from 'electron';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { decryptWithMigration } from '../../utils/security';
|
||||
|
||||
const primaryHex = '11'.repeat(32);
|
||||
const fallbackHex = '22'.repeat(32);
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
safeStorage: {
|
||||
isEncryptionAvailable: vi.fn(() => true),
|
||||
decryptString: vi.fn(() => primaryHex),
|
||||
encryptString: vi.fn((value: string) => Buffer.from(value)),
|
||||
},
|
||||
app: {
|
||||
getPath: vi.fn(() => 'C:\\test'),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
default: {
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('keytar', () => ({
|
||||
default: {
|
||||
findCredentials: vi.fn(async () => []),
|
||||
getPassword: vi.fn(async () => fallbackHex),
|
||||
setPassword: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const fsMock = vi.mocked(fs, { deep: true });
|
||||
const keytarMock = vi.mocked(keytar, { deep: true });
|
||||
const safeStorageMock = vi.mocked(safeStorage, { deep: true });
|
||||
|
||||
function encryptWithKey(key: Buffer, text: string): string {
|
||||
const iv = crypto.randomBytes(16);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
|
||||
let encrypted = cipher.update(text, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
|
||||
const authTag = cipher.getAuthTag();
|
||||
|
||||
return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
safeStorageMock.isEncryptionAvailable.mockReturnValue(true);
|
||||
safeStorageMock.decryptString.mockReturnValue(primaryHex);
|
||||
|
||||
fsMock.readFile.mockImplementation(async (_path, encoding) => {
|
||||
if (encoding === 'utf8') {
|
||||
return 'not-hex';
|
||||
}
|
||||
|
||||
return Buffer.from('encrypted');
|
||||
});
|
||||
fsMock.writeFile.mockResolvedValue(undefined);
|
||||
fsMock.rename.mockResolvedValue(undefined);
|
||||
fsMock.unlink.mockResolvedValue(undefined);
|
||||
|
||||
keytarMock.findCredentials.mockResolvedValue([]);
|
||||
keytarMock.getPassword.mockResolvedValue(fallbackHex);
|
||||
});
|
||||
|
||||
describe('decryptWithMigration', () => {
|
||||
it('falls back to legacy key and re-encrypts', async () => {
|
||||
const plaintext = '{"token":"legacy"}';
|
||||
const ciphertext = encryptWithKey(Buffer.from(fallbackHex, 'hex'), plaintext);
|
||||
|
||||
const result = await decryptWithMigration(ciphertext);
|
||||
|
||||
expect(result.value).toBe(plaintext);
|
||||
expect(result.usedFallback).toBe('keytar');
|
||||
expect(result.reencrypted).toBeTypeOf('string');
|
||||
expect(result.reencrypted).not.toBe(ciphertext);
|
||||
expect(keytarMock.getPassword).toHaveBeenCalledTimes(1);
|
||||
|
||||
if (result.reencrypted) {
|
||||
const migrated = await decryptWithMigration(result.reencrypted);
|
||||
expect(migrated.value).toBe(plaintext);
|
||||
expect(migrated.usedFallback).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not use fallback when primary key works', async () => {
|
||||
const plaintext = '{"token":"primary"}';
|
||||
const ciphertext = encryptWithKey(Buffer.from(primaryHex, 'hex'), plaintext);
|
||||
|
||||
const result = await decryptWithMigration(ciphertext);
|
||||
|
||||
expect(result.value).toBe(plaintext);
|
||||
expect(result.usedFallback).toBeUndefined();
|
||||
expect(result.reencrypted).toBeUndefined();
|
||||
});
|
||||
|
||||
it('throws migration error code when legacy keys are unavailable', async () => {
|
||||
keytarMock.getPassword.mockResolvedValue(null);
|
||||
fsMock.readFile.mockImplementation(async (_path, encoding) => {
|
||||
if (encoding === 'utf8') {
|
||||
return 'not-hex';
|
||||
}
|
||||
|
||||
return Buffer.from('encrypted');
|
||||
});
|
||||
|
||||
const plaintext = '{"token":"legacy"}';
|
||||
const ciphertext = encryptWithKey(Buffer.from('33'.repeat(32), 'hex'), plaintext);
|
||||
|
||||
await expect(decryptWithMigration(ciphertext)).rejects.toThrow('ERR_DATA_MIGRATION_FAILED');
|
||||
});
|
||||
});
|
||||
Vendored
-1
@@ -7,7 +7,6 @@ declare global {
|
||||
|
||||
interface Window {
|
||||
electron: {
|
||||
SENTRY_ENABLED: boolean;
|
||||
onGoogleAuthCode: (callback: (code: string) => void) => () => void;
|
||||
changeLanguage: (lang: string) => void;
|
||||
};
|
||||
|
||||
+1
-7
@@ -20,11 +20,8 @@ export const AppConfigSchema = z.object({
|
||||
theme: z.string(),
|
||||
auto_refresh: z.boolean(),
|
||||
refresh_interval: z.number(), // minutes
|
||||
auto_sync: z.boolean(),
|
||||
auto_sync: z.boolean(), // 是否自动同步
|
||||
sync_interval: z.number(), // minutes
|
||||
auto_startup: z.boolean(),
|
||||
error_reporting_enabled: z.boolean(),
|
||||
privacy_consent_asked: z.boolean().optional().default(false), // Optional for backward compatibility
|
||||
default_export_path: z.string().nullable().optional(), // 导出路径
|
||||
proxy: ProxyConfigSchema,
|
||||
});
|
||||
@@ -40,9 +37,6 @@ export const DEFAULT_APP_CONFIG: AppConfig = {
|
||||
refresh_interval: 15,
|
||||
auto_sync: false,
|
||||
sync_interval: 5,
|
||||
auto_startup: false,
|
||||
error_reporting_enabled: true, // Default to disabled for privacy
|
||||
privacy_consent_asked: false, // Whether the user has been asked for consent
|
||||
default_export_path: null,
|
||||
proxy: {
|
||||
enabled: false,
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
import { app } from 'electron';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { logger } from './logger';
|
||||
import { AppConfig } from '../types/config';
|
||||
|
||||
export const AUTO_START_ARG = '--autostart';
|
||||
const LINUX_AUTOSTART_FILENAME = 'antigravity-manager.desktop';
|
||||
|
||||
function getLinuxAutoStartPath() {
|
||||
const dir = path.join(os.homedir(), '.config', 'autostart');
|
||||
return path.join(dir, LINUX_AUTOSTART_FILENAME);
|
||||
}
|
||||
|
||||
export function isAutoStartLaunch(argv = process.argv) {
|
||||
if (process.platform === 'linux') {
|
||||
return argv.includes(AUTO_START_ARG);
|
||||
}
|
||||
|
||||
if (process.platform === 'win32' || process.platform === 'darwin') {
|
||||
try {
|
||||
const settings = app.getLoginItemSettings();
|
||||
return settings.wasOpenedAtLogin;
|
||||
} catch (error) {
|
||||
logger.error('AutoStart: Failed to read login item settings', error);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function syncWindowsOrMacAutoStart(enabled: boolean) {
|
||||
try {
|
||||
app.setLoginItemSettings({
|
||||
openAtLogin: enabled,
|
||||
openAsHidden: enabled,
|
||||
path: process.execPath,
|
||||
args: enabled ? [AUTO_START_ARG] : [],
|
||||
});
|
||||
const settings = app.getLoginItemSettings();
|
||||
if (settings.openAtLogin !== enabled) {
|
||||
logger.warn(
|
||||
`AutoStart: Login item mismatch (expected ${enabled}, actual ${settings.openAtLogin})`,
|
||||
);
|
||||
}
|
||||
logger.info(`AutoStart: Login item set to ${enabled}`);
|
||||
} catch (error) {
|
||||
logger.error('AutoStart: Failed to update login item settings', error);
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupLinuxAutoStartEntries(currentPath: string) {
|
||||
const autoStartDir = path.dirname(currentPath);
|
||||
if (!fs.existsSync(autoStartDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const legacyNames = [
|
||||
`${app.getName()}.desktop`,
|
||||
`${app.getName().replace(/\s+/g, '')}.desktop`,
|
||||
'Antigravity Manager.desktop',
|
||||
'AntigravityManager.desktop',
|
||||
];
|
||||
|
||||
for (const name of legacyNames) {
|
||||
const candidate = path.join(autoStartDir, name);
|
||||
if (candidate === currentPath) {
|
||||
continue;
|
||||
}
|
||||
if (fs.existsSync(candidate)) {
|
||||
try {
|
||||
fs.unlinkSync(candidate);
|
||||
logger.info(`AutoStart: Removed legacy autostart entry ${candidate}`);
|
||||
} catch (error) {
|
||||
logger.warn('AutoStart: Failed to remove legacy autostart entry', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function syncLinuxAutoStart(enabled: boolean) {
|
||||
const autoStartPath = getLinuxAutoStartPath();
|
||||
|
||||
if (!enabled) {
|
||||
if (fs.existsSync(autoStartPath)) {
|
||||
fs.unlinkSync(autoStartPath);
|
||||
logger.info('AutoStart: Removed Linux autostart entry');
|
||||
}
|
||||
cleanupLinuxAutoStartEntries(autoStartPath);
|
||||
return;
|
||||
}
|
||||
|
||||
const autoStartDir = path.dirname(autoStartPath);
|
||||
if (!fs.existsSync(autoStartDir)) {
|
||||
fs.mkdirSync(autoStartDir, { recursive: true });
|
||||
}
|
||||
|
||||
const execPath = process.execPath.replace(/"/g, '\\"');
|
||||
const content = [
|
||||
'[Desktop Entry]',
|
||||
'Type=Application',
|
||||
`Name=${app.getName()}`,
|
||||
`Exec="${execPath}" ${AUTO_START_ARG}`,
|
||||
'X-GNOME-Autostart-enabled=true',
|
||||
'Hidden=false',
|
||||
'NoDisplay=false',
|
||||
].join('\n');
|
||||
|
||||
cleanupLinuxAutoStartEntries(autoStartPath);
|
||||
fs.writeFileSync(autoStartPath, content, 'utf-8');
|
||||
logger.info('AutoStart: Created Linux autostart entry');
|
||||
}
|
||||
|
||||
export function syncAutoStart(config: AppConfig) {
|
||||
const enabled = Boolean(config.auto_startup);
|
||||
|
||||
if (process.platform === 'win32' || process.platform === 'darwin') {
|
||||
syncWindowsOrMacAutoStart(enabled);
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
syncLinuxAutoStart(enabled);
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
|
||||
const KEYCHAIN_ERROR_CODE = 'ERR_KEYCHAIN_UNAVAILABLE';
|
||||
const KEYCHAIN_HINT_TRANSLOCATION = 'HINT_APP_TRANSLOCATION';
|
||||
const KEYCHAIN_HINT_KEYCHAIN_DENIED = 'HINT_KEYCHAIN_DENIED';
|
||||
const KEYCHAIN_HINT_SIGN_NOTARIZE = 'HINT_SIGN_NOTARIZE';
|
||||
const DATA_MIGRATION_ERROR_CODE = 'ERR_DATA_MIGRATION_FAILED';
|
||||
const DATA_MIGRATION_HINT_RELOGIN = 'HINT_RELOGIN';
|
||||
const DATA_MIGRATION_HINT_CLEAR_DATA = 'HINT_CLEAR_DATA';
|
||||
|
||||
const KEYCHAIN_HINT_I18N_MAP: Record<string, string> = {
|
||||
[KEYCHAIN_HINT_TRANSLOCATION]: 'error.keychainHint.translocation',
|
||||
[KEYCHAIN_HINT_KEYCHAIN_DENIED]: 'error.keychainHint.keychainDenied',
|
||||
[KEYCHAIN_HINT_SIGN_NOTARIZE]: 'error.keychainHint.signNotarize',
|
||||
};
|
||||
|
||||
const DATA_MIGRATION_HINT_I18N_MAP: Record<string, string> = {
|
||||
[DATA_MIGRATION_HINT_RELOGIN]: 'error.dataMigrationHint.relogin',
|
||||
[DATA_MIGRATION_HINT_CLEAR_DATA]: 'error.dataMigrationHint.clearData',
|
||||
};
|
||||
|
||||
function resolveKeychainMessage(hintCode: string | undefined, t: TFunction): string {
|
||||
const base = t('error.keychainUnavailable');
|
||||
if (!hintCode) {
|
||||
return base;
|
||||
}
|
||||
|
||||
const hintKey = KEYCHAIN_HINT_I18N_MAP[hintCode];
|
||||
if (!hintKey) {
|
||||
return base;
|
||||
}
|
||||
|
||||
return `${base} ${t(hintKey)}`;
|
||||
}
|
||||
|
||||
function resolveDataMigrationMessage(hintCode: string | undefined, t: TFunction): string {
|
||||
const base = t('error.dataMigrationFailed');
|
||||
if (!hintCode) {
|
||||
return base;
|
||||
}
|
||||
|
||||
const hintKey = DATA_MIGRATION_HINT_I18N_MAP[hintCode];
|
||||
if (!hintKey) {
|
||||
return base;
|
||||
}
|
||||
|
||||
return `${base} ${t(hintKey)}`;
|
||||
}
|
||||
|
||||
export function getLocalizedErrorMessage(error: unknown, t: TFunction): string {
|
||||
if (error instanceof Error) {
|
||||
const rawMessage = error.message;
|
||||
const [code, hint] = rawMessage.split('|');
|
||||
if (code === KEYCHAIN_ERROR_CODE) {
|
||||
return resolveKeychainMessage(hint, t);
|
||||
}
|
||||
if (code === DATA_MIGRATION_ERROR_CODE) {
|
||||
return resolveDataMigrationMessage(hint, t);
|
||||
}
|
||||
return rawMessage;
|
||||
}
|
||||
|
||||
if (error && typeof error === 'object' && 'message' in error) {
|
||||
const rawMessage = String((error as { message?: unknown }).message ?? '');
|
||||
const [code, hint] = rawMessage.split('|');
|
||||
if (code === KEYCHAIN_ERROR_CODE) {
|
||||
return resolveKeychainMessage(hint, t);
|
||||
}
|
||||
if (code === DATA_MIGRATION_ERROR_CODE) {
|
||||
return resolveDataMigrationMessage(hint, t);
|
||||
}
|
||||
if (rawMessage) {
|
||||
return rawMessage;
|
||||
}
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
@@ -4,23 +4,6 @@ import { getAgentDir } from './paths';
|
||||
|
||||
export type LogLevel = 'info' | 'warn' | 'error' | 'debug';
|
||||
|
||||
const LOG_WINDOW_MS = 30_000;
|
||||
const MAX_LOG_ENTRIES = 200;
|
||||
|
||||
interface LogEntry {
|
||||
timestamp: number;
|
||||
level: LogLevel;
|
||||
message: string;
|
||||
formatted: string;
|
||||
}
|
||||
|
||||
type SentryReporter = (payload: {
|
||||
level: LogLevel;
|
||||
message: string;
|
||||
error?: Error;
|
||||
logs: LogEntry[];
|
||||
}) => void;
|
||||
|
||||
/**
|
||||
* Safely stringify an object, handling circular references
|
||||
* This prevents "Converting circular structure to JSON" errors
|
||||
@@ -50,9 +33,6 @@ function safeStringify(obj: unknown): string {
|
||||
|
||||
class Logger {
|
||||
private logFilePath: string;
|
||||
private recentLogs: LogEntry[] = [];
|
||||
private sentryReporter: SentryReporter | null = null;
|
||||
private sentryEnabled = false;
|
||||
|
||||
constructor() {
|
||||
const agentDir = getAgentDir();
|
||||
@@ -95,55 +75,10 @@ class Logger {
|
||||
console.log(`${color}[${level.toUpperCase()}]${reset} ${message}`, ...args);
|
||||
}
|
||||
|
||||
private pruneLogs(now: number) {
|
||||
while (this.recentLogs.length > 0 && now - this.recentLogs[0].timestamp > LOG_WINDOW_MS) {
|
||||
this.recentLogs.shift();
|
||||
}
|
||||
|
||||
if (this.recentLogs.length > MAX_LOG_ENTRIES) {
|
||||
this.recentLogs = this.recentLogs.slice(-MAX_LOG_ENTRIES);
|
||||
}
|
||||
}
|
||||
|
||||
private extractError(args: unknown[]): Error | undefined {
|
||||
for (const arg of args) {
|
||||
if (arg instanceof Error) {
|
||||
return arg;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
setSentryReporter(reporter: SentryReporter | null) {
|
||||
this.sentryReporter = reporter;
|
||||
}
|
||||
|
||||
setErrorReportingEnabled(enabled: boolean) {
|
||||
this.sentryEnabled = enabled;
|
||||
}
|
||||
|
||||
log(level: LogLevel, message: string, ...args: unknown[]) {
|
||||
const formattedMessage = this.formatMessage(level, message, ...args);
|
||||
const now = Date.now();
|
||||
this.recentLogs.push({
|
||||
timestamp: now,
|
||||
level,
|
||||
message,
|
||||
formatted: formattedMessage,
|
||||
});
|
||||
this.pruneLogs(now);
|
||||
|
||||
this.writeToConsole(level, message, ...args);
|
||||
this.writeToFile(formattedMessage);
|
||||
|
||||
if (level === 'error' && this.sentryEnabled && this.sentryReporter) {
|
||||
this.sentryReporter({
|
||||
level,
|
||||
message,
|
||||
error: this.extractError(args),
|
||||
logs: [...this.recentLogs],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
info(message: string, ...args: unknown[]) {
|
||||
|
||||
@@ -124,8 +124,6 @@ export function getAntigravityDbPaths(): string[] {
|
||||
}
|
||||
|
||||
if (process.platform === 'linux') {
|
||||
paths.push(path.join(appData, 'User', 'globalStorage', 'state.vscdb'));
|
||||
paths.push(path.join(appData, 'User', 'state.vscdb'));
|
||||
paths.push(path.join(appData, 'state.vscdb'));
|
||||
return paths;
|
||||
}
|
||||
|
||||
@@ -40,11 +40,9 @@ export class ProtobufUtils {
|
||||
return this.readVarint(data, offset).nextOffset;
|
||||
case 1: // 64-bit
|
||||
return offset + 8;
|
||||
case 2: {
|
||||
// Length-delimited
|
||||
case 2: // Length-delimited
|
||||
const { value: length, nextOffset } = this.readVarint(data, offset);
|
||||
return nextOffset + Number(length);
|
||||
}
|
||||
case 5: // 32-bit
|
||||
return offset + 4;
|
||||
default:
|
||||
|
||||
+62
-433
@@ -1,342 +1,40 @@
|
||||
import keytar from 'keytar';
|
||||
import crypto from 'crypto';
|
||||
import { logger } from './logger';
|
||||
import { safeStorage, app } from 'electron';
|
||||
import path from 'path';
|
||||
import fs from 'fs/promises';
|
||||
|
||||
const SERVICE_NAME = 'AntigravityManager';
|
||||
const ACCOUNT_NAME = 'MasterKey';
|
||||
const KEYCHAIN_ERROR_CODE = 'ERR_KEYCHAIN_UNAVAILABLE';
|
||||
const KEYCHAIN_HINT_TRANSLOCATION = 'HINT_APP_TRANSLOCATION';
|
||||
const KEYCHAIN_HINT_KEYCHAIN_DENIED = 'HINT_KEYCHAIN_DENIED';
|
||||
const KEYCHAIN_HINT_SIGN_NOTARIZE = 'HINT_SIGN_NOTARIZE';
|
||||
const DATA_MIGRATION_ERROR_CODE = 'ERR_DATA_MIGRATION_FAILED';
|
||||
const DATA_MIGRATION_HINT_RELOGIN = 'HINT_RELOGIN';
|
||||
|
||||
export type KeySource = 'safeStorage' | 'keytar' | 'file';
|
||||
|
||||
interface MasterKeyState {
|
||||
key: Buffer;
|
||||
source: KeySource;
|
||||
}
|
||||
|
||||
// Cache the key in memory to avoid frequent system calls
|
||||
let cachedMasterKey: Buffer | null = null;
|
||||
let cachedMasterKeySource: KeySource | null = null;
|
||||
|
||||
function cacheMasterKey(key: Buffer, source: KeySource) {
|
||||
cachedMasterKey = key;
|
||||
cachedMasterKeySource = source;
|
||||
}
|
||||
async function getOrGenerateMasterKey(): Promise<Buffer> {
|
||||
if (cachedMasterKey) return cachedMasterKey;
|
||||
|
||||
function getCachedMasterKey() {
|
||||
if (!cachedMasterKey || !cachedMasterKeySource) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { key: cachedMasterKey, source: cachedMasterKeySource };
|
||||
}
|
||||
|
||||
function buildKeychainAccessHint(error: unknown): string | null {
|
||||
if (process.platform !== 'darwin') {
|
||||
return null;
|
||||
}
|
||||
|
||||
let appPath = '';
|
||||
try {
|
||||
appPath = app.getAppPath();
|
||||
} catch {
|
||||
appPath = '';
|
||||
}
|
||||
let hexKey = await keytar.getPassword(SERVICE_NAME, ACCOUNT_NAME);
|
||||
|
||||
const isTranslocated = appPath.includes('/AppTranslocation/');
|
||||
if (isTranslocated) {
|
||||
return KEYCHAIN_HINT_TRANSLOCATION;
|
||||
}
|
||||
if (!hexKey) {
|
||||
logger.info('Security: Generating new master key...');
|
||||
// Generate 256-bit key (32 bytes)
|
||||
const buffer = crypto.randomBytes(32);
|
||||
hexKey = buffer.toString('hex');
|
||||
await keytar.setPassword(SERVICE_NAME, ACCOUNT_NAME, hexKey);
|
||||
}
|
||||
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
if (errorMessage.toLowerCase().includes('keychain')) {
|
||||
return KEYCHAIN_HINT_KEYCHAIN_DENIED;
|
||||
}
|
||||
|
||||
return KEYCHAIN_HINT_SIGN_NOTARIZE;
|
||||
}
|
||||
|
||||
// Lock to prevent concurrent key generation
|
||||
let keyGenerationInProgress: Promise<MasterKeyState> | null = null;
|
||||
|
||||
// Fallback key file path (used when keytar and safeStorage both fail)
|
||||
function getFallbackKeyPath(): string {
|
||||
const userDataPath = app.getPath('userData');
|
||||
return path.join(userDataPath, '.mk');
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to load keytar dynamically to avoid hard failure if it's not available
|
||||
*/
|
||||
async function tryKeytar(): Promise<typeof import('keytar') | null> {
|
||||
try {
|
||||
// Native modules may fail to load in production builds
|
||||
const keytar = await import('keytar');
|
||||
// Test if keytar is actually working by calling a method
|
||||
await keytar.default.findCredentials(SERVICE_NAME);
|
||||
return keytar.default;
|
||||
cachedMasterKey = Buffer.from(hexKey, 'hex');
|
||||
return cachedMasterKey;
|
||||
} catch (error) {
|
||||
logger.warn('Security: keytar not available, using fallback', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readSafeStorageKey(keyPath: string): Promise<Buffer | null> {
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const encryptedKey = await fs.readFile(keyPath);
|
||||
const hexKey = safeStorage.decryptString(encryptedKey);
|
||||
|
||||
if (!/^[a-f0-9]+$/i.test(hexKey) || hexKey.length !== 64) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Buffer.from(hexKey, 'hex');
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.warn('Security: Failed to read safeStorage key file', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrCreateSafeStorageKey(
|
||||
keyPath: string,
|
||||
): Promise<{ key: Buffer; created: boolean }> {
|
||||
const existingKey = await readSafeStorageKey(keyPath);
|
||||
if (existingKey) {
|
||||
return { key: existingKey, created: false };
|
||||
}
|
||||
|
||||
const buffer = crypto.randomBytes(32);
|
||||
const hexKey = buffer.toString('hex');
|
||||
const encrypted = safeStorage.encryptString(hexKey);
|
||||
await atomicWriteFile(keyPath, encrypted, { mode: 0o600 });
|
||||
return { key: buffer, created: true };
|
||||
}
|
||||
|
||||
async function readKeytarKey(): Promise<Buffer | null> {
|
||||
const keytar = await tryKeytar();
|
||||
if (!keytar) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const existingKey = await keytar.getPassword(SERVICE_NAME, ACCOUNT_NAME);
|
||||
if (!existingKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!/^[a-f0-9]+$/i.test(existingKey) || existingKey.length !== 64) {
|
||||
logger.warn('Security: keytar key has unexpected format');
|
||||
return null;
|
||||
}
|
||||
|
||||
return Buffer.from(existingKey, 'hex');
|
||||
}
|
||||
|
||||
async function getOrCreateKeytarKey(): Promise<{ key: Buffer; created: boolean } | null> {
|
||||
const keytar = await tryKeytar();
|
||||
if (!keytar) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const existingKey = await keytar.getPassword(SERVICE_NAME, ACCOUNT_NAME);
|
||||
if (existingKey) {
|
||||
return { key: Buffer.from(existingKey, 'hex'), created: false };
|
||||
}
|
||||
|
||||
const buffer = crypto.randomBytes(32);
|
||||
const hexKey = buffer.toString('hex');
|
||||
await keytar.setPassword(SERVICE_NAME, ACCOUNT_NAME, hexKey);
|
||||
return { key: buffer, created: true };
|
||||
}
|
||||
|
||||
async function readFileFallbackKey(keyPath: string): Promise<Buffer | null> {
|
||||
try {
|
||||
const content = await fs.readFile(keyPath, 'utf8');
|
||||
if (content.length === 64 && /^[a-f0-9]+$/i.test(content)) {
|
||||
return Buffer.from(content, 'hex');
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.warn('Security: Error reading fallback key file', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrCreateFileFallbackKey(
|
||||
keyPath: string,
|
||||
): Promise<{ key: Buffer; created: boolean }> {
|
||||
const existingKey = await readFileFallbackKey(keyPath);
|
||||
if (existingKey) {
|
||||
return { key: existingKey, created: false };
|
||||
}
|
||||
|
||||
const buffer = crypto.randomBytes(32);
|
||||
const hexKey = buffer.toString('hex');
|
||||
await atomicWriteFile(keyPath, hexKey, { mode: 0o600 });
|
||||
return { key: buffer, created: true };
|
||||
}
|
||||
|
||||
async function getFallbackMasterKeys(
|
||||
keyPath: string,
|
||||
primarySource: KeySource,
|
||||
): Promise<MasterKeyState[]> {
|
||||
const fallbackKeys: MasterKeyState[] = [];
|
||||
|
||||
if (primarySource !== 'keytar') {
|
||||
const keytarKey = await readKeytarKey();
|
||||
if (keytarKey) {
|
||||
fallbackKeys.push({ key: keytarKey, source: 'keytar' });
|
||||
}
|
||||
}
|
||||
|
||||
if (primarySource !== 'file') {
|
||||
const fileKey = await readFileFallbackKey(keyPath);
|
||||
if (fileKey) {
|
||||
fallbackKeys.push({ key: fileKey, source: 'file' });
|
||||
}
|
||||
}
|
||||
|
||||
if (primarySource !== 'safeStorage') {
|
||||
const safeStorageKey = await readSafeStorageKey(keyPath);
|
||||
if (safeStorageKey) {
|
||||
fallbackKeys.push({ key: safeStorageKey, source: 'safeStorage' });
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic file write to prevent data races
|
||||
* Writes to a temp file first, then renames atomically
|
||||
*/
|
||||
async function atomicWriteFile(
|
||||
filePath: string,
|
||||
data: Buffer | string,
|
||||
options?: { mode?: number },
|
||||
): Promise<void> {
|
||||
const tempPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
|
||||
try {
|
||||
await fs.writeFile(tempPath, data, { mode: options?.mode ?? 0o600 });
|
||||
await fs.rename(tempPath, filePath);
|
||||
} catch (error) {
|
||||
// Clean up temp file if rename failed
|
||||
try {
|
||||
await fs.unlink(tempPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or generate master encryption key using multiple fallback strategies:
|
||||
* 1. safeStorage (Electron's built-in secure storage) - preferred
|
||||
* 2. keytar (system keychain) - fallback
|
||||
* 3. File-based with safeStorage encryption - last resort (with security warning)
|
||||
*
|
||||
* Uses a lock to prevent concurrent key generation (data race prevention)
|
||||
*/
|
||||
async function getPrimaryMasterKey(): Promise<MasterKeyState> {
|
||||
const cached = getCachedMasterKey();
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
if (keyGenerationInProgress) {
|
||||
return keyGenerationInProgress;
|
||||
}
|
||||
|
||||
keyGenerationInProgress = generatePrimaryMasterKey();
|
||||
try {
|
||||
return await keyGenerationInProgress;
|
||||
} finally {
|
||||
keyGenerationInProgress = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function generatePrimaryMasterKey(): Promise<MasterKeyState> {
|
||||
const cached = getCachedMasterKey();
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const keyPath = getFallbackKeyPath();
|
||||
|
||||
if (safeStorage.isEncryptionAvailable()) {
|
||||
try {
|
||||
const result = await getOrCreateSafeStorageKey(keyPath);
|
||||
cacheMasterKey(result.key, 'safeStorage');
|
||||
if (result.created) {
|
||||
logger.info('Security: Generated new master key via safeStorage');
|
||||
} else {
|
||||
logger.info('Security: Loaded master key via safeStorage');
|
||||
}
|
||||
return { key: result.key, source: 'safeStorage' };
|
||||
} catch (error) {
|
||||
logger.warn('Security: safeStorage failed, trying keytar', error);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await getOrCreateKeytarKey();
|
||||
if (result) {
|
||||
cacheMasterKey(result.key, 'keytar');
|
||||
if (result.created) {
|
||||
logger.info('Security: Generated new master key via keytar');
|
||||
} else {
|
||||
logger.info('Security: Loaded master key via keytar');
|
||||
}
|
||||
return { key: result.key, source: 'keytar' };
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Security: keytar failed', error);
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
'Security: WARNING - Using file-based key storage. ' +
|
||||
'This is less secure than system keychain. ' +
|
||||
'Ensure the app data directory has restricted permissions.',
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await getOrCreateFileFallbackKey(keyPath);
|
||||
cacheMasterKey(result.key, 'file');
|
||||
if (result.created) {
|
||||
logger.warn('Security: Generating file-based fallback key (less secure)');
|
||||
} else {
|
||||
logger.warn('Security: Using file-based fallback key (less secure)');
|
||||
}
|
||||
return { key: result.key, source: 'file' };
|
||||
} catch (error) {
|
||||
const hint = buildKeychainAccessHint(error);
|
||||
logger.error('Security: Failed to access keychain/credential manager', error);
|
||||
const message = hint ? `${KEYCHAIN_ERROR_CODE}|${hint}` : KEYCHAIN_ERROR_CODE;
|
||||
throw new Error(message);
|
||||
// Fallback? If we can't store the key, we can't persistently encrypt.
|
||||
// For now, throw to prevent data loss (better not to write than to write something we can't decrypt later or write plain text when promised encrypted)
|
||||
throw new Error('Key management system unavailable');
|
||||
}
|
||||
}
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
const IV_LENGTH = 16;
|
||||
const AUTH_TAG_LENGTH = 16;
|
||||
|
||||
/**
|
||||
* Encrypts a string using AES-256-GCM.
|
||||
@@ -344,120 +42,21 @@ const IV_LENGTH = 16;
|
||||
*/
|
||||
export async function encrypt(text: string): Promise<string> {
|
||||
try {
|
||||
const { key } = await getPrimaryMasterKey();
|
||||
return encryptWithKey(key, text);
|
||||
const key = await getOrGenerateMasterKey();
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
let encrypted = cipher.update(text, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
|
||||
const authTag = cipher.getAuthTag();
|
||||
|
||||
// Format: iv:authTag:encrypted
|
||||
return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
|
||||
} catch (error) {
|
||||
logger.error('Security: Encryption failed', error);
|
||||
throw new Error('Encryption failed');
|
||||
}
|
||||
}
|
||||
|
||||
function encryptWithKey(key: Buffer, text: string): string {
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
let encrypted = cipher.update(text, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
|
||||
const authTag = cipher.getAuthTag();
|
||||
|
||||
return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
|
||||
}
|
||||
|
||||
function decryptWithKey(
|
||||
key: Buffer,
|
||||
ivHex: string,
|
||||
authTagHex: string,
|
||||
encryptedHex: string,
|
||||
): string {
|
||||
const iv = Buffer.from(ivHex, 'hex');
|
||||
const authTag = Buffer.from(authTagHex, 'hex');
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
|
||||
let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
|
||||
decrypted += decipher.final('utf8');
|
||||
|
||||
return decrypted;
|
||||
}
|
||||
|
||||
function isAuthTagMismatchError(errorMessage: string): boolean {
|
||||
const normalized = errorMessage.toLowerCase();
|
||||
return (
|
||||
normalized.includes('unable to authenticate data') ||
|
||||
normalized.includes('auth tag') ||
|
||||
normalized.includes('bad decrypt')
|
||||
);
|
||||
}
|
||||
|
||||
export async function decryptWithMigration(
|
||||
text: string,
|
||||
): Promise<{ value: string; reencrypted?: string; usedFallback?: KeySource }> {
|
||||
if (text.startsWith('{') || text.startsWith('[')) {
|
||||
return { value: text };
|
||||
}
|
||||
|
||||
const parts = text.split(':');
|
||||
if (parts.length !== 3) {
|
||||
return { value: text };
|
||||
}
|
||||
|
||||
const [ivHex, authTagHex, encryptedHex] = parts;
|
||||
|
||||
if (
|
||||
!/^[a-f0-9]+$/i.test(ivHex) ||
|
||||
!/^[a-f0-9]+$/i.test(authTagHex) ||
|
||||
!/^[a-f0-9]+$/i.test(encryptedHex)
|
||||
) {
|
||||
logger.warn('Security: Invalid encrypted format - not valid hex');
|
||||
throw new Error('Invalid encrypted data format');
|
||||
}
|
||||
|
||||
const primary = await getPrimaryMasterKey();
|
||||
try {
|
||||
return { value: decryptWithKey(primary.key, ivHex, authTagHex, encryptedHex) };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
|
||||
if (errorMessage.includes('Invalid key length') || errorMessage.includes('Invalid IV length')) {
|
||||
logger.error('Security: Decryption failed - corrupted encrypted data');
|
||||
throw new Error('Decryption failed: Corrupted encrypted data');
|
||||
}
|
||||
|
||||
if (!isAuthTagMismatchError(errorMessage)) {
|
||||
logger.error('Security: Decryption failed', error);
|
||||
throw new Error('Decryption failed');
|
||||
}
|
||||
|
||||
const keyPath = getFallbackKeyPath();
|
||||
const fallbackKeys = await getFallbackMasterKeys(keyPath, primary.source);
|
||||
for (const fallback of fallbackKeys) {
|
||||
try {
|
||||
const value = decryptWithKey(fallback.key, ivHex, authTagHex, encryptedHex);
|
||||
let reencrypted: string | undefined;
|
||||
try {
|
||||
reencrypted = encryptWithKey(primary.key, value);
|
||||
} catch (reencryptError) {
|
||||
logger.warn(
|
||||
`Security: Failed to re-encrypt data from ${fallback.source} to ${primary.source}`,
|
||||
reencryptError,
|
||||
);
|
||||
}
|
||||
if (reencrypted) {
|
||||
logger.info(`Security: Re-encrypted data from ${fallback.source} to ${primary.source}`);
|
||||
}
|
||||
return { value, reencrypted, usedFallback: fallback.source };
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
logger.error(
|
||||
'Security: Decryption failed - authentication tag mismatch (wrong key or corrupted data)',
|
||||
);
|
||||
throw new Error(`${DATA_MIGRATION_ERROR_CODE}|${DATA_MIGRATION_HINT_RELOGIN}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,6 +65,36 @@ export async function decryptWithMigration(
|
||||
* Input format: "iv_hex:auth_tag_hex:ciphertext_hex"
|
||||
*/
|
||||
export async function decrypt(text: string): Promise<string> {
|
||||
const result = await decryptWithMigration(text);
|
||||
return result.value;
|
||||
// Check if it's plain text (JSON) for backward compatibility
|
||||
// Very rough check: starts with { or [
|
||||
if (text.startsWith('{') || text.startsWith('[')) {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Also checking if it follows our pattern
|
||||
const parts = text.split(':');
|
||||
if (parts.length !== 3) {
|
||||
// Treat as plain text if it doesn't look like our encrypted format
|
||||
return text;
|
||||
}
|
||||
|
||||
try {
|
||||
const key = await getOrGenerateMasterKey();
|
||||
|
||||
const [ivHex, authTagHex, encryptedHex] = parts;
|
||||
const iv = Buffer.from(ivHex, 'hex');
|
||||
const authTag = Buffer.from(authTagHex, 'hex');
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
|
||||
let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
|
||||
decrypted += decipher.final('utf8');
|
||||
|
||||
return decrypted;
|
||||
} catch (error) {
|
||||
logger.error('Security: Decryption failed', error);
|
||||
// If decryption fails, it might be corrupted or using a different key.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
+19
-39
@@ -1,45 +1,25 @@
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import path from 'path';
|
||||
import { sentryVitePlugin } from '@sentry/vite-plugin';
|
||||
|
||||
// https://vitejs.dev/config
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '');
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
sentryVitePlugin({
|
||||
org: process.env.SENTRY_ORG || env.SENTRY_ORG,
|
||||
project: process.env.SENTRY_PROJECT || env.SENTRY_PROJECT,
|
||||
authToken: process.env.SENTRY_AUTH_TOKEN || env.SENTRY_AUTH_TOKEN,
|
||||
release: {
|
||||
name: `${process.env.npm_package_name}@${process.env.npm_package_version}`,
|
||||
},
|
||||
}),
|
||||
],
|
||||
define: {
|
||||
'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN || env.SENTRY_DSN),
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(process.cwd(), './src'),
|
||||
kafkajs: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
mqtt: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
amqplib: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'amqp-connection-manager': path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
nats: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
ioredis: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'@fastify/static': path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'@fastify/view': path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(process.cwd(), './src'),
|
||||
kafkajs: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
mqtt: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
amqplib: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'amqp-connection-manager': path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
nats: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
ioredis: path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'@fastify/static': path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'@fastify/view': path.resolve(process.cwd(), './src/mocks/empty.ts'),
|
||||
'@nestjs/microservices': path.resolve(process.cwd(), './src/mocks/nestjs-microservices'),
|
||||
'@nestjs/websockets': path.resolve(process.cwd(), './src/mocks/nestjs-websockets'),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
external: ['better-sqlite3', 'keytar'],
|
||||
},
|
||||
build: {
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
external: ['better-sqlite3', 'keytar'],
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
+3
-30
@@ -1,31 +1,4 @@
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import { sentryVitePlugin } from '@sentry/vite-plugin';
|
||||
import path from 'path';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '');
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
sentryVitePlugin({
|
||||
org: process.env.SENTRY_ORG || env.SENTRY_ORG,
|
||||
project: process.env.SENTRY_PROJECT || env.SENTRY_PROJECT,
|
||||
authToken: process.env.SENTRY_AUTH_TOKEN || env.SENTRY_AUTH_TOKEN,
|
||||
release: {
|
||||
name: `${process.env.npm_package_name}@${process.env.npm_package_version}`,
|
||||
},
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(process.cwd(), './src'),
|
||||
},
|
||||
},
|
||||
build: {
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
external: ['better-sqlite3', 'keytar'],
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
// https://vitejs.dev/config
|
||||
export default defineConfig({});
|
||||
+19
-44
@@ -1,53 +1,28 @@
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import { tanstackRouter } from '@tanstack/router-plugin/vite';
|
||||
import path from 'path';
|
||||
import { codeInspectorPlugin } from 'code-inspector-plugin';
|
||||
import { sentryVitePlugin } from '@sentry/vite-plugin';
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '');
|
||||
|
||||
return {
|
||||
plugins: [
|
||||
sentryVitePlugin({
|
||||
org: process.env.SENTRY_ORG || env.SENTRY_ORG,
|
||||
project: process.env.SENTRY_PROJECT || env.SENTRY_PROJECT,
|
||||
authToken: process.env.SENTRY_AUTH_TOKEN || env.SENTRY_AUTH_TOKEN,
|
||||
release: {
|
||||
name: `${process.env.npm_package_name}@${process.env.npm_package_version}`,
|
||||
},
|
||||
// Electron loads files from app://, so we need to normalize paths for Source Map matching
|
||||
sourcemaps: {
|
||||
// Rewrite the source paths to strip the Electron app:// protocol
|
||||
rewriteSources: (source) => {
|
||||
// Transform: app:///.vite/renderer/main_window/assets/index.js
|
||||
// Into: ~/.vite/renderer/main_window/assets/index.js
|
||||
return source.replace(/^app:\/\/\//, '~/');
|
||||
},
|
||||
},
|
||||
}),
|
||||
tanstackRouter({
|
||||
target: 'react',
|
||||
autoCodeSplitting: true,
|
||||
}),
|
||||
tailwindcss(),
|
||||
react({
|
||||
babel: {
|
||||
plugins: ['babel-plugin-react-compiler'],
|
||||
},
|
||||
}),
|
||||
codeInspectorPlugin({ bundler: 'vite' }),
|
||||
],
|
||||
define: {
|
||||
'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN || env.SENTRY_DSN),
|
||||
},
|
||||
resolve: {
|
||||
preserveSymlinks: true,
|
||||
alias: {
|
||||
'@': path.resolve(process.cwd(), './src'),
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
tanstackRouter({
|
||||
target: 'react',
|
||||
autoCodeSplitting: true,
|
||||
}),
|
||||
tailwindcss(),
|
||||
react({
|
||||
babel: {
|
||||
plugins: ['babel-plugin-react-compiler'],
|
||||
},
|
||||
}),
|
||||
codeInspectorPlugin({ bundler: 'vite' }),
|
||||
],
|
||||
resolve: {
|
||||
preserveSymlinks: true,
|
||||
alias: {
|
||||
'@': path.resolve(process.cwd(), './src'),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user