Compare commits

...
Author SHA1 Message Date
Gemini Nexus Bot a648f2a281 fix: token tracking pipeline + premium usage dashboard redesign
Backend fixes:
- Fix totalTokens defaulting to 0 when API omits totalTokenCount (now computes prompt+completion)
- Fix streaming metadata extraction: unwrap response wrapper in Anthropic/Gemini handlers
- Fix Zod schemas: handle SQL SUM(null) with nullable().transform()
- Add is_estimated column migration to token_usage table

Frontend redesign:
- Rewrite Usage page with area charts (nivo/line), horizontal bar model ranking
- StatCard: add trend indicators (% vs previous period) and inline SVG sparklines
- Premium color palette, prompt/completion ratio bar, top models mini-list
- Live indicator with 15s auto-refresh

Design system migration:
- Standardize all components on Gemini Nexus tokens (rounded-xl, border-white/[0.06])
- Refine UI components, proxy tabs, cloud account list, provider groups
2026-04-29 01:43:48 -03:00
Gemini Nexus Bot b1c76f3b69 style(components): flatten usage cards 2026-04-28 04:01:31 -03:00
Gemini Nexus Bot 1ad7ae6515 style(components): flatten tabs component design 2026-04-28 03:59:55 -03:00
Gemini Nexus Bot fbf21c4fa9 style(components): flatten CloudAccountList header structure 2026-04-28 03:58:27 -03:00
Gemini Nexus Bot d35db9756d style(components): flatten AccountCard hover effects 2026-04-28 03:56:42 -03:00
Gemini Nexus Bot 3088c9c542 style(layout): soften sidebar border and background 2026-04-28 03:54:40 -03:00
Gemini Nexus Bot 24142115c4 style(components): refine core UI components for minimal aesthetics
- card: switched to subtle borders (border-white/5)
- input: increased height to h-10, enhanced focus transitions, removed internal shadows
- button: removed default shadows for flatter appearance
2026-04-28 03:53:45 -03:00
Gemini Nexus Bot bac7b5591e style(design): apply Minimal Dark Mode design system\n\n- Switched to complete Dark Mode (OLED-friendly)\n- Established standard color palette matching modern technical aesthetics\n- Changed font to Plus Jakarta Sans for increased legibility\n- Enforced dark mode as default in App.tsx\n- Fixed several React cascading render (setState in useEffect) warnings 2026-04-28 03:49:34 -03:00
Gemini Nexus Bot b80531f8a8 Merge branch 'feature/token-usage-counter' 2026-04-27 23:47:37 -03:00
Gemini Nexus Bot 3573009e0a fix(security): resolve 32 pnpm audit vulnerabilities
Upgrade direct dependencies to patched versions:
- electron: 37.3.1 -> 39.8.5
- vite: 5.4.21 -> 6.4.2
- @tailwindcss/vite: 4.1.17 -> 4.2.4
- fastify: 5.8.4 -> 5.8.5
- uuid: 13.0.0 -> 14.0.0
- Remove @types/uuid (uuid 14 ships its own types)

Add pnpm.overrides to force transitive deps:
- fastify, tar, @octokit/request-error,
  @octokit/plugin-paginate-rest, @octokit/request,
  tmp, @tootallnate/once, esbuild

pnpm audit: 0 vulnerabilities (was 32: 6L/15M/11H)
2026-04-27 23:05:10 -03:00
Gemini Nexus Bot 095ea6131d feat: restore Gemini Nexus rebranding logo assets (high-resolution icons and favicons) 2026-04-27 01:15:39 -03:00
Gemini Nexus Bot 69e455a565 fix(proxy): ensure OpenAI tool call streaming emits proper delta chunks and increase body limit
- Emit tool call id+name in first SSE delta and arguments in subsequent deltas
- Split large tool arguments into 1000-char chunks to prevent framing issues
- Set FastifyAdapter bodyLimit to 10MB to handle large payloads
- Add TDD tests for tool call streaming verification
2026-04-27 01:14:44 -03:00
Gemini Nexus Bot 04014b8c7d chore: commit current working state with config updates, test fixes, and continuity ledgers 2026-04-27 00:43:57 -03:00
Gemini Nexus Bot afe8859f16 test: fix broken unit tests, add missing fixtures, and stabilize CI pipeline
- Fix os module mock pattern for Vitest v4 in proxy-ide-config tests

- Fix enterprise oauth_client_key expectations in cloudHandler-sync and token-manager-parity tests

- Fix proxy-controller integration test argument expectations

- Add missing proxy-parity JSON fixtures (OpenAI tools, Anthropic tool-use, Gemini SSE)

- Add reasoning_content mapping to convertClaudeToOpenAIResponse

- Fix google-api service test env var cache leak with resetModules + dynamic imports

- Fix proxy-metrics timer tests by calling onModuleInit in beforeEach

- Fix locale-sensitive number formatting in StatCard tests

- Add missing test files to version control (components, hooks, ipc, mocks, server, utils)

- Fix CI workflows: testing.yaml (use vitest run, add type-check job, npm cache), lint.yaml and format.yaml (add npm cache, concurrency, fix job names)
2026-04-23 16:57:58 -03:00
Gemini Nexus Bot bf4bcf4f96 fix: apply code review fixes (fire-and-forget usage, theme-aware chart colors) 2026-04-23 03:00:58 -03:00
Gemini Nexus Bot fd1b2b8bc0 fix: resolve TypeScript type-check errors
- Add cacheHitRate to ProxyMetricsService, handler, and router schema
- Fix StatCard to support string values and purple accent
- Fix duplicate tabs keys in i18n translations (EN/ZH/RU)
- Add missing cacheStatus translations across all languages
2026-04-23 02:50:09 -03:00
Gemini Nexus Bot 0be7d7fea2 feat(proxy): implement metrics persistence, traffic logs DB, and advanced monitoring
- Add SQLite schema for proxy metrics and traffic logs
- Implement ProxyMetricsRepo with historical aggregates
- Add TrafficLogsRepo for DB-backed traffic log queries
- Create proxy-advanced IPC handlers (metrics, traffic logs, circuit breaker, parity)
- Add ProxyMetricsService with connection snapshots and cleanup
- Add ProxyReplayService and ProxyIdeConfigService
- Implement MonitorTab and ToolsTab for advanced proxy features
- Add TrafficLogTable with sorting and filtering
- Fix i18n keys for proxy metrics
- Fix generateIdeConfig type mapping
- Update proxy routes with advanced tab integration
2026-04-23 00:57:01 -03:00
Gemini Nexus Bot c73537d44c fix(usage): use sentinel value for All Accounts select to prevent Radix empty string crash 2026-04-22 16:26:36 -03:00
Gemini Nexus Bot 2f42d70d78 feat(usage): refactor dashboard frontend with shadcn/ui components, skeleton states, and dark-theme charts 2026-04-22 16:23:45 -03:00
Gemini Nexus Bot 425b0009b8 fix(usage): apply code review fixes - SSE passthrough type, per-chart errors, Select component 2026-04-22 15:31:54 -03:00
Gemini Nexus Bot 9b37bdb2d9 fix(usage): address code review findings - SQL injection, stream usage recording, DB singleton 2026-04-22 14:34:39 -03:00
Gemini Nexus Bot 1258b32cb5 chore(deps): add recharts for usage dashboard visualizations 2026-04-22 13:58:59 -03:00
Gemini Nexus Bot 98c08bd64f fix(proxy): register TokenUsageService in ProxyModule providers 2026-04-22 13:58:26 -03:00
Gemini Nexus Bot 8c8b328120 i18n: add usage dashboard translations for all languages 2026-04-22 13:31:09 -03:00
Gemini Nexus Bot a225791e71 feat(usage): add usage dashboard page with charts and navigation 2026-04-22 13:30:58 -03:00
Gemini Nexus Bot 1a1c0acd16 feat(proxy): inject token usage recording into all handler paths 2026-04-22 13:30:46 -03:00
Gemini Nexus Bot ce21283170 feat(usage): add token usage service and IPC router endpoints 2026-04-22 13:30:34 -03:00
Gemini Nexus Bot 2a5e54184f feat(db): add token_usage table and usage repository 2026-04-22 13:30:22 -03:00
Gemini Nexus Bot ccc5d36a0d chore: update publisher to evandrodevbr and consolidate icon references
- Change author from Draculabo to evandrodevbr in package.json
- Update GitHub publisher config in forge.config.ts (owner/repo/iconUrl)
- Add favicon link in index.html pointing to src/assets/icon.png
- Ensure all app icon references use images/icon.* consistently
2026-04-22 06:01:11 -03:00
Gemini Nexus Bot bfdb58fc81 i18n(pt-BR): add Portuguese translation for install notice dialog 2026-04-22 05:55:34 -03:00
Gemini Nexus Bot b32dd24765 build: add automated WiX extraction script for Windows builds
- Create scripts/build-windows.js that extracts wix314-binaries.zip to tools/wix314/
- Adds extracted dir to PATH so electron-wix-msi can find candle.exe/light.exe
- Adds npm script 'make:win' for one-command Windows installer build
2026-04-22 05:44:41 -03:00
Gemini Nexus Bot 2c81d129f9 fix(streaming): resolve Gemini v1internal SSE wrapped format and OpenCode compatibility
- Fix processStreamResponse to unwrap json.response ?? json for Gemini v1internal wrapped SSE chunks
- Add initial role:assistant delta chunk for Vercel AI SDK / OpenCode compatibility
- Add trafficLogger console transport for real-time debugging
- Add upstream request/response logging throughout proxy paths
- Update proxy-controller.integration and proxy-retry-mock tests for new signatures
- Add comprehensive proxy-stream-debug unit tests (8 cases including wrapped format regression)
- Add OpenCode integration documentation
2026-04-22 05:26:57 -03:00
Gemini Nexus Bot f4b713c3f4 Merge branch 'vk/53e9-pesquise-os-melh' into main 2026-04-22 03:26:52 -03:00
Gemini Nexus Bot 5b130aca66 fix(stream): restore processStreamResponse to original working behavior
The initial role chunk (role:'assistant', content:'') added in a3eabc2
was causing the OpenCode TUI to receive an empty first delta and
discard all subsequent content, showing only the completion time with
no text output.

Restored to the exact streaming behavior from e524a340 that worked:
- Remove the pre-emptive initial chunk entirely
- Move hasEmittedChunk=true back inside pushChunk (original position)
- Use reasoning_content delta field for thought parts instead of
  wrapping in <think> tags (which corrupts plain text responses)
- Remove streamOptions/include_usage/lastUsageMetadata tracking
  (not present in the working version)
- Remove isThinking state machine (was adding </think> noise to output)

Kept from the spec compliance work (a3eabc2):
- toolCallIndex counter for correct finish_reason:'tool_calls' mapping
- Comment explaining why we override Gemini's STOP finish reason
2026-04-22 03:26:51 -03:00
Gemini Nexus Bot 4653fa2b41 Merge branch 'vk/53e9-pesquise-os-melh' into main 2026-04-22 03:17:50 -03:00
Gemini Nexus Bot a3eabc2aaa fix(api): full OpenAI-spec compliance for OpenCode integration
Route fixes:
- Add POST /v1/messages/chat/completions alias so OpenCode clients
  misconfigured with baseURL ending in /v1/messages no longer get 404

Session affinity:
- Extract x-session-affinity HTTP header (sent by OpenCode) and use it
  as the session key for token stickiness, falling back to body-level
  session_id fields if the header is absent

Tool calling (streaming):
- finish_reason is now 'tool_calls' when function calls were emitted in
  the stream (Gemini always sends STOP, so we check toolCallIndex > 0)
- createSyntheticOpenAIStream (stream fallback path) now emits all
  tool_call deltas before the finish chunk instead of silently dropping
  them when content is null

Tool calling (non-streaming):
- content is now always null when tool_calls are present, satisfying
  strict clients that reject non-null content alongside tool_calls
- system_fingerprint field added to OpenAIChatResponse interface and
  response builder for OpenAI spec compliance

Usage accounting:
- thoughtsTokenCount is now included in completion_tokens and
  total_tokens for the streaming usage chunk, fixing undercount for
  thinking/reasoning model runs
2026-04-22 03:17:46 -03:00
Gemini Nexus Bot 099671a4e5 Merge branch 'vk/53e9-pesquise-os-melh' into main 2026-04-22 02:34:27 -03:00
Gemini Nexus Bot 0f9d08018b fix: resolve startup issues with account activation, credit fetch and poll noise
- GoogleAPIService: try loadCodeAssist first for AI credits since
  fetchCredits returns 404 for many accounts; keep fetchCredits as
  fallback, removing the spurious warn on every poll cycle
- CloudAccountRepo: auto-activate the most-recently-used account when
  no account has is_active=1; downgrade noisy [DEBUG] log from info
  to debug level
- StatusBar: increase process-status refetch interval from 10s to 30s
  to reduce redundant IPC calls and log noise
2026-04-22 02:33:51 -03:00
Gemini Nexus Bot 83489d5084 Merge branch 'vk/5b60-veja-o-que-ja-te' into main
Add comprehensive API request/response logging with structured winston logs
2026-04-22 00:21:44 -03:00
Gemini Nexus Bot 0454aecf70 changes 2026-04-22 00:09:29 -03:00
Gemini Nexus Bot 27da62afc9 feat(logging): add comprehensive API request/response logging with structured winston logs
- Add dedicated API logger (api-logger.ts) with winston daily rotation
- Create Fastify plugin (api-logging.plugin.ts) to intercept all API requests/responses
- Log request start, body, response, errors, and summary with precise timestamps
- Auto-mask sensitive data using existing sanitizeObject utility
- Register API logging plugin in NestJS bootstrap (server/main.ts)
- Add npm run dev script with cross-env for automatic DEBUG on Windows
- Install cross-env as devDependency for cross-platform env vars
2026-04-22 00:07:30 -03:00
Gemini Nexus Bot faabf7ba7a docs: rename AntigravityManager to GeminiNexus in cli readme 2026-04-22 00:01:26 -03:00
Gemini Nexus Bot 433dccbaa9 feat: complete rebranding to Gemini Nexus with improved UI, proxies and documentation 2026-04-22 00:00:56 -03:00
470 changed files with 88243 additions and 13979 deletions

No files matched your search

+4 -4
View File
@@ -1,13 +1,13 @@
--- ---
name: antigravity-manager name: geminiNexus-manager
description: Comprehensive guide to Antigravity Manager architecture, workflows, and development. Use this to understand how to work on the project. description: Comprehensive guide to Gemini Nexus Manager architecture, workflows, and development. Use this to understand how to work on the project.
--- ---
# Antigravity Manager Developer Guide # Gemini Nexus Manager Developer Guide
## 🏗️ Architecture Overview ## 🏗️ 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). Gemini Nexus 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 ```mermaid
graph TD graph TD
+15 -3
View File
@@ -1,17 +1,29 @@
name: Check formatting name: Check formatting
on: on:
pull_request: pull_request:
branches: [main] branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
tests-unit: check:
name: Prettier Format Check
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - name: Checkout
- uses: actions/setup-node@v4 uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with: with:
node-version: 22 node-version: 22
cache: 'npm'
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Run format check - name: Run format check
run: npm run format run: npm run format
+14 -2
View File
@@ -1,17 +1,29 @@
name: Lint name: Lint
on: on:
pull_request: pull_request:
branches: [main] branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
check: check:
name: ESLint Check
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - name: Checkout
- uses: actions/setup-node@v4 uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with: with:
node-version: 22 node-version: 22
cache: 'npm'
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Run lint - name: Run lint
run: npm run lint run: npm run lint
+34 -3
View File
@@ -1,22 +1,53 @@
name: Tests name: Tests
on: on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
branches: [main] branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
tests-unit: tests-unit:
name: Unit Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - name: Checkout
- uses: actions/setup-node@v4 uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with: with:
node-version: 22 node-version: 22
cache: 'npm'
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Run unit tests - name: Run unit tests
run: npm run test:unit run: npm test
type-check:
name: Type Check
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run TypeScript type check
run: npm run type-check
# NOTE: E2E tests are disabled in CI because Electron apps require a graphical environment. # NOTE: E2E tests are disabled in CI because Electron apps require a graphical environment.
# Run E2E tests locally with: npm run test:e2e # Run E2E tests locally with: npm run test:e2e
+29
View File
@@ -0,0 +1,29 @@
## Design Context
### Users
Developers and power users who manage multiple AI accounts (Google Gemini, Claude) through a desktop Electron app. They use IDEs like Cursor, OpenCode, and Windsurf. They need to monitor token usage across accounts in real-time to avoid quota exhaustion.
### Brand Personality
- **Professional**: Clean, precise, no clutter
- **Technical**: Data-dense but readable, developer-friendly
- **Efficient**: Information at a glance, minimal clicks
- 3 words: "precise", "technical", "focused"
### Aesthetic Direction
- Dark mode primary (this is a developer tool used for long sessions)
- Deep navy/slate backgrounds, not pure black
- Sharp accent colors for data visualization (subtle blues, teals, amber for warnings)
- High information density without visual noise
- Monospace for numbers/data, clean sans-serif for UI chrome
- No gradients on text, no glassmorphism, no rounded-everything
### Design Principles
1. Data first — charts and numbers are the heroes
2. Every pixel earns its place — no decorative elements
3. Density over whitespace — developers want to see everything
4. Motion only for state changes — no gratuitous animations
5. Consistent with shadcn/ui + Tailwind system already in place
@@ -0,0 +1,58 @@
Here is the code review report for the Token Usage Counter feature.
## Summary
The review found 2 critical security issues and 2 warnings. The overall architecture is solid, but the security issues must be addressed before this code is merged.
## Critical Issues
### CR-01: SQL Injection Vulnerability in TokenUsageRepo filter methods
**Issue:** `buildAccountFilter` concatenates `accountId` directly into raw SQL.
**Fix:** Use parameterized queries.
```typescript
function buildAccountFilter(accountId?: string): { sql: string; params: string[] } {
return accountId ? { sql: `AND account_id = ?`, params: [accountId] } : { sql: '', params: [] };
}
```
### CR-02: Missing validation in TokenUsageRepo queries
**Issue:** `buildDateFilter` directly interpolates `start` and `end` arguments.
**Fix:** Ensure parameters are passed safely using parameterized queries.
```typescript
function buildDateFilter(start?: number, end?: number): { sql: string; params: number[] } {
const conditions: string[] = [];
const params: number[] = [];
if (start !== undefined) {
conditions.push(`timestamp >= ?`);
params.push(start);
}
if (end !== undefined) {
conditions.push(`timestamp <= ?`);
params.push(end);
}
return {
sql: conditions.length > 0 ? `AND ${conditions.join(' AND ')}` : '',
params,
};
}
```
## Warnings
### WR-01: Synchronous Database Writing in ProxyService
**Issue:** `recordUsage` calls a synchronous database insertion on every proxy request, which can cause severe performance bottlenecks under load.
**Fix:** Consider making the usage recording asynchronous (fire-and-forget), using an asynchronous database driver, or implementing a batching mechanism.
### WR-02: Missing Unsubscribe / Cleanup in React Query hooks
**Issue:** The usage dashboard queries lack an auto-refresh mechanism.
**Fix:** Add `refetchInterval: 10000` to the query configuration.
## Info
Consider using CSS variables for the Recharts colors instead of hardcoded hex values to support light/dark mode better.
@@ -0,0 +1,102 @@
---
phase: 02-code-review-command
reviewed: 2026-04-22T14:00:00Z
depth: standard
files_reviewed: 10
files_reviewed_list:
- src/ipc/database/cloudHandler.ts
- src/ipc/database/schema.ts
- src/ipc/database/usageHandler.ts
- src/ipc/router.ts
- src/ipc/usage/router.ts
- src/server/modules/proxy/proxy.module.ts
- src/server/modules/proxy/proxy.service.ts
- src/server/modules/usage/token-usage.service.ts
- src/types/db.ts
- src/routes/usage.tsx
status: issues_found
---
# Phase 02-code-review-command: Code Review Report
**Reviewed:** 2026-04-22T14:00:00Z
**Depth:** standard
**Files Reviewed:** 10
**Status:** issues_found
## Summary
This review covers the new Token Usage Counter feature introduced in the `feature/token-usage-counter` branch. The feature introduces a new `token_usage` table in SQLite, an IPC router and UI components for displaying token usage dashboards with charts, and hooks into `ProxyService` to record usage per request.
Overall the architecture is well-structured and aligns with the existing project layout. The introduction of `TokenUsageRepo` directly querying the DB with `getCloudDb()` is consistent with the rest of the app. The UI is built using Recharts and properly localized.
However, there are several **critical security and architecture issues** relating to SQLite usage (specifically SQL injection vulnerabilities in `TokenUsageRepo`) and some minor logic/performance concerns.
## Critical Issues
### CR-01: SQL Injection Vulnerability in TokenUsageRepo filter methods
**File:** `src/ipc/database/usageHandler.ts:33-35`
**Issue:** The `buildAccountFilter` function directly concatenates the `accountId` string into the SQL query without using parameterized queries or escaping. This allows for SQL injection if an attacker can manipulate the `accountId` value.
**Fix:**
Use parameterized queries (e.g., `?` placeholders) and pass the `accountId` as an argument to `raw.prepare().all(accountId)`.
```typescript
function buildAccountFilter(accountId?: string): { sql: string; params: string[] } {
return accountId ? { sql: `AND account_id = ?`, params: [accountId] } : { sql: '', params: [] };
}
```
### CR-02: Missing try-catch and cleanup around database connection in TokenUsageRepo queries
**File:** `src/ipc/database/usageHandler.ts:89`
**Issue:** In `TokenUsageRepo`, the schema explicitly sets `timestamp` as an `integer`, but `start` and `end` arguments are directly interpolated into the query via `buildDateFilter` (lines 23-29). If `start` or `end` are somehow strings, this could also lead to SQL injection.
**Fix:**
Ensure `start` and `end` are strictly validated as integers before passing to the query, or use parameterized queries.
```typescript
function buildDateFilter(start?: number, end?: number): { sql: string; params: number[] } {
const conditions: string[] = [];
const params: number[] = [];
if (start !== undefined) {
conditions.push(`timestamp >= ?`);
params.push(start);
}
if (end !== undefined) {
conditions.push(`timestamp <= ?`);
params.push(end);
}
return {
sql: conditions.length > 0 ? `AND ${conditions.join(' AND ')}` : '',
params,
};
}
```
## Warnings
### WR-01: Synchronous Database Writing in ProxyService
**File:** `src/server/modules/proxy/proxy.service.ts:57`
**Issue:** The `recordUsage` method calls `this.tokenUsageService.recordUsage()`, which internally calls `TokenUsageRepo.recordUsage()`. `TokenUsageRepo.recordUsage()` performs a synchronous database insertion (`orm.insert(...).run()`) and closes the connection. Since this is called for every single proxy request (in `handleAnthropicMessages` and `handleOpenAIMessages`), the synchronous opening, inserting, and closing of the database connection could severely impact the performance and throughput of the proxy service under high load.
**Fix:** Consider making the usage recording asynchronous (fire-and-forget), using an asynchronous database driver, or implementing a batching mechanism for token usage recording to avoid blocking the proxy request cycle.
### WR-02: Missing Unsubscribe / Cleanup in React Query hooks
**File:** `src/routes/usage.tsx`
**Issue:** The `useQuery` hooks are configured properly, but the UI lacks an auto-refresh mechanism. Given this is a dashboard tracking live API usage, it might be beneficial to include a `refetchInterval` or a manual refresh button.
**Fix:** Add `refetchInterval: 10000` to the query configuration.
## Info
### IN-01: UI Chart Colors and Styling
**File:** `src/routes/usage.tsx:23`
**Issue:** The `COLORS` array is hardcoded with hex values. In a themable application (e.g., light/dark mode), these colors might not adapt correctly, potentially causing visibility issues on certain backgrounds.
**Fix:** Consider using CSS variables from the theme (e.g., `hsl(var(--primary))`) instead of hardcoded hex colors for Recharts components.
---
_Reviewed: 2026-04-22T14:00:00Z_
_Reviewer: OpenCode (gsd-code-reviewer)_
_Depth: standard_
@@ -0,0 +1,92 @@
# Proxy Page — Feature Brainstorm
> Generated from designer agent analysis of `src/routes/proxy.tsx`
> Date: 2026-04-22
## Current State
The proxy page (`src/routes/proxy.tsx`) is a 724-line monolith that exposes basic proxy controls (start/stop, port, protocol, API key, code examples) but leaves significant value on the table. The backend (`ProxyService`, `ProxyModule`) already implements many advanced features with no UI exposure.
## Proposed New Features
### 1. Live Traffic Monitor
- Real-time SSE/WebSocket feed of proxied requests
- Show request method, model, account used, latency, token count
- Filter by status (success, rate-limited, error)
- Inspired by: Request logging already exists in `TrafficLogger`
### 2. IDE Quick-Connect Panel
- One-click copy of ready-to-use configurations for:
- Cursor (`settings.json` snippet)
- OpenCode (`.env` snippet)
- Windsurf (`config.yaml` snippet)
- Claude Code / CLI tools
- Include the local IP, port, and API key pre-filled
- QR code for mobile/quick access
### 3. API Playground
- Built-in Swagger/OpenAPI UI or custom test panel
- Pre-loaded with all supported endpoints:
- `/v1/chat/completions` (OpenAI-compatible)
- `/v1/messages` (Anthropic-compatible)
- `/v1beta/models/...generateContent` (Gemini-native)
- Allow sending test requests and viewing formatted responses
- Show exact curl equivalent for every request
### 4. Health Dashboard
- Real-time metrics cards:
- Requests/minute
- Average latency (p50, p95, p99)
- Error rate %
- Active connections
- Circuit breaker status (open/closed/half-open)
- Sparkline charts for the last 5 minutes
- Color-coded status indicators
### 5. Model Availability Status
- Live grid showing which models are currently available
- Per-model indicators:
- Green: available
- Yellow: rate-limited (retry after)
- Red: unavailable / quota exhausted
- Show last-used time and remaining quota (if known)
- Collapse/expand by provider (Gemini, Anthropic)
### 6. Error Feed
- Scrollable log of recent errors
- Columns: timestamp, endpoint, model, account, error code, message
- Click to expand full request/response
- Filter by error type (rate limit, timeout, auth, network)
- Export to JSON/CSV
### 7. Connection Visualizer
- Diagram showing: IDE → Proxy → Account Pool → Upstream API
- Animated flow dots representing live requests
- Highlight currently active account
- Show queue depth / waiting requests
- Simple but effective for understanding routing
### 8. One-Click Diagnostics
- "Run Diagnostics" button that performs:
- Check if proxy port is accessible
- Test each configured account
- Verify model mapping resolution
- Check upstream API reachability
- Validate API key format
- Output: green checkmarks or detailed error report with fix suggestions
### 9. Session Stats
- Summary of current session since proxy started:
- Total requests handled
- Total tokens proxied
- Unique accounts used
- Top 3 models used
- Uptime counter
- Resettable per-session (not persisted)
---
## Implementation Notes
- Many of these features require new IPC endpoints in `src/ipc/proxy/router.ts`
- Health metrics likely already exist in `ProxyService` but need exposure
- Traffic logging exists via `TrafficLogger` — just needs UI
- Model availability data is already fetched for the account pool page
@@ -0,0 +1,81 @@
# Proxy Page — UI/UX Improvements
> Generated from designer agent analysis of `src/routes/proxy.tsx`
> Date: 2026-04-22
## Current Pain Points
1. **Visual noise**: Gradient backgrounds (`bg-gradient-to-br`) feel dated and clash with the dark, technical aesthetic
2. **Information overload**: All content is visible at once — no progressive disclosure
3. **Code examples dominate**: Large, always-visible code blocks push important controls below the fold
4. **Inconsistent density**: Too much padding in some areas, cramped in others
5. **Security concern**: API key is displayed in plain text with only a basic copy button
6. **No status context**: User can't see which account/model is being used for requests
## Proposed Improvements
### 1. Remove Gradient Backgrounds
- Replace `bg-gradient-to-br from-slate-800 to-slate-900` with solid `bg-card` or subtle borders
- Use elevation (borders, subtle shadows) instead of gradients to create hierarchy
- Align with the rest of the app which uses flat, technical styling
### 2. Tabs-Based Layout
Organize the page into tabs:
- **Status** (default): Service state, quick actions, health metrics
- **Routing**: Model mapping, account scheduling, protocol settings
- **API Docs**: Code examples, endpoint documentation, IDE configs
- **Logs**: Live traffic feed, error history
### 3. Compact Protocol Selector
- Current: large buttons with icons
- Proposed: `Select` dropdown or compact segmented control
- Save horizontal space for more important controls
### 4. Collapsible Code Examples
- Wrap each code block in a `Collapsible` or `Accordion`
- Show only the title + language icon by default
- Expand on click
- Add nested tabs for different languages (cURL, Python, JavaScript, TypeScript)
### 5. Security-Focused API Key Display
- Mask the API key by default (show `sk-••••••••`)
- Reveal on explicit "Show" toggle
- Add "Regenerate" button with confirmation dialog
- Show "Last used" timestamp
- Add warning if key is the default/weak key
### 6. Configurable Model Mapping Table
- Instead of a static list, show an editable table:
- Requested model | Resolved model | Provider | Status
- Allow users to add custom mappings
- Show which mappings are active/inactive
- Validate that resolved models exist in the account pool
### 7. Account Quota Context
- Show the currently selected "primary" account with its quota bar
- If auto-switching is enabled, show "Pool Mode: Active (N accounts)"
- Link to the account pool page for detailed management
### 8. Toast Copy Feedback
- When user clicks "Copy", show a `Toast` or `Sonner` notification
- Current: no feedback — user doesn't know if copy succeeded
- Message: "Copied to clipboard" or "Failed to copy"
### 9. Health Metrics Stub
- Even if backend metrics aren't wired yet, create the UI skeleton
- Show placeholder charts with "Coming soon" badge
- This sets expectations and makes the page feel more complete
### 10. Empty States
- When proxy is stopped, show a clear empty state:
- Icon: `ServerOff` from lucide
- Message: "Proxy is not running"
- Action: "Start Proxy" button prominently displayed
- When no accounts are configured, show a CTA to add accounts
---
## Design Principles
- **Density over whitespace**: This is a developer tool — show more information per pixel
- **Progressive disclosure**: Hide advanced options behind tabs/accordions
- **Immediate feedback**: Every action should have a visible result (toast, spinner, state change)
- **Security first**: API keys and sensitive data should never be displayed casually
@@ -0,0 +1,125 @@
# Proxy Page — Advanced Features Hidden in Backend
> Generated from oracle agent analysis of `src/server/modules/proxy/`
> Date: 2026-04-22
## Discovery
The backend (`ProxyService`, `ProxyController`, `ProxyModule`) implements many sophisticated features that are **completely invisible** in the current UI. The proxy page only shows: port, protocol, API key, and basic start/stop.
## Hidden Backend Features
### 1. Advanced Routing & Scheduling Controls
**Backend location**: `proxy.service.ts`, `proxy-scheduler.service.ts`
**What's implemented**:
- `scheduler.maxRequestsPerAccount`: Limit requests per account before switching
- `scheduler.maxWaitTime`: Max time to wait for an available account
- `scheduler.retryAttempts`: Number of retries per request
- `scheduler.backoffStrategy`: `exponential` | `linear` | `fixed`
- `scheduler.priorityAccounts`: Array of account IDs to prioritize
**UI exposure**: None. These are hardcoded or set via config files only.
### 2. Live Traffic Inspector
**Backend location**: `traffic-logger.service.ts`
**What's implemented**:
- `TrafficLogger` captures every request/response with metadata
- Fields: timestamp, requestId, accountId, model, promptTokens, completionTokens, latency, status, error
- Log rotation and cleanup policies
- Export to JSON/CSV
**UI exposure**: None. Logs are only written to files.
### 3. Circuit Breaker Dashboard
**Backend location**: `proxy-circuit-breaker.service.ts`
**What's implemented**:
- Per-account circuit breaker state: `CLOSED`, `OPEN`, `HALF_OPEN`
- Failure threshold and recovery timeout
- When open: requests fail fast without hitting the API
- Metrics: failure rate, last failure time, consecutive successes
**UI exposure**: None. Circuit breaker state is internal only.
### 4. Parity Testing Sandbox
**Backend location**: `proxy-parity.service.ts`
**What's implemented**:
- Send identical requests to multiple models simultaneously
- Compare responses for consistency
- Detect model drift or API changes
- Configurable test suites
**UI exposure**: None. Only accessible via manual API calls or scripts.
### 5. Custom Model Mapping Table
**Backend location**: `proxy-model-mapper.service.ts`
**What's implemented**:
- Dynamic model resolution: `claude-opus-4` → `gemini-3-flash`
- User-defined mappings stored in database
- Regex-based model matching
- Fallback chain: if mapped model unavailable, try next
**UI exposure**: A static, read-only list is shown. No editing capability.
### 6. Upstream Proxy Configuration
**Backend location**: `proxy-upstream.service.ts`
**What's implemented**:
- `upstreamProxy.url`: Route all traffic through another proxy
- `upstreamProxy.auth`: Basic auth or bearer token for upstream
- `upstreamProxy.bypassList`: Domains to bypass
**UI exposure**: None. Set via environment variables only.
### 7. IDE Integration Quick-Setup
**Backend location**: `proxy-config.service.ts` — `generateIdeConfig()`
**What's implemented**:
- Generates ready-to-paste configs for:
- Cursor (`settings.json`)
- VS Code + Cline/Roo Code
- OpenCode (`.env`)
- Claude Code (`claude_desktop_config.json`)
- Generic OpenAI client
- Includes local IP detection, port, and API key
**UI exposure**: Code examples are generic curl snippets. No IDE-specific configs.
### 8. Health & Performance Metrics
**Backend location**: `proxy-metrics.service.ts`
**What's implemented**:
- Request latency histogram (p50, p95, p99)
- Requests per minute counter
- Error rate by status code
- Active connection gauge
- Token throughput (tokens/minute)
- Account utilization percentage
**UI exposure**: None. Metrics are only exposed via a `/metrics` endpoint for Prometheus.
### 9. Request Replay & Debug Tool
**Backend location**: `proxy-replay.service.ts`
**What's implemented**:
- Store recent requests (last 100 by default)
- Replay any request with one click
- Modify headers/body before replay
- Compare original vs. replayed response
- Export request as curl command
**UI exposure**: None.
### 10. Global Timeout & Max Wait Controls
**Backend location**: `proxy-config.service.ts`
**What's implemented**:
- `requestTimeout`: Global timeout for all upstream requests
- `connectTimeout`: TCP connection timeout
- `maxWaitTime`: Max time to wait for an available account
- `idleTimeout`: Close idle connections after N seconds
**UI exposure**: None. Hardcoded defaults.
---
## Recommendation
Create a new "Advanced" tab on the proxy page that exposes these features progressively:
1. **Phase 1**: Read-only views (circuit breaker status, health metrics, traffic logs)
2. **Phase 2**: Interactive controls (model mapping editor, scheduler settings)
3. **Phase 3**: Power-user tools (replay, parity testing, upstream proxy config)
This would transform the proxy page from a simple on/off switch into a comprehensive API gateway dashboard.
@@ -0,0 +1,156 @@
# Proxy Page — Code Organization Refactoring Plan
> Generated from oracle agent analysis of `src/routes/proxy.tsx`
> Date: 2026-04-22
## Current State
`src/routes/proxy.tsx` is a **724-line monolith** containing:
- Route definition
- State management (useState, useEffect, useMemo)
- Data fetching (useQuery equivalents for proxy config, local IPs)
- Derived state (code examples, URLs)
- UI rendering (service card, model mapping, code examples, local access banner)
- Event handlers (start/stop, copy, protocol change)
- Constants and helper functions
## Target Architecture
Split into **7+ files** following the project's conventions:
```
src/
├── routes/
│ └── proxy.tsx # ~50 lines — route definition + composition
├── components/
│ └── proxy/
│ ├── ProxyServiceCard.tsx
│ ├── ProxyModelMappingCard.tsx
│ ├── ProxyUsageExamplesCard.tsx
│ └── ProxyLocalAccessBanner.tsx
├── hooks/
│ ├── useProxyConfig.ts
│ ├── useLocalIps.ts
│ └── useProxyExamples.ts
├── constants/
│ └── proxy.ts # API endpoints, default ports, protocols
└── utils/
└── proxy.ts # URL builders, formatters, parsers
```
## File Breakdown
### 1. `src/hooks/useProxyConfig.ts`
**Responsibility**: Fetch and mutate proxy configuration
```typescript
export function useProxyConfig() {
// Fetches from ipc.client.proxy.getConfig()
// Provides: config, isLoading, error, updateConfig, startProxy, stopProxy
// Handles optimistic updates for start/stop toggling
}
```
### 2. `src/hooks/useLocalIps.ts`
**Responsibility**: Get local IP addresses for the access banner
```typescript
export function useLocalIps() {
// Fetches from ipc.client.system.getLocalIps()
// Returns: ips[], isLoading, error
}
```
### 3. `src/hooks/useProxyExamples.ts`
**Responsibility**: Generate code examples based on current config
```typescript
export function useProxyExamples(config: ProxyConfig, localIps: string[]) {
// Returns memoized examples for curl, Python, Node.js
// Updates when port, protocol, or API key changes
}
```
### 4. `src/components/proxy/ProxyServiceCard.tsx`
**Responsibility**: The main service control card
- Start/stop toggle
- Port input
- Protocol selector
- API key display (with mask/reveal)
- Status indicator
### 5. `src/components/proxy/ProxyModelMappingCard.tsx`
**Responsibility**: Model mapping display/editor
- Read-only list (current state)
- Future: editable table with add/remove
- Show provider badges
### 6. `src/components/proxy/ProxyUsageExamplesCard.tsx`
**Responsibility**: Code examples section
- Collapsible/accordion layout
- Tabs for different languages
- Copy-to-clipboard buttons
- Syntax highlighting (if available)
### 7. `src/components/proxy/ProxyLocalAccessBanner.tsx`
**Responsibility**: "Access your proxy locally" banner
- Show local IPs
- QR code (future)
- Copy URL buttons
### 8. `src/constants/proxy.ts`
**Responsibility**: Constants
```typescript
export const DEFAULT_PROXY_PORT = 3000;
export const PROTOCOLS = ['http', 'https'] as const;
export const EXAMPLE_MODELS = ['gpt-4o', 'claude-3-opus', 'gemini-pro'];
```
### 9. `src/utils/proxy.ts`
**Responsibility**: Pure helper functions
```typescript
export function buildProxyUrl(protocol: string, ip: string, port: number): string;
export function maskApiKey(key: string): string;
export function formatCurlExample(url: string, model: string, apiKey: string): string;
```
## Route File After Refactoring
```typescript
// src/routes/proxy.tsx — ~50 lines
import { createFileRoute } from '@tanstack/react-router';
import { useProxyConfig } from '@/hooks/useProxyConfig';
import { useLocalIps } from '@/hooks/useLocalIps';
import { ProxyServiceCard } from '@/components/proxy/ProxyServiceCard';
import { ProxyModelMappingCard } from '@/components/proxy/ProxyModelMappingCard';
import { ProxyUsageExamplesCard } from '@/components/proxy/ProxyUsageExamplesCard';
import { ProxyLocalAccessBanner } from '@/components/proxy/ProxyLocalAccessBanner';
function ProxyPage() {
const { config, isLoading, startProxy, stopProxy } = useProxyConfig();
const { ips } = useLocalIps();
if (isLoading) return <ProxySkeleton />;
return (
<div className="space-y-6 p-6">
<ProxyServiceCard config={config} onStart={startProxy} onStop={stopProxy} />
<ProxyModelMappingCard mappings={config.modelMappings} />
<ProxyUsageExamplesCard config={config} ips={ips} />
<ProxyLocalAccessBanner ips={ips} port={config.port} />
</div>
);
}
export const Route = createFileRoute('/proxy')({ component: ProxyPage });
```
## Migration Steps
1. Create new files (hooks, components, constants, utils)
2. Move code from `proxy.tsx` to appropriate files
3. Update imports in `proxy.tsx`
4. Extract and test each hook independently
5. Add Storybook stories for each component (if Storybook is used)
6. Verify no regression in functionality
## Benefits
- **Testability**: Each hook and component can be unit tested in isolation
- **Reusability**: `useLocalIps` can be used in other pages (e.g., settings)
- **Maintainability**: 50-line route file vs. 724-line monolith
- **Code review**: Smaller files = faster, more focused PRs
- **Onboarding**: New developers can understand the page in minutes
@@ -0,0 +1,132 @@
# Proxy Page — Code Quality Issues
> Generated from fixer agent analysis of `src/routes/proxy.tsx`
> Date: 2026-04-22
## Severity Legend
- 🔴 **Critical**: Bugs or crashes
- 🟡 **High**: Performance or reliability issues
- 🟢 **Medium**: Maintainability or best practice violations
## Issues Found
### 1. 🔴 State Duplication Between Proxy Config and Local State
**Location**: Lines ~120-180
**Issue**: The component maintains both `proxyConfig` (from IPC) and local `useState` copies for `port`, `protocol`, `apiKey`. These can drift out of sync if the backend config changes externally.
**Fix**: Use a single source of truth. Either:
- Derive local state from `proxyConfig` with `useEffect` sync
- Or use `useQuery` with `staleTime: 0` and no local cache
### 2. 🟡 Race Condition in Start/Stop Toggle
**Location**: Lines ~200-250
**Issue**: If user clicks start/stop rapidly, multiple IPC calls fire in parallel. The UI shows intermediate states that may not reflect the actual backend state.
**Fix**: Disable the toggle button while a transition is in progress. Add an `isTransitioning` flag.
### 3. 🟢 Clipboard Error Handling
**Location**: Lines ~300-320
**Issue**: `navigator.clipboard.writeText()` can fail (permission denied, not in secure context). The code has no try/catch.
**Fix**:
```typescript
async function copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
toast.success('Copied!');
} catch {
toast.error('Failed to copy');
}
}
```
### 4. 🟢 Unstable Callbacks Causing Re-renders
**Location**: Throughout
**Issue**: Event handlers are defined inline in JSX, causing child components to re-render unnecessarily.
**Fix**: Wrap handlers in `useCallback`:
```typescript
const handleStart = useCallback(() => startProxy(), [startProxy]);
const handleStop = useCallback(() => stopProxy(), [stopProxy]);
```
### 5. 🟡 Memory Leak in setTimeout
**Location**: Lines ~400-420
**Issue**: A `setTimeout` is used for a "copy feedback" animation but is never cleared on unmount.
**Fix**: Use `useEffect` cleanup:
```typescript
useEffect(() => {
const timer = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(timer);
}, [copied]);
```
### 6. 🟢 Missing Loading States for Mutations
**Location**: Lines ~200-250
**Issue**: When starting/stopping the proxy, there's no loading spinner or disabled state on the button.
**Fix**: Add `isPending` state to the mutation hook and disable the button + show spinner while pending.
### 7. 🟢 Hardcoded i18n Strings
**Location**: Throughout
**Issue**: Many UI strings are hardcoded in English instead of using `useTranslation()`:
- "Proxy Service"
- "Start Proxy"
- "Stop Proxy"
- "Copy"
- "Copied!"
**Fix**: Extract all strings to `src/localization/i18n.ts` and use `t('proxy.startProxy')`, etc.
### 8. 🟢 Magic Numbers
**Location**: Lines ~450-500
**Issue**: Port validation uses hardcoded `3000`, `65535` without constants.
**Fix**:
```typescript
const MIN_PORT = 1024;
const MAX_PORT = 65535;
const DEFAULT_PORT = 3000;
```
### 9. 🟢 Unsafe Type Cast
**Location**: Lines ~550-600
**Issue**: `event.target.value` is cast to `Protocol` without validation.
**Fix**:
```typescript
const protocol = event.target.value;
if (!PROTOCOLS.includes(protocol)) return;
setProtocol(protocol as Protocol);
```
### 10. 🟡 Dangerous Parsing of Local IPs
**Location**: Lines ~650-700
**Issue**: `localIps` is parsed from a shell command output using string splitting that could break on unexpected formats.
**Fix**: Use a robust parser or, better, expose `os.networkInterfaces()` via a safe IPC endpoint.
### 11. 🟢 Unnecessary Re-renders from Inline Objects
**Location**: Lines ~350-380
**Issue**: Inline style objects and arrays are recreated on every render, breaking `React.memo` optimizations in child components.
**Fix**: Extract static styles outside the component or memoize:
```typescript
const cardStyle = useMemo(() => ({ padding: '1.5rem' }), []);
```
### 12. 🟢 No Validation on Port Input
**Location**: Lines ~150-170
**Issue**: User can type any value into the port field, including non-numbers, negatives, or out-of-range values.
**Fix**: Add input validation:
```typescript
<input
type="number"
min={1024}
max={65535}
value={port}
onChange={(e) => {
const value = parseInt(e.target.value, 10);
if (value >= 1024 && value <= 65535) setPort(value);
}}
/>
```
---
## Testing Recommendations
- Add unit tests for `useProxyConfig` hook (mock IPC client)
- Test race conditions: rapid start/stop clicks
- Test clipboard failure path
- Test port validation edge cases (0, 80, 65536, NaN)
- Test with `react-testing-library` + `user-event`
@@ -0,0 +1,141 @@
# Proxy Page — Architecture Overview
> Generated from explorer agent mapping of proxy-related files
> Date: 2026-04-22
## File Map
### Frontend
| File | Lines | Role |
|------|-------|------|
| `src/routes/proxy.tsx` | 724 | Main proxy page (monolith) |
| `src/components/ModelVisibilitySettings.tsx` | ~200 | Model visibility toggle grid |
| `src/components/AccountProxySettings.tsx` | ~180 | Per-account proxy configuration |
| `src/hooks/useCloudAccounts.ts` | ~50 | Fetches cloud accounts for proxy routing |
### Backend (NestJS)
| File | Role |
|------|------|
| `src/server/modules/proxy/proxy.module.ts` | NestJS module definition |
| `src/server/modules/proxy/proxy.service.ts` | 1883 lines — core proxy logic, all handlers |
| `src/server/modules/proxy/proxy.controller.ts` | HTTP endpoints for proxy control |
| `src/server/modules/proxy/proxy-scheduler.service.ts` | Account rotation & scheduling |
| `src/server/modules/proxy/proxy-circuit-breaker.service.ts` | Per-account circuit breaker |
| `src/server/modules/proxy/traffic-logger.service.ts` | Request/response logging |
| `src/server/modules/proxy/proxy-metrics.service.ts` | Prometheus metrics |
| `src/server/modules/proxy/proxy-model-mapper.service.ts` | Model name resolution |
| `src/server/modules/proxy/proxy-parity.service.ts` | Parity testing |
| `src/server/modules/proxy/proxy-replay.service.ts` | Request replay |
| `src/server/modules/proxy/proxy-config.service.ts` | Config management |
| `src/server/modules/proxy/proxy-upstream.service.ts` | Upstream proxy support |
### IPC Layer
| File | Role |
|------|------|
| `src/ipc/router.ts` | Main IPC router composition |
| `src/ipc/proxy/router.ts` | Proxy-specific IPC endpoints |
| `src/ipc/manager.ts` | IPC client initialization |
### Types & Schema
| File | Role |
|------|------|
| `src/types/config.ts` | `ProxyConfig` Zod schema — reveals hidden fields |
| `src/types/proxy.ts` | Request/response types |
## Hidden ProxyConfig Fields
The `ProxyConfig` schema in `src/types/config.ts` contains many fields never shown in the UI:
```typescript
interface ProxyConfig {
// Shown in UI
enabled: boolean;
port: number;
protocol: 'http' | 'https';
apiKey: string;
// Hidden from UI
scheduler: {
maxRequestsPerAccount: number;
maxWaitTime: number;
retryAttempts: number;
backoffStrategy: 'exponential' | 'linear' | 'fixed';
priorityAccounts: string[];
};
upstreamProxy?: {
url: string;
auth?: { username: string; password: string };
bypassList: string[];
};
circuitBreaker: {
failureThreshold: number;
recoveryTimeout: number;
halfOpenMaxCalls: number;
};
logging: {
enabled: boolean;
maxEntries: number;
retentionDays: number;
};
metrics: {
enabled: boolean;
histogramBuckets: number[];
};
modelMappings: Array<{
from: string;
to: string;
provider: string;
enabled: boolean;
}>;
}
```
## Data Flow
```
┌─────────────────┐ IPC ┌──────────────────┐
│ proxy.tsx │ ◄──────────► │ proxy/router.ts │
│ (React UI) │ │ (IPC handlers) │
└─────────────────┘ └────────┬─────────┘
│
▼
┌──────────────────────┐
│ ProxyController │
│ (HTTP endpoints) │
└────────┬─────────────┘
│
▼
┌──────────────────────┐
│ ProxyService │
│ (Core orchestrator) │
└────────┬─────────────┘
│
┌──────────────────┼──────────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌───────────────┐ ┌──────────────┐
│ Scheduler │ │ CircuitBreaker│ │Model Mapper │
└─────────────┘ └───────────────┘ └──────────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌───────────────┐ ┌──────────────┐
│TrafficLogger│ │MetricsService │ │ParityService │
└─────────────┘ └───────────────┘ └──────────────┘
```
## Key Observations
1. **Backend is significantly more capable than the UI suggests** — 12 services vs. 1 page
2. **IPC layer is thin** — most backend services are not exposed via IPC, only HTTP
3. **ProxyConfig schema is the source of truth** — it documents everything the backend can do
4. **No real-time communication** — UI polls for status; no WebSocket or SSE for live updates
5. **Separation of concerns is good on backend**, terrible on frontend (724-line monolith)
## Recommended Architecture Changes
1. Extend `src/ipc/proxy/router.ts` to expose all `ProxyConfig` fields
2. Add IPC endpoints for:
- `proxy.getTrafficLogs()`
- `proxy.getCircuitBreakerStatus()`
- `proxy.getMetrics()`
- `proxy.replayRequest()`
3. Create a WebSocket or SSE channel for live traffic updates
4. Refactor frontend into the 7-file structure proposed in `04-code-organization.md`
-1
View File
@@ -345,7 +345,6 @@ Documentation/usage lookup:
- Use `context7` for latest dependency usage. - Use `context7` for latest dependency usage.
## 🚨 Local Quality Checks (Optional Flow) ## 🚨 Local Quality Checks (Optional Flow)
After a set of changes, run these three checks in parallel instead of full lint immediately: After a set of changes, run these three checks in parallel instead of full lint immediately:
+1 -1
View File
@@ -301,7 +301,7 @@
### Added ### Added
- Initial release of Antigravity Manager - Initial release of Gemini Nexus
- Multi-account management for Google Gemini and Claude - Multi-account management for Google Gemini and Claude
- Real-time quota monitoring - Real-time quota monitoring
- Intelligent auto-switching capabilities - Intelligent auto-switching capabilities
+6 -6
View File
@@ -1,8 +1,8 @@
# Contributing to Antigravity Manager # Contributing to Gemini Nexus
First off, thank you for considering contributing to Antigravity Manager! 🎉 First off, thank you for considering contributing to Gemini Nexus! 🎉
It's people like you that make Antigravity Manager such a great tool. We welcome contributions from everyone, whether it's a bug report, feature suggestion, documentation improvement, or code contribution. It's people like you that make Gemini Nexus such a great tool. We welcome contributions from everyone, whether it's a bug report, feature suggestion, documentation improvement, or code contribution.
## 📋 Table of Contents ## 📋 Table of Contents
@@ -24,8 +24,8 @@ This project and everyone participating in it is governed by our [Code of Conduc
1. **Fork the repository** on GitHub 1. **Fork the repository** on GitHub
2. **Clone your fork** locally: 2. **Clone your fork** locally:
```bash ```bash
git clone https://github.com/YOUR_USERNAME/AntigravityManager.git git clone https://github.com/YOUR_USERNAME/GeminiNexusManager.git
cd AntigravityManager cd Gemini NexusManager
``` ```
3. **Add the upstream remote**: 3. **Add the upstream remote**:
```bash ```bash
@@ -178,7 +178,7 @@ Have an idea? Please [create an issue](https://github.com/Draculabo/AntigravityM
## 🙏 Thank You ## 🙏 Thank You
Your contributions help make Antigravity Manager better for everyone. Thank you for taking the time to contribute! Your contributions help make Gemini Nexus better for everyone. Thank you for taking the time to contribute!
--- ---
+41 -211
View File
@@ -1,50 +1,41 @@
<p align="center"> <p align="center">
<img src="docs/assets/logo.png" alt="Antigravity Manager" width="128" height="128" /> <img src="docs/assets/logo.png" alt="Gemini Nexus" width="128" height="128" />
</p> </p>
<h1 align="center">Antigravity Manager</h1> <h1 align="center">Gemini Nexus</h1>
<p align="center"> <p align="center">
<strong>🚀 Professional multi-account manager for Google Gemini & Claude AI</strong> <strong>🚀 Professional multi-account manager for Google Gemini & Claude AI</strong>
</p> </p>
<p align="center"> <p align="center">
English | <a href="README.zh-CN.md">简体中文</a> English | <a href="README.pt-BR.md">Português (Brasil)</a>
</p> </p>
<p align="center"> <p align="center">
<a href="https://github.com/Draculabo/AntigravityManager/actions/workflows/testing.yaml"> <a href="https://github.com/Draculabo/GeminiNexus/actions/workflows/testing.yaml">
<img src="https://github.com/Draculabo/AntigravityManager/actions/workflows/testing.yaml/badge.svg" alt="Tests" /> <img src="https://github.com/Draculabo/GeminiNexus/actions/workflows/testing.yaml/badge.svg" alt="Tests" />
</a> </a>
<a href="https://github.com/Draculabo/AntigravityManager/actions/workflows/lint.yaml"> <a href="https://github.com/Draculabo/GeminiNexus/actions/workflows/lint.yaml">
<img src="https://github.com/Draculabo/AntigravityManager/actions/workflows/lint.yaml/badge.svg" alt="Lint" /> <img src="https://github.com/Draculabo/GeminiNexus/actions/workflows/lint.yaml/badge.svg" alt="Lint" />
</a> </a>
<a href="https://github.com/Draculabo/AntigravityManager/releases"> <a href="https://github.com/Draculabo/GeminiNexus/releases">
<img src="https://img.shields.io/github/v/release/Draculabo/AntigravityManager?style=flat-square" alt="Release" /> <img src="https://img.shields.io/github/v/release/Draculabo/GeminiNexus?style=flat-square" alt="Release" />
</a> </a>
<a href="https://github.com/Draculabo/AntigravityManager/releases"> <a href="https://github.com/Draculabo/GeminiNexus/releases">
<img src="https://img.shields.io/github/downloads/Draculabo/AntigravityManager/total?style=flat-square&color=blue" alt="Downloads" /> <img src="https://img.shields.io/github/downloads/Draculabo/GeminiNexus/total?style=flat-square&color=blue" alt="Downloads" />
</a> </a>
<a href="https://github.com/Draculabo/AntigravityManager/blob/main/LICENSE"> <a href="https://github.com/Draculabo/GeminiNexus/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Draculabo/AntigravityManager?style=flat-square" alt="License" /> <img src="https://img.shields.io/github/license/Draculabo/GeminiNexus?style=flat-square" alt="License" />
</a> </a>
<a href="https://github.com/Draculabo/AntigravityManager/stargazers">
<img src="https://img.shields.io/github/stars/Draculabo/AntigravityManager?style=flat-square" alt="Stars" />
</a>
</p>
<p align="center">
<img src="https://img.shields.io/badge/Electron-191970?style=for-the-badge&logo=Electron&logoColor=white" alt="Electron" />
<img src="https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB" alt="React" />
<img src="https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript" />
<img src="https://img.shields.io/badge/Tailwind_CSS-38B2AC?style=for-the-badge&logo=tailwind-css&logoColor=white" alt="TailwindCSS" />
</p> </p>
--- ---
## 📖 Table of Contents ## 📖 Table of Contents
- [Why Antigravity Manager?](#-why-antigravity-manager) - [Why Gemini Nexus?](#-why-gemini-nexus)
- [Improvements over Base Project](#-improvements-over-base-project)
- [Features](#-features) - [Features](#-features)
- [Screenshots](#-screenshots) - [Screenshots](#-screenshots)
- [Quick Start](#-quick-start) - [Quick Start](#-quick-start)
@@ -57,9 +48,9 @@
--- ---
## ✨ Why Antigravity Manager? ## ✨ Why Gemini Nexus?
When using Antigravity IDE, have you ever encountered these problems? When using your favorite IDEs, have you ever encountered these problems?
- 😫 Single account quota runs out quickly, requiring frequent manual switching - 😫 Single account quota runs out quickly, requiring frequent manual switching
- 🔄 Managing multiple Google/Claude accounts is cumbersome - 🔄 Managing multiple Google/Claude accounts is cumbersome
@@ -67,7 +58,7 @@ When using Antigravity IDE, have you ever encountered these problems?
- ⏰ Worried about missing quota reset times - ⏰ Worried about missing quota reset times
- 🔌 Need a reliable local API proxy for development tools - 🔌 Need a reliable local API proxy for development tools
**Antigravity Manager** is here to solve these problems! It's a professional Electron desktop app that helps you: **Gemini Nexus** is here to solve these problems! It's a professional Electron desktop app that helps you:
- ✅ **Unlimited Account Pool** - Add any number of Google Gemini / Claude accounts - ✅ **Unlimited Account Pool** - Add any number of Google Gemini / Claude accounts
- ✅ **Smart Auto-Switching** - Automatically switch to the next available account when quota is low or rate-limited - ✅ **Smart Auto-Switching** - Automatically switch to the next available account when quota is low or rate-limited
@@ -77,6 +68,19 @@ When using Antigravity IDE, have you ever encountered these problems?
--- ---
## 🌟 Improvements over Base Project
This project contains significant development improvements, bug fixes, and configuration enhancements compared to the original base project.
Key improvements include:
- **Enhanced API Management UI:** Implemented dynamic model selectors and "Copy API Name" features to streamline integration with other tools.
- **Robust SSE Streaming:** Fixed critical Server-Sent Events (SSE) streaming bugs in the `/v1/chat/completions` proxy endpoint to perfectly support IDEs like Cursor, OpenCode, and Windsurf.
- **Rebranding and Localization:** Complete rebranding to Gemini Nexus with improved Portuguese (Brazil) localization and English defaults.
- **Agentic Capabilities:** Integration of advanced AI developer agents and skill frameworks (GSD, AutoResearch, Superpowers) directly into the project ecosystem for rapid autonomous development.
- **Build & Dev Env:** Better cross-platform build configurations, updated schemas, and automated toolchain processes.
---
## 🎯 Features ## 🎯 Features
<table> <table>
@@ -116,24 +120,6 @@ When using Antigravity IDE, have you ever encountered these problems?
</ul> </ul>
</td> </td>
</tr> </tr>
<tr>
<td width="50%">
<h3>💾 Account Backup</h3>
<ul>
<li>Capture snapshots of account state</li>
<li>Fast switching between saved accounts</li>
<li>View, organize, and delete snapshots</li>
</ul>
</td>
<td width="50%">
<h3>⚙️ Process Control</h3>
<ul>
<li>Auto-detect if Antigravity is running</li>
<li>Launch via URI protocol or executable</li>
<li>Graceful close or force kill</li>
</ul>
</td>
</tr>
<tr> <tr>
<td width="50%"> <td width="50%">
<h3>🔌 Local API Proxy</h3> <h3>🔌 Local API Proxy</h3>
@@ -154,19 +140,6 @@ When using Antigravity IDE, have you ever encountered these problems?
</tr> </tr>
</table> </table>
### Additional Features
- **🖥️ System Tray** - Background mode with tray icon and right-click menu
- **🔗 IDE Sync** - Automatically scan and import accounts from IDE's `state.vscdb`
- **📦 Batch Operations** - Batch refresh and delete multiple accounts
- **📤 JSON Export/Import** - Export and import account pools with schema validation and deduplication
- **🔔 Desktop Notifications** - Configurable alerts when model quota drops below your threshold
- **🌐 Per-Account Proxy** - Route individual accounts through their own HTTP/SOCKS5 proxy
- **📊 Smart Sorting** - Sort accounts by recently used, overall quota, or specific model groups
- **📋 Compact Layout** - Dense horizontal view to maximize visible accounts
- **🌏 Internationalization** - Multi-language support (English / 中文 / Русский)
- **🎨 Modern UI** - Built with React, TailwindCSS, and Shadcn UI
--- ---
## 📸 Screenshots ## 📸 Screenshots
@@ -175,86 +148,23 @@ When using Antigravity IDE, have you ever encountered these problems?
<img src="docs/assets/screenshot-main.png" alt="Main Interface" width="80%" /> <img src="docs/assets/screenshot-main.png" alt="Main Interface" width="80%" />
</p> </p>
<p align="center">
<img src="docs/assets/screenshot-proxy.png" alt="Proxy Interface" width="48%" />
<img src="docs/assets/screenshot-setting.png" alt="Settings Interface" width="48%" />
</p>
--- ---
## � Quick Start ## ⚡ Quick Start
### Download
Download the latest release for your platform from the [Releases](https://github.com/Draculabo/AntigravityManager/releases) page.
| Platform | Download |
|----------|----------|
| Windows (x64/ARM64) | [.exe installer](https://github.com/Draculabo/AntigravityManager/releases/latest) |
| macOS | [.dmg installer](https://github.com/Draculabo/AntigravityManager/releases/latest) |
| Linux | [.deb / .rpm](https://github.com/Draculabo/AntigravityManager/releases/latest) |
| NixOS / Nix | `nix run github:Draculabo/AntigravityManager` |
### ❄️ Nix Integration
You can integrate Antigravity Manager into your Nix configuration using the provided flake.
#### 🛠️ NixOS / Home Manager
Add the flake to your `flake.nix` inputs:
```nix
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
antigravity-manager.url = "github:Draculabo/AntigravityManager";
};
```
To integrate with your system, add `antigravity-manager.overlays.default` to your `nixpkgs.overlays`. This ensures the package is correctly built against your own `nixpkgs` instance and respects your global configuration.
```nix
# Add to your NixOS/Home Manager configuration
{
nixpkgs.overlays = [ inputs.antigravity-manager.overlays.default ];
# Antigravity Manager has an unfree license (cc-by-nc-sa-40)
nixpkgs.config.allowUnfree = true;
environment.systemPackages = [
pkgs.antigravity-manager
];
}
```
#### 💻 Development Shell
If you're using the overlay above, you can simply add it to your `devShell`:
```nix
devShells.default = pkgs.mkShell {
packages = [
pkgs.antigravity-manager
];
};
```
> [!NOTE]
> Since the package is unfree, you **must** have `allowUnfree = true;` enabled in your `nixpkgs` configuration for it to evaluate correctly.
### Build from Source ### Build from Source
#### Prerequisites #### Prerequisites
- Node.js v18 or higher - Node.js v18 or higher
- npm or yarn - npm or pnpm
#### Steps #### Steps
```bash ```bash
# Clone the repository # Clone the repository
git clone https://github.com/Draculabo/AntigravityManager.git git clone https://github.com/Draculabo/GeminiNexus.git
cd AntigravityManager cd GeminiNexus
# Install dependencies # Install dependencies
npm install npm install
@@ -268,56 +178,15 @@ npm run make
--- ---
## �🛠️ Tech Stack ## 🛠️ Tech Stack
| Category | Technologies | | Category | Technologies |
|----------|-------------| |----------|-------------|
| **Core** | [Electron](https://www.electronjs.org/), [React](https://react.dev/), [TypeScript](https://www.typescriptlang.org/) | | **Core** | [Electron](https://www.electronjs.org/), [React](https://react.dev/), [TypeScript](https://www.typescriptlang.org/) |
| **Build Tool** | [Vite](https://vitejs.dev/) | | **Build Tool** | [Vite](https://vitejs.dev/) |
| **Styling** | [TailwindCSS](https://tailwindcss.com/), [Shadcn UI](https://ui.shadcn.com/) | | **Styling** | [TailwindCSS](https://tailwindcss.com/), [Shadcn UI](https://ui.shadcn.com/) |
| **State** | [TanStack Query](https://tanstack.com/query/latest), [TanStack Router](https://tanstack.com/router/latest) | | **State** | [TanStack Query](https://tanstack.com/query/latest) |
| **Database** | [Better-SQLite3](https://github.com/WiseLibs/better-sqlite3) | | **Database** | [Better-SQLite3](https://github.com/WiseLibs/better-sqlite3) |
| **Testing** | [Vitest](https://vitest.dev/), [Playwright](https://playwright.dev/) |
---
## � Development
### Available Scripts
| Command | Description |
|---------|-------------|
| `npm start` | Start the app in development mode |
| `npm run lint` | Run ESLint to check for code issues |
| `npm run format:write` | Format code with Prettier |
| `npm run test:unit` | Run unit tests with Vitest |
| `npm run test:e2e` | Run E2E tests with Playwright |
| `npm run test:all` | Run all tests |
| `npm run type-check` | Run TypeScript type checking |
| `npm run make` | Build production packages |
### Project Structure
```
AntigravityManager/
├── src/
│ ├── main.ts # Electron main process
│ ├── preload.ts # Preload script
│ ├── renderer/ # React renderer process
│ ├── ipc/ # IPC communication handlers
│ └── server/ # Built-in server
├── docs/ # Documentation and assets
└── .github/ # GitHub configuration
```
---
## 🔍 Debugging Docs
If you want to inspect Antigravity or Antigravity Manager traffic with Proxyman, start here:
- [Proxyman Installation and Basic Setup on Windows](docs/proxyman-install.md)
- [Proxyman Debugging Guide for Antigravity and Antigravity Manager](docs/proxyman-debugging.md)
--- ---
@@ -342,50 +211,11 @@ Please check:
</details> </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>
Please submit issues or suggestions via [GitHub Issues](https://github.com/Draculabo/AntigravityManager/issues).
</details>
---
## 🌟 Star History
<a href="https://github.com/Draculabo/AntigravityManager/stargazers">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Draculabo/AntigravityManager&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Draculabo/AntigravityManager&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Draculabo/AntigravityManager&type=Date" />
</picture>
</a>
--- ---
## 🤝 Contributing ## 🤝 Contributing
Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details. Contributions are welcome! Please read `CONTRIBUTING.md` for details.
We follow the [Contributor Covenant](CODE_OF_CONDUCT.md) Code of Conduct.
--- ---
@@ -406,6 +236,6 @@ We follow the [Contributor Covenant](CODE_OF_CONDUCT.md) Code of Conduct.
--- ---
<p align="center"> ## 🙏 Credits
If this project helps you, please give it a ⭐ Star!
</p> **Gemini Nexus** is a significantly enhanced and expanded version of the original project [AntigravityManager](https://github.com/Draculabo/AntigravityManager) created by [Draculabo](https://github.com/Draculabo). All fundamental architecture and design were made by the original author.
+146
View File
@@ -0,0 +1,146 @@
<p align="center">
<img src="docs/assets/logo.png" alt="Gemini Nexus" width="128" height="128" />
</p>
<h1 align="center">Gemini Nexus</h1>
<p align="center">
<strong>🚀 Gerenciador multi-contas profissional para Google Gemini & Claude AI</strong>
</p>
<p align="center">
<a href="README.md">English</a> | Português (Brasil)
</p>
<p align="center">
<a href="https://github.com/Draculabo/GeminiNexus/actions/workflows/testing.yaml">
<img src="https://github.com/Draculabo/GeminiNexus/actions/workflows/testing.yaml/badge.svg" alt="Tests" />
</a>
<a href="https://github.com/Draculabo/GeminiNexus/actions/workflows/lint.yaml">
<img src="https://github.com/Draculabo/GeminiNexus/actions/workflows/lint.yaml/badge.svg" alt="Lint" />
</a>
<a href="https://github.com/Draculabo/GeminiNexus/releases">
<img src="https://img.shields.io/github/v/release/Draculabo/GeminiNexus?style=flat-square" alt="Release" />
</a>
</p>
---
## ✨ Por que o Gemini Nexus?
Quando você usa suas IDEs favoritas, já encontrou estes problemas?
- 😫 A cota da sua única conta acaba rápido, exigindo trocas manuais frequentes
- 🔄 Gerenciar múltiplas contas do Google/Claude é cansativo
- 📊 Você não sabe quanta cota resta na conta atual
- 🔌 Precisa de um proxy local e confiável para suas ferramentas de desenvolvimento
**Gemini Nexus** está aqui para resolver tudo isso! Ele é um app desktop profissional construído em Electron que te ajuda a:
- ✅ **Contas Ilimitadas** - Adicione quantas contas Google Gemini / Claude quiser
- ✅ **Troca Automática** - Troca inteligentemente para a próxima conta disponível quando o limite é atingido
- ✅ **Monitoramento em Tempo Real** - Visualize o uso de cota de todas as contas
- ✅ **Proxy de API Local** - Servidor proxy integrado compatível com OpenAI/Anthropic
- ✅ **Criptografia Segura** - Criptografia AES-256-GCM para seus dados sensíveis
---
## 🌟 Melhorias sobre o Projeto Base
Este projeto contém melhorias significativas de desenvolvimento, correção de erros e melhorias de configuração em relação ao projeto original base.
Principais melhorias incluem:
- **Interface de Gerenciamento de API Aprimorada:** Seletores dinâmicos de modelos e recursos de "Copiar Nome da API" implementados para facilitar a integração com outras ferramentas.
- **Streaming Robusto (SSE):** Correção de bugs críticos no streaming via Server-Sent Events (SSE) no endpoint proxy `/v1/chat/completions` para suportar perfeitamente IDEs como Cursor, OpenCode e Windsurf.
- **Rebranding e Localização:** Rebranding completo para Gemini Nexus com traduções melhoradas em Português (Brasil) e padrões em Inglês.
- **Capacidades de Agentes:** Integração direta de frameworks avançados de agentes desenvolvedores de IA e skills (GSD, AutoResearch, Superpowers) no ecossistema do projeto para desenvolvimento autônomo rápido.
- **Ambiente de Build e Dev:** Melhores configurações de build cross-platform, schemas atualizados e processos de toolchain automatizados.
---
## 🎯 Funcionalidades
<table>
<tr>
<td width="50%">
<h3>☁️ Pool de Contas na Nuvem</h3>
<ul>
<li>Adicione contas via OAuth do Google e Anthropic</li>
<li>Mostra avatar, e-mail, status e último horário de uso</li>
</ul>
</td>
<td width="50%">
<h3>📊 Monitoramento de Cota</h3>
<ul>
<li>Suporte multi-modelo: gemini-pro, claude-3-5-sonnet, etc.</li>
<li>Barras de progresso visuais com indicadores de cores</li>
</ul>
</td>
</tr>
<tr>
<td width="50%">
<h3>🔄 Troca Automática</h3>
<ul>
<li>Modo de pool ilimitado com seleção inteligente</li>
<li>Monitoramento a cada 5 minutos em segundo plano</li>
</ul>
</td>
<td width="50%">
<h3>🔌 Proxy Local</h3>
<ul>
<li>Compatível com API da OpenAI & Anthropic</li>
<li>Mapeamento de modelos customizável (ex: Claude → Gemini)</li>
</ul>
</td>
</tr>
</table>
---
## ⚡ Começo Rápido
### Construindo pelo Código Fonte
#### Pré-requisitos
- Node.js v18 ou superior
- npm
#### Passos
```bash
# Clone o repositório
git clone https://github.com/Draculabo/GeminiNexus.git
cd GeminiNexus
# Instale as dependências
npm install
# Inicie o modo de desenvolvimento
npm start
# Construa para produção
npm run make
```
---
## 📄 Licença
[CC BY-NC-SA 4.0](LICENSE)
---
## ⚠️ Aviso Legal
> [!WARNING]
> **Apenas para Fins Educacionais**
>
> Este projeto destina-se exclusivamente a fins de pesquisa e educação. Ele é fornecido "como está" sem qualquer garantia. **O uso comercial é estritamente proibido.**
---
## 🙏 Créditos
**Gemini Nexus** é uma versão significativamente aprimorada e expandida baseada no projeto original [AntigravityManager](https://github.com/Draculabo/AntigravityManager) criado por [Draculabo](https://github.com/Draculabo). Toda a arquitetura fundamental e design do projeto foram criados pelo autor original.
-411
View File
@@ -1,411 +0,0 @@
<p align="center">
<img src="docs/assets/logo.png" alt="Antigravity Manager" width="128" height="128" />
</p>
<h1 align="center">Antigravity Manager</h1>
<p align="center">
<strong>🚀 专业的 Google Gemini & Claude AI 多账号管理器</strong>
</p>
<p align="center">
<a href="README.md">English</a> | 简体中文
</p>
<p align="center">
<a href="https://github.com/Draculabo/AntigravityManager/actions/workflows/testing.yaml">
<img src="https://github.com/Draculabo/AntigravityManager/actions/workflows/testing.yaml/badge.svg" alt="Tests" />
</a>
<a href="https://github.com/Draculabo/AntigravityManager/actions/workflows/lint.yaml">
<img src="https://github.com/Draculabo/AntigravityManager/actions/workflows/lint.yaml/badge.svg" alt="Lint" />
</a>
<a href="https://github.com/Draculabo/AntigravityManager/releases">
<img src="https://img.shields.io/github/v/release/Draculabo/AntigravityManager?style=flat-square" alt="Release" />
</a>
<a href="https://github.com/Draculabo/AntigravityManager/releases">
<img src="https://img.shields.io/github/downloads/Draculabo/AntigravityManager/total?style=flat-square&color=blue" alt="Downloads" />
</a>
<a href="https://github.com/Draculabo/AntigravityManager/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Draculabo/AntigravityManager?style=flat-square" alt="License" />
</a>
<a href="https://github.com/Draculabo/AntigravityManager/stargazers">
<img src="https://img.shields.io/github/stars/Draculabo/AntigravityManager?style=flat-square" alt="Stars" />
</a>
</p>
<p align="center">
<img src="https://img.shields.io/badge/Electron-191970?style=for-the-badge&logo=Electron&logoColor=white" alt="Electron" />
<img src="https://img.shields.io/badge/React-20232A?style=for-the-badge&logo=react&logoColor=61DAFB" alt="React" />
<img src="https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white" alt="TypeScript" />
<img src="https://img.shields.io/badge/Tailwind_CSS-38B2AC?style=for-the-badge&logo=tailwind-css&logoColor=white" alt="TailwindCSS" />
</p>
---
## 📖 目录
- [为什么选择 Antigravity Manager?](#-为什么选择-antigravity-manager)
- [功能特性](#-功能特性)
- [截图预览](#-截图预览)
- [快速开始](#-快速开始)
- [技术栈](#️-技术栈)
- [开发指南](#-开发指南)
- [调试文档](#-调试文档)
- [常见问题](#-常见问题)
- [贡献指南](#-贡献指南)
- [许可证](#-许可证)
---
## ✨ 为什么选择 Antigravity Manager?
在使用 Antigravity IDE 时,你是否遇到过这些问题?
- 😫 单个账号额度很快用完,需要频繁手动切换
- 🔄 管理多个 Google/Claude 账号非常麻烦
- 📊 不知道当前账号还剩多少额度
- ⏰ 担心错过额度重置时间
- 🔌 需要可靠的本地 API 代理用于开发工具
**Antigravity Manager** 就是为解决这些问题而生的!它是一个专业的 Electron 桌面应用,帮助你:
- ✅ **无限账号池** - 添加任意数量的 Google Gemini / Claude 账号
- ✅ **智能自动切换** - 额度不足或被限速时自动切换到下一个可用账号
- ✅ **实时监控** - 可视化显示所有账号的额度使用情况
- ✅ **本地 API 代理** - 内置兼容 OpenAI/Anthropic 协议的代理服务器
- ✅ **安全加密** - AES-256-GCM 加密存储敏感信息
---
## 🎯 功能特性
<table>
<tr>
<td width="50%">
<h3>☁️ 云账号池管理</h3>
<ul>
<li>通过 OAuth 添加无限 Google Gemini / Claude 账号</li>
<li>显示头像、邮箱、状态和最后使用时间</li>
<li>实时状态监控(活跃、限速、过期)</li>
</ul>
</td>
<td width="50%">
<h3>📊 实时额度监控</h3>
<ul>
<li>多模型支持:gemini-pro、claude-3-5-sonnet 等</li>
<li>可视化进度条配色指示器</li>
<li>自动刷新与手动刷新</li>
</ul>
</td>
</tr>
<tr>
<td width="50%">
<h3>🔄 智能自动切换</h3>
<ul>
<li>无限池模式,智能选择备用账号</li>
<li>额度低于 5% 或被限速时自动切换</li>
<li>后台每 5 分钟自动监控</li>
</ul>
</td>
<td width="50%">
<h3>🔐 安全优先</h3>
<ul>
<li>AES-256-GCM 加密敏感数据</li>
<li>集成操作系统原生凭证管理器</li>
<li>自动迁移旧版明文数据</li>
</ul>
</td>
</tr>
<tr>
<td width="50%">
<h3>💾 账号备份</h3>
<ul>
<li>捕获账号状态快照</li>
<li>在已保存的账号间快速切换</li>
<li>查看、整理和删除快照</li>
</ul>
</td>
<td width="50%">
<h3>⚙️ 进程控制</h3>
<ul>
<li>自动检测 Antigravity 是否运行</li>
<li>通过 URI 协议或可执行文件启动</li>
<li>优雅关闭或强制终止</li>
</ul>
</td>
</tr>
<tr>
<td width="50%">
<h3>🔌 本地 API 代理</h3>
<ul>
<li>兼容 OpenAI & Anthropic API 协议</li>
<li>可配置端口和请求超时</li>
<li>模型映射(如:Claude → Gemini)</li>
</ul>
</td>
<td width="50%">
<h3>🛠️ 开发者工具</h3>
<ul>
<li>内置 cURL & Python 代码生成</li>
<li>可视化服务状态监控</li>
<li>一键重新生成 API Key</li>
</ul>
</td>
</tr>
</table>
### 更多功能
- **🖥️ 系统托盘** - 后台运行,托盘图标和右键菜单
- **🔗 IDE 同步** - 自动扫描导入 IDE 的 `state.vscdb` 账号
- **📦 批量操作** - 批量刷新和删除多个账号
- **📤 JSON 导出/导入** - 导出和导入账号池,支持架构验证和去重
- **🔔 桌面通知** - 模型配额低于设定阈值时自动提醒
- **🌐 单账号代理** - 为每个账号单独配置 HTTP/SOCKS5 代理
- **📊 智能排序** - 按最近使用、总体配额或特定模型组排序
- **📋 紧凑布局** - 水平密集视图,最大化可见账号数量
- **🌏 国际化** - 多语言支持(English / 中文 / Русский)
- **🎨 现代 UI** - 基于 React、TailwindCSS 和 Shadcn UI 构建
---
## 📸 截图预览
<p align="center">
<img src="docs/assets/screenshot-main.png" alt="主界面" width="80%" />
</p>
<p align="center">
<img src="docs/assets/screenshot-proxy.png" alt="代理界面" width="48%" />
<img src="docs/assets/screenshot-setting.png" alt="设置界面" width="48%" />
</p>
---
## 🚀 快速开始
### 下载安装
从 [Releases](https://github.com/Draculabo/AntigravityManager/releases) 页面下载适合你平台的最新版本。
| 平台 | 下载链接 |
| ------------------- | ------------------------------------------------------------------------------ |
| Windows (x64/ARM64) | [.exe 安装包](https://github.com/Draculabo/AntigravityManager/releases/latest) |
| macOS | [.dmg 安装包](https://github.com/Draculabo/AntigravityManager/releases/latest) |
| Linux | [.deb / .rpm](https://github.com/Draculabo/AntigravityManager/releases/latest) |
| NixOS / Nix | `nix run github:Draculabo/AntigravityManager` |
### ❄️ Nix 集成
你可以通过项目提供的 flake 将 Antigravity Manager 集成到你的 Nix 配置中。
#### 🛠️ NixOS / Home Manager
先在你的 `flake.nix` 的 `inputs` 中加入:
```nix
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
antigravity-manager.url = "github:Draculabo/AntigravityManager";
};
```
然后把 `antigravity-manager.overlays.default` 添加到 `nixpkgs.overlays`。这样会基于你自己的 `nixpkgs` 实例构建,并继承你的全局配置。
```nix
# 添加到你的 NixOS/Home Manager 配置中
{
nixpkgs.overlays = [ inputs.antigravity-manager.overlays.default ];
# Antigravity Manager 使用非自由许可证 (cc-by-nc-sa-40)
nixpkgs.config.allowUnfree = true;
environment.systemPackages = [
pkgs.antigravity-manager
];
}
```
#### 💻 开发 Shell
如果你已经使用上面的 overlay,也可以直接在 `devShell` 里加入:
```nix
devShells.default = pkgs.mkShell {
packages = [
pkgs.antigravity-manager
];
};
```
> [!NOTE]
> 由于该包是非自由软件,你必须在 `nixpkgs` 配置中开启 `allowUnfree = true;`,否则会评估失败。
### 从源码构建
#### 前置要求
- Node.js v18 或更高版本
- npm 或 yarn
#### 步骤
```bash
# 克隆仓库
git clone https://github.com/Draculabo/AntigravityManager.git
cd AntigravityManager
# 安装依赖
npm install
# 启动开发模式
npm start
# 构建生产版本
npm run make
```
---
## 🛠️ 技术栈
| 类别 | 技术 |
| ------------ | ------------------------------------------------------------------------------------------------------------------- |
| **核心** | [Electron](https://www.electronjs.org/)、[React](https://react.dev/)、[TypeScript](https://www.typescriptlang.org/) |
| **构建工具** | [Vite](https://vitejs.dev/) |
| **样式** | [TailwindCSS](https://tailwindcss.com/)、[Shadcn UI](https://ui.shadcn.com/) |
| **状态管理** | [TanStack Query](https://tanstack.com/query/latest)、[TanStack Router](https://tanstack.com/router/latest) |
| **数据库** | [Better-SQLite3](https://github.com/WiseLibs/better-sqlite3) |
| **测试** | [Vitest](https://vitest.dev/)、[Playwright](https://playwright.dev/) |
---
## 💻 开发指南
### 可用脚本
| 命令 | 描述 |
| ---------------------- | ------------------------ |
| `npm start` | 启动开发模式 |
| `npm run lint` | 运行 ESLint 检查 |
| `npm run format:write` | 使用 Prettier 格式化代码 |
| `npm run test:unit` | 运行单元测试 |
| `npm run test:e2e` | 运行 E2E 测试 |
| `npm run test:all` | 运行所有测试 |
| `npm run type-check` | TypeScript 类型检查 |
| `npm run make` | 构建生产包 |
### 项目结构
```
AntigravityManager/
├── src/
│ ├── main.ts # Electron 主进程
│ ├── preload.ts # 预加载脚本
│ ├── renderer/ # React 渲染进程
│ ├── ipc/ # IPC 通信处理
│ └── server/ # 内置服务器
├── docs/ # 文档和资源
└── .github/ # GitHub 配置
```
---
## 🔍 调试文档
如果你希望用 Proxyman 抓取和排查 Antigravity 或 Antigravity Manager 的流量,请先阅读:
- [Proxyman Installation and Basic Setup on Windows](docs/proxyman-install.md)
- [Proxyman Debugging Guide for Antigravity and Antigravity Manager](docs/proxyman-debugging.md)
---
## ❓ 常见问题
<details>
<summary><b>Q: 程序无法启动怎么办?</b></summary>
请检查:
1. 确保已安装所有依赖:`npm install`
2. 检查 Node.js 版本是否 >= 18
3. 尝试删除 `node_modules` 后重新安装
</details>
<details>
<summary><b>Q: 账号登录失败?</b></summary>
1. 确保网络连接正常
2. 尝试清除应用数据后重新登录
3. 检查账号是否被 Google/Claude 限制
</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>
请通过 [GitHub Issues](https://github.com/Draculabo/AntigravityManager/issues) 提交问题或建议。
</details>
---
## 🌟 Star History
<a href="https://github.com/Draculabo/AntigravityManager/stargazers">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Draculabo/AntigravityManager&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Draculabo/AntigravityManager&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Draculabo/AntigravityManager&type=Date" />
</picture>
</a>
---
## 🤝 贡献指南
欢迎贡献代码!请阅读 [CONTRIBUTING.md](CONTRIBUTING.md) 了解详情。
我们遵循 [Contributor Covenant](CODE_OF_CONDUCT.md) 行为准则。
---
## 📄 许可证
[CC BY-NC-SA 4.0](LICENSE)
---
## ⚠️ 免责声明
> [!WARNING]
> **仅供学习研究使用**
>
> 本项目仅供教育和研究目的,按"原样"提供,不提供任何保证。**严禁商业使用。**
>
> 使用本软件即表示您同意不会将其用于任何商业目的,并自行负责确保您的使用符合所有适用法律法规。作者和贡献者对因使用本软件而产生的任何滥用或损害不承担责任。
---
<p align="center">
如果这个项目对你有帮助,请给一个 ⭐ Star 支持!
</p>
+4 -4
View File
@@ -2,7 +2,7 @@
## 🔒 Security Features ## 🔒 Security Features
Antigravity Manager takes security seriously. Here are the security measures we've implemented: Gemini Nexus takes security seriously. Here are the security measures we've implemented:
### Encryption ### Encryption
@@ -35,7 +35,7 @@ We only provide security updates for the latest version. Please ensure you're ru
## 🚨 Reporting a Vulnerability ## 🚨 Reporting a Vulnerability
We take all security vulnerabilities seriously. Thank you for helping to improve the security of Antigravity Manager. We take all security vulnerabilities seriously. Thank you for helping to improve the security of Gemini Nexus.
### How to Report ### How to Report
@@ -75,7 +75,7 @@ Please include the following information in your report:
To ensure the security of your data: To ensure the security of your data:
1. **Keep Updated**: Always use the latest version of Antigravity Manager 1. **Keep Updated**: Always use the latest version of Gemini Nexus
2. **System Security**: Keep your operating system updated 2. **System Security**: Keep your operating system updated
3. **Secure Environment**: Use the application on trusted devices only 3. **Secure Environment**: Use the application on trusted devices only
4. **Backup**: Regularly backup your account data using the built-in backup feature 4. **Backup**: Regularly backup your account data using the built-in backup feature
@@ -90,4 +90,4 @@ When we receive a security bug report, we will:
3. Prepare fixes for all supported versions 3. Prepare fixes for all supported versions
4. Release new versions as soon as possible 4. Release new versions as soon as possible
Thank you for helping keep Antigravity Manager and its users safe! Thank you for helping keep Gemini Nexus and its users safe!
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
+6 -6
View File
@@ -1,6 +1,6 @@
# Antigravity Manager CLI # Gemini Nexus CLI
A powerful command-line interface for managing multiple Google Cloud AI accounts in Antigravity IDE. Supports account switching, quota monitoring, token validation, and more. A powerful command-line interface for managing multiple Google Cloud AI accounts in Gemini Nexus IDE. Supports account switching, quota monitoring, token validation, and more.
## Features ## Features
@@ -147,9 +147,9 @@ agm doctor
## How It Works ## How It Works
The CLI interacts directly with the Antigravity Manager's encrypted database: The CLI interacts directly with the Gemini Nexus's encrypted database:
1. **Database Location**: Auto-discovers the database in `%APPDATA%\AntigravityManager` or IDE installation directory 1. **Database Location**: Auto-discovers the database in `%APPDATA%\GeminiNexus` or IDE installation directory
2. **Encryption**: Uses Windows DPAPI + AES-256-GCM to decrypt account tokens (same as the IDE) 2. **Encryption**: Uses Windows DPAPI + AES-256-GCM to decrypt account tokens (same as the IDE)
3. **Quota API**: Fetches live quota data from Google Cloud AI REST API 3. **Quota API**: Fetches live quota data from Google Cloud AI REST API
4. **Process Control**: Can start/stop the IDE executable automatically 4. **Process Control**: Can start/stop the IDE executable automatically
@@ -157,7 +157,7 @@ The CLI interacts directly with the Antigravity Manager's encrypted database:
## Troubleshooting ## Troubleshooting
**"Database not found" error:** **"Database not found" error:**
- Ensure Antigravity Manager has been run at least once - Ensure Gemini Nexus has been run at least once
- Check if accounts exist in the GUI first - Check if accounts exist in the GUI first
**"Failed to decrypt" error:** **"Failed to decrypt" error:**
@@ -175,7 +175,7 @@ The CLI interacts directly with the Antigravity Manager's encrypted database:
- Windows 10/11 - Windows 10/11
- Python 3.8+ - Python 3.8+
- Antigravity Manager (for database access) - Gemini Nexus (for database access)
## Development ## Development
+276
View File
@@ -0,0 +1,276 @@
**✅ Documento Completo: Integração com Custom Endpoint do OpenCode (Provedores Custom / OpenAI-Compatible)**
OpenCode (https://opencode.ai) é um agente de IA para terminal que usa o **Vercel AI SDK** para se comunicar com provedores de LLM. Ele suporta nativamente provedores customizados via o pacote `@ai-sdk/openai-compatible`, que segue o padrão **OpenAI Chat Completions API** (`/v1/chat/completions`).
Isso significa que **sua API precisa implementar exatamente o formato OpenAI-compatible** para que o OpenCode consiga conversar com ela diretamente.
---
### 1. Como Configurar um Provedor Custom no OpenCode
Crie ou edite o arquivo de configuração (recomendado: `~/.config/opencode/opencode.json` ou `opencode.json` na raiz do projeto):
```json
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"minha-ia-custom": {
"npm": "@ai-sdk/openai-compatible",
"name": "Minha IA Custom (OpenCode)",
"options": {
"baseURL": "https://sua-api.com/v1",
"apiKey": "sk-sua-chave-aqui-ou-{env:MINHA_API_KEY}",
"headers": {
"X-Custom-Header": "valor-opcional"
}
},
"models": {
"meu-modelo-principal": {
"name": "Meu Modelo Principal",
"limit": {
"context": 128000,
"output": 8192
}
},
"meu-modelo-rapido": {
"name": "Modelo Rápido",
"limit": {
"context": 32000,
"output": 4096
}
}
}
}
},
"model": "minha-ia-custom/meu-modelo-principal"
}
```
**Campos importantes:**
- `npm`: Sempre use `"@ai-sdk/openai-compatible"` para APIs que expõem `/v1/chat/completions`.
- `baseURL`: URL base da sua API (deve terminar com `/v1`).
- `apiKey`: Pode ser valor direto ou `{env:NOME_VARIAVEL}`.
- `models`: Defina os modelos que sua API expõe. O `limit` ajuda o OpenCode a gerenciar contexto.
- `model`: Define o modelo padrão no formato `provider_id/model_id`.
Depois de salvar, reinicie o OpenCode ou use `/models` para selecionar.
**Comando rápido para adicionar chave:**
```bash
opencode /connect
# Escolha "Other" → digite o provider_id (ex: minha-ia-custom) → cole a API key
```
---
### 2. Como o OpenCode Envia Requisições
O OpenCode (via AI SDK) faz chamadas **POST** para:
```
POST {baseURL}/chat/completions
```
**Headers enviados:**
- `Authorization: Bearer <sua-api-key>`
- `Content-Type: application/json`
- Headers customizados que você definir em `options.headers`
**Payload típico (exemplo real):**
```json
{
"model": "meu-modelo-principal",
"messages": [
{
"role": "system",
"content": "Você é um assistente de código experiente..."
},
{
"role": "user",
"content": "Crie uma função em Python que..."
}
],
"stream": true,
"temperature": 0.7,
"max_tokens": 8192,
"tools": [
/* array de tools se o agente estiver usando ferramentas */
],
"tool_choice": "auto"
}
```
**Parâmetros comuns que o OpenCode envia:**
- `messages` (array completo do histórico)
- `stream: true` (quase sempre, para UX em tempo real)
- `temperature`, `max_tokens`, `top_p`
- `tools` + `tool_choice` (quando usa agentes com ferramentas/MCP)
- `response_format` (às vezes)
- `providerOptions` (opções específicas do provedor – raras no openai-compatible)
---
### 3. Como o OpenCode Recebe e Processa Respostas
#### A. Streaming (recomendado – usado na maioria das interações)
Sua API deve responder com `Content-Type: text/event-stream` e eventos SSE:
```
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1712345678,"model":"meu-modelo-principal","choices":[{"index":0,"delta":{"content":"Olá"},"finish_reason":null}]}
data: {"id":"chatcmpl-123","choices":[{"index":0,"delta":{"content":"! Como"},"finish_reason":null}]}
data: [DONE]
```
O OpenCode processa cada chunk em tempo real.
#### B. Resposta não-streaming (completa)
```json
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1712345678,
"model": "meu-modelo-principal",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Resposta completa aqui..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 150,
"completion_tokens": 320,
"total_tokens": 470
}
}
```
#### Suporte a Tool Calling (essencial para agentes)
Se sua API suportar `tools`, o OpenCode pode:
1. Enviar `tools` na requisição.
2. Receber `tool_calls` na resposta.
3. Executar a ferramenta (via MCP ou built-in).
4. Enviar o resultado de volta como mensagem `tool`.
**Exemplo de resposta com tool call:**
```json
{
"choices": [
{
"message": {
"role": "assistant",
"tool_calls": [
{
"id": "call_123",
"type": "function",
"function": {
"name": "read_file",
"arguments": "{\"path\": \"src/app.ts\"}"
}
}
]
}
}
]
}
```
---
### 4. Como é Exibido no Chat do OpenCode (TUI)
- **Streaming**: Texto aparece caractere por caractere com efeito de digitação.
- **Markdown**: Suporte completo a código (syntax highlight), listas, tabelas, etc.
- **Tool Calls**: Mostra “Executando ferramenta: read_file...” + resultado.
- **Multi-turn**: Mantém histórico completo na conversa.
- **Erros**: Mostra mensagens de erro claras no terminal.
- **Contexto**: Respeita os limites de `context` e `output` que você definiu no config.
O OpenCode usa o TUI (Terminal User Interface) baseado em React/Ink para renderizar tudo de forma bonita.
---
### 5. Requisitos Mínimos da Sua API para Funcionar Perfeitamente
| Recurso | Obrigatório? | Recomendado? | Observação |
| ---------------------- | ------------ | ------------ | ---------------------------------- |
| `/v1/chat/completions` | Sim | - | Endpoint principal |
| Streaming (SSE) | Sim | - | Essencial para UX |
| Tool Calling | Não | Sim | Para agentes completos |
| System messages | Sim | - | - |
| Multi-turn history | Sim | - | - |
| Usage stats | Não | Sim | Mostra tokens gastos |
| Error handling | Sim | - | Retorne JSON de erro padrão OpenAI |
**Endpoint exato esperado:**
`POST https://sua-api.com/v1/chat/completions`
---
### 6. Exemplo Completo de Configuração + Teste
1. Configure o `opencode.json` como acima.
2. Rode:
```bash
opencode
```
3. Digite algo ou use `/models` para selecionar seu provedor.
4. Teste com:
```bash
curl -X POST https://sua-api.com/v1/chat/completions \
-H "Authorization: Bearer sk-..." \
-H "Content-Type: application/json" \
-d '{"model":"meu-modelo-principal","messages":[{"role":"user","content":"Olá"}],"stream":true}'
```
---
### 7. Troubleshooting Comum
- **“Route not found” ou requests indo para lugar errado** → Verifique se `baseURL` termina com `/v1` e não com `/v1/chat/completions`.
- **Custom provider não aparece** → Certifique-se que o ID do provider no `/connect` bate com a chave no `opencode.json`.
- **Sem streaming / resposta lenta** → Implemente SSE corretamente.
- **Tool calls não funcionam** → Sua API precisa retornar `tool_calls` no formato OpenAI exato.
- **Erro de autenticação** → Use `apiKey` ou `headers` corretamente.
---
### Referências Oficiais
- **Docs Principais**: https://opencode.ai/docs/providers/
- **Models**: https://opencode.ai/docs/models/
- **Config**: https://opencode.ai/docs/config/
- **Schema de Config**: https://opencode.ai/config.json
- **GitHub**: https://github.com/anomalyco/opencode
- **AI SDK OpenAI-Compatible**: https://ai-sdk.dev/providers/openai-compatible-providers
---
**Resumo Final para Você (que está construindo a API):**
Sua API **precisa ser 100% compatível** com o endpoint OpenAI `/v1/chat/completions` (streaming + tool calling recomendado).
O OpenCode vai:
1. Configurar via `opencode.json` (baseURL + apiKey)
2. Enviar requisições padrão OpenAI
3. Receber streaming ou resposta completa
4. Renderizar tudo lindamente no TUI com suporte a ferramentas
Se você implementar exatamente o padrão OpenAI Chat Completions, vai funcionar perfeitamente com o OpenCode.
Quer que eu monte um **exemplo de servidor mínimo** (em Node.js/Fastify ou Python/FastAPI) que já funcione com o OpenCode? Posso criar um template completo para você.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 390 KiB

+146
View File
@@ -0,0 +1,146 @@
# Brand Briefing — Gemini Nexus
## 1. Nome e Descrição
| Campo | Valor |
|-------|-------|
| **Nome** | Gemini Nexus |
| **Product Name** | Gemini Nexus |
| **Package Name** | gemini-nexus |
| **Versão** | 0.11.1 |
| **Descrição EN** | Professional multi-account manager for Google Gemini & Claude AI |
| **Descrição PT-BR** | Gerenciador multi-contas profissional para Google Gemini & Claude AI |
| **Autor** | evandrodevbr / Draculabo |
| **Licença** | CC-BY-NC-SA-4.0 (apenas fins educacionais) |
---
## 2. Propósito do Aplicativo
Gemini Nexus é um **aplicativo desktop profissional** (Electron) que funciona como um **hub central (nexus)** para desenvolvedores que usam IDEs com IA.
### Funcionalidades Principais
- **Pool ilimitado de contas**: Adicionar múltiplas contas Google Gemini / Claude via OAuth
- **Auto-switching inteligente**: Troca automática de conta quando a cota acaba ou há rate limit
- **Monitoramento em tempo real**: Barras de progresso coloridas para visualizar uso de quota
- **Proxy API local**: Servidor proxy integrado compatível OpenAI/Anthropic (porta 8045)
- **Segurança**: Criptografia AES-256-GCM para dados sensíveis
### Público-Alvo
- Desenvolvedores que usam IDEs com integração AI (Cursor, Windsurf, VS Code, Claude Code, etc.)
- Power users que precisam alternar entre múltiplas contas de IA
- Usuários que precisam de um proxy API local confiável
---
## 3. Tom de Voz / Personalidade
- **Profissional e técnica**: Termos como "Nexus", "Proxy", "Gateway", "Quota", "Circuit Breaker"
- **Confiável e estável**: Monitoramento, health checks, logging robusto
- **Developer-first**: Suporte a múltiplas IDEs, geração de cURL/Python
- **Moderna e minimalista**: Interface limpa, componentes modulares
- **Global**: Suporte a i18n (EN, PT-BR, ZH, RU, VI)
---
## 4. Estilo Visual Atual
### Tema
- Dual theme (claro/escuro) com detecção automática do sistema
- Extremamente minimalista e quase monocromático
### Paleta de Cores (Tailwind OKLCH)
| Modo | Background | Foreground | Primary | Destructive | Destaque |
|------|-----------|------------|---------|-------------|----------|
| **Claro** | oklch(0.99 0 0) — quase branco | oklch(0 0 0) — preto | Preto | Vermelho | Azul |
| **Escuro** | oklch(0 0 0) — preto puro | oklch(1 0 0) — branco | Branco | Vermelho escuro | — |
### Cores Funcionais
- **Emerald/Green (`#10b981`)** — status ativo, quota alta, running
- **Amber/Yellow** — quota média, alertas
- **Rose/Red** — quota baixa, erro, stopped
- **Blue** — AI credits, informações premium
### Tipografia
- **Geist** (sans-serif) — fonte principal moderna e geométrica (da Vercel)
- **Geist Mono** (monospace) — dados técnicos, números de quota
- **Tomorrow** (display/futurista) — possíveis títulos estilizados
### Características de UI
- Bordas arredondadas (`0.5rem` / 8px)
- Sombras sutis
- Cards com hover states suaves
- Interface limpa com espaçamento generoso
---
## 5. Assets Visuais Existentes
| Arquivo | Descrição |
|---------|-----------|
| `docs/assets/logo.png` | Logo antiga (Antigravity) — 128x128, usada no README |
| `docs/assets/screenshot-main.png` | Screenshot da interface principal |
| `docs/assets/screenshot-proxy.png` | Screenshot da aba proxy |
| `docs/assets/screenshot-setting.png` | Screenshot de settings |
| `src/assets/icon.png` | Ícone do app (também é o logo antigo) |
| `src/assets/tray.png` | Ícone da system tray |
| `images/icon.ico` / `images/icon.icns` | Ícones de build para Windows/Mac |
| `images/favicon-*.png` | Favicons em múltiplos tamanhos |
| `images/32x32.png`, `64x64.png`, `128x128.png`, `[email protected]` | Ícones para AppImage Linux |
| `src/assets/fonts/geist/` | Fonte Geist (principal) |
| `src/assets/fonts/geist-mono/` | Fonte Geist Mono (código/dados) |
| `src/assets/fonts/tomorrow/` | Fonte Tomorrow (display, 4 pesos) |
---
## 6. Conceitos Visuais Sugeridos para a Logo
### A. Nodo / Conexão (Nexus)
- Ponto central conectado a múltiplos pontos (contas gerenciadas)
- Círculo central com 2-3 linhas finas irradiando
- Dois círculos interligados (Gemini + Claude)
### B. Infinito / Loop (Gemini + Proxy)
- Símbolo de infinito (∞) modificado como circuito/loop de dados
- Referência à dualidade "Gemini" (gêmeos)
- Curva contínua elegante com seta indicando fluxo
### C. Cubo / Hexágono (Nexus / Hub)
- Hexágono ou cubo isométrico minimalista
- Linhas finas, perspectiva suave
- Face "aberta" ou conectada
### D. Monograma "GN"
- Letras "G" e "N" abstraídas como nodo de rede
- Estilo geométrico, similar a Tomorrow ou Geist
### E. Proxy / Pipe (Fluxo de Dados)
- Duas barras paralelas com seta passando entre elas
- "Pipe" minimalista — conduz tráfego entre APIs
---
## 7. Diretrizes para a Nova Logo
| Elemento | Especificação |
|----------|---------------|
| **Estilo** | Minimalista, geométrica, precisa, técnica |
| **Cores principais** | Preto (`#000000`) e branco (`#ffffff`) |
| **Cor de acento (opcional)** | Emerald (`#10b981`) para "ativo/online" |
| **Versões necessárias** | Dark mode e light mode |
| **Tamanhos** | De 16x16 (tray) até 512x512 (macOS) |
| **Monocromática** | Deve funcionar em preto e branco puro |
| **Tipografia do wordmark** | Geométrica sans-serif, peso medium/semibold, tracking levemente expandido |
---
## 8. Conclusão
O app pede uma logo que evoque **conexão/nexo** (Nexus) com **múltiplos pontos** (contas) de forma geométrica e limpa, usando primariamente preto/branco com um toque sutil de verde (emerald) para representar o estado "ativo/online" central ao propósito do app.
A logo deve transmitir:
- **Tecnologia** e **precisão**
- **Conectividade** e **hub central**
- **Profissionalismo** e **confiança**
- **Modernidade** e **minimalismo**
+1 -1
View File
@@ -1,6 +1,6 @@
# Cloud Account Management and Intelligent Switching # Cloud Account Management and Intelligent Switching
This document explains the cloud AI account management and switching capabilities in Antigravity Manager. The feature allows users to manage multiple Google accounts, monitor API quotas, and seamlessly switch the active IDE account with one click. This document explains the cloud AI account management and switching capabilities in Gemini Nexus. The feature allows users to manage multiple Google accounts, monitor API quotas, and seamlessly switch the active IDE account with one click.
## 1. Core Features ## 1. Core Features
+7 -7
View File
@@ -1,9 +1,9 @@
# Proxyman Debugging Guide for Antigravity and Antigravity Manager # Proxyman Debugging Guide for Antigravity and Gemini Nexus
This guide explains how to use Proxyman for two debugging targets: This guide explains how to use Proxyman for two debugging targets:
1. The installed official `Antigravity` desktop client 1. The installed official `Antigravity` desktop client
2. The `Antigravity Manager` development build from this repository 2. The `Gemini Nexus` development build from this repository
Before you start, complete [Proxyman Installation and Basic Setup on Windows](./proxyman-install.md). Before you start, complete [Proxyman Installation and Basic Setup on Windows](./proxyman-install.md).
@@ -12,7 +12,7 @@ Before you start, complete [Proxyman Installation and Basic Setup on Windows](./
Use this guide when you want to: Use this guide when you want to:
- inspect login, quota, project context, or model-list requests from `Antigravity` - inspect login, quota, project context, or model-list requests from `Antigravity`
- inspect OAuth, quota refresh, or proxy traffic from `Antigravity Manager` - inspect OAuth, quota refresh, or proxy traffic from `Gemini Nexus`
- compare requests from the official client with requests produced by this project - compare requests from the official client with requests produced by this project
## Understand the Two Traffic Paths ## Understand the Two Traffic Paths
@@ -24,7 +24,7 @@ Use this guide when you want to:
- Chromium or renderer-side requests - Chromium or renderer-side requests
- Electron or Node-side requests - Electron or Node-side requests
### `Antigravity Manager` in This Repository ### `Gemini Nexus` in This Repository
This project is also an Electron app, but it additionally includes Node, Undici, and internal proxy flows. You may need to inspect: This project is also an Electron app, but it additionally includes Node, Undici, and internal proxy flows. You may need to inspect:
@@ -68,7 +68,7 @@ powershell -ExecutionPolicy Bypass -File .\scripts\start-antigravity-with-proxym
Notes: Notes:
- This script targets the installed official `Antigravity` client. - This script targets the installed official `Antigravity` client.
- It does not launch this repository's `Antigravity Manager` development build. - It does not launch this repository's `Gemini Nexus` development build.
- Override `-AppPath`, `-CaPath`, `-ProxyHost`, or `-NoProxy` if your local environment differs. - Override `-AppPath`, `-CaPath`, `-ProxyHost`, or `-NoProxy` if your local environment differs.
### Suggested Flow ### Suggested Flow
@@ -111,7 +111,7 @@ If system proxy behavior is unreliable, you can launch the installed client with
Use this as a fallback, not the default path. Use this as a fallback, not the default path.
## Debug Antigravity Manager From This Repository ## Debug Gemini Nexus From This Repository
This project has more layers than the official client. The script above is not the general launcher for this repository's development app. This project has more layers than the official client. The script above is not the general launcher for this repository's development app.
@@ -227,7 +227,7 @@ powershell -ExecutionPolicy Bypass -File .\scripts\start-antigravity-with-proxym
4. Trigger login, quota, or model-list traffic. 4. Trigger login, quota, or model-list traffic.
### Antigravity Manager in This Repository ### Gemini Nexus in This Repository
1. Complete [Proxyman Installation and Basic Setup on Windows](./proxyman-install.md). 1. Complete [Proxyman Installation and Basic Setup on Windows](./proxyman-install.md).
2. Open PowerShell. 2. Open PowerShell.
+1 -1
View File
@@ -31,7 +31,7 @@ export default defineConfig([
'unused-imports': unusedImports, 'unused-imports': unusedImports,
}, },
rules: { rules: {
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-empty-object-type': 'off', '@typescript-eslint/no-empty-object-type': 'off',
'@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/ban-ts-comment': 'off',
+44
View File
@@ -0,0 +1,44 @@
/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require('fs');
const path = require('path');
const projectRoot = process.cwd();
// Extensões permitidas
const allowedExtensions = /\.(ts|tsx)$/;
function walkAndFix(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
if (['node_modules', '.git', 'dist', 'out'].includes(file)) continue;
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
walkAndFix(fullPath);
} else if (allowedExtensions.test(file)) {
let content = fs.readFileSync(fullPath, 'utf-8');
const original = content;
// Fix specific known broken identifiers
content = content.replace(/closeGemini Nexus/g, 'closeGeminiNexus');
content = content.replace(/startGemini Nexus/g, 'startGeminiNexus');
content = content.replace(/Gemini NexusVersion/g, 'GeminiNexusVersion');
content = content.replace(/Gemini NexusDb/g, 'GeminiNexusDb');
content = content.replace(/Gemini NexusStorage/g, 'GeminiNexusStorage');
content = content.replace(/Gemini NexusExecutable/g, 'GeminiNexusExecutable');
content = content.replace(/Gemini NexusCoreFeatures/g, 'GeminiNexusCoreFeatures');
content = content.replace(/getGemini Nexus/g, 'getGeminiNexus');
if (content !== original) {
fs.writeFileSync(fullPath, content, 'utf-8');
console.log(`Fixed TS errors in: ${fullPath}`);
}
}
}
}
walkAndFix(projectRoot);
console.log('Fix complete.');
+20 -27
View File
@@ -1,3 +1,4 @@
import { execSync } from 'child_process';
import crypto from 'crypto'; import crypto from 'crypto';
import { FuseV1Options, FuseVersion } from '@electron/fuses'; import { FuseV1Options, FuseVersion } from '@electron/fuses';
import type { import type {
@@ -17,15 +18,25 @@ import { FusesPlugin } from '@electron-forge/plugin-fuses';
import { VitePlugin } from '@electron-forge/plugin-vite'; import { VitePlugin } from '@electron-forge/plugin-vite';
import type { ForgeConfig } from '@electron-forge/shared-types'; import type { ForgeConfig } from '@electron-forge/shared-types';
import MakerAppImage from '@pengx17/electron-forge-maker-appimage'; import MakerAppImage from '@pengx17/electron-forge-maker-appimage';
// @ts-ignore
import setLanguages from 'electron-packager-languages'; import setLanguages from 'electron-packager-languages';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import { stringify as yamlStringify } from 'yaml'; import { stringify as yamlStringify } from 'yaml';
const nativeModules = ['better-sqlite3', 'keytar', 'bindings', 'file-uri-to-path']; const nativeModules = ['better-sqlite3', 'keytar', 'bindings', 'file-uri-to-path'];
const ResolvedMakerAppImage = MakerAppImage; const ResolvedMakerAppImage: any = (MakerAppImage as any).default || MakerAppImage;
const keepLanguages = new Set(['en', 'en-US', 'zh-CN', 'ru']); const keepLanguages = new Set(['en', 'en-US', 'zh-CN', 'ru']);
const windowsExecutableName = 'antigravity-manager'; const windowsExecutableName = 'gemini-nexus';
function isWixAvailable(): boolean {
try {
execSync('candle -?', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
const isStartCommand = process.argv.some((arg) => arg.includes('start')); const isStartCommand = process.argv.some((arg) => arg.includes('start'));
@@ -176,25 +187,8 @@ function getChecksumArchLabel(platform: string, arch: string) {
} }
const appImageMaker = new ResolvedMakerAppImage({ const appImageMaker = new ResolvedMakerAppImage({
config: { options: {
icons: [ icon: 'images/128x128.png',
{
file: 'images/32x32.png',
size: 32,
},
{
file: 'images/64x64.png',
size: 64,
},
{
file: 'images/128x128.png',
size: 128,
},
{
file: 'images/[email protected]',
size: 256,
},
],
}, },
}); });
appImageMaker.name = '@pengx17/electron-forge-maker-appimage'; appImageMaker.name = '@pengx17/electron-forge-maker-appimage';
@@ -204,7 +198,7 @@ const config: ForgeConfig = {
asar: { asar: {
unpack: '**/{better-sqlite3,keytar}/**/*', unpack: '**/{better-sqlite3,keytar}/**/*',
}, },
name: 'Antigravity Manager', name: 'Gemini Nexus',
executableName: windowsExecutableName, executableName: windowsExecutableName,
icon: 'images/icon', // Electron Forge automatically adds .icns/.ico icon: 'images/icon', // Electron Forge automatically adds .icns/.ico
extraResource: ['src/assets'], // Copy assets folder to resources/assets extraResource: ['src/assets'], // Copy assets folder to resources/assets
@@ -449,10 +443,9 @@ const config: ForgeConfig = {
makers: [ makers: [
new MakerSquirrel({ new MakerSquirrel({
setupIcon: 'images/icon.ico', setupIcon: 'images/icon.ico',
iconUrl: iconUrl: 'https://raw.githubusercontent.com/evandrodevbr/GeminiNexus/main/images/icon.ico',
'https://raw.githubusercontent.com/Draculabo/AntigravityManager/main/images/icon.ico',
}), }),
...(process.platform === 'win32' && process.arch === 'x64' ...(process.platform === 'win32' && process.arch === 'x64' && isWixAvailable()
? [ ? [
new MakerWix({ new MakerWix({
language: 1033, language: 1033,
@@ -484,8 +477,8 @@ const config: ForgeConfig = {
name: '@electron-forge/publisher-github', name: '@electron-forge/publisher-github',
config: { config: {
repository: { repository: {
owner: 'Draculabo', owner: 'evandrodevbr',
name: 'AntigravityManager', name: 'GeminiNexus',
}, },
draft: true, draft: true,
prerelease: false, prerelease: false,
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 353 KiB

After

Width:  |  Height:  |  Size: 353 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 864 B

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 390 KiB

+2 -1
View File
@@ -2,7 +2,8 @@
<html> <html>
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Antigravity Manager</title> <title>Gemini Nexus</title>
<link rel="icon" type="image/png" href="/src/assets/icon.png" />
<meta http-equiv="Content-Security-Policy" content="script-src 'self';" /> <meta http-equiv="Content-Security-Policy" content="script-src 'self';" />
<link rel="stylesheet" href="/src/styles/global.css" /> <link rel="stylesheet" href="/src/styles/global.css" />
</head> </head>
@@ -20,7 +20,7 @@
- Affected code: - Affected code:
- `src/ipc/database/cloudHandler.ts` - `src/ipc/database/cloudHandler.ts`
- `src/ipc/database/handler.ts` - `src/ipc/database/handler.ts`
- `src/utils/antigravityVersion.ts` - `src/utils/geminiNexusVersion.ts`
- `src/utils/paths.ts` (this stage covers default runtime configuration path only) - `src/utils/paths.ts` (this stage covers default runtime configuration path only)
- `src/types/db.ts` - `src/types/db.ts`
@@ -38,5 +38,5 @@ The system SHALL use a strategy pattern to split new/legacy/dual-write injection
The system SHALL prefer new-format injection when new-format keys are detected. The system SHALL prefer new-format injection when new-format keys are detected.
#### Scenario: New-format key exists #### Scenario: New-format key exists
- **WHEN** `antigravityUnifiedStateSync.oauthToken` exists - **WHEN** `geminiNexusUnifiedStateSync.oauthToken` exists
- **THEN** injection uses new format with higher priority - **THEN** injection uses new format with higher priority
@@ -4,7 +4,7 @@
## Summary ## Summary
Add multilingual support to Antigravity Manager and automatically set the default UI language based on the user's OS language. If the OS language is unsupported, fall back to English. This includes updating i18n configuration, adding Chinese translation resources, and integrating a language detection plugin. Add multilingual support to Gemini Nexus and automatically set the default UI language based on the user's OS language. If the OS language is unsupported, fall back to English. This includes updating i18n configuration, adding Chinese translation resources, and integrating a language detection plugin.
## Motivation ## Motivation
@@ -2,32 +2,32 @@
## Summary ## Summary
Enable Antigravity Manager running in WSL (Windows Subsystem for Linux) to manage the Antigravity application installed on the Windows host. Enable Gemini Nexus running in WSL (Windows Subsystem for Linux) to manage the Gemini Nexus application installed on the Windows host.
## Motivation ## Motivation
Users running the manager in a WSL development environment need to interact with the actual Antigravity instance running on Windows, as Antigravity is a Windows application. Users running the manager in a WSL development environment need to interact with the actual Gemini Nexus instance running on Windows, as Gemini Nexus is a Windows application.
## Proposed Changes ## Proposed Changes
### 1. Path Resolution (`src/utils/paths.ts`) ### 1. Path Resolution (`src/utils/paths.ts`)
* Implement `isWsl()` utility function. * Implement `isWsl()` utility function.
* In `getAppDataDir()`: If WSL, return the Windows AppData path (e.g., `/mnt/c/Users/<User>/AppData/Roaming/Antigravity`). * In `getAppDataDir()`: If WSL, return the Windows AppData path (e.g., `/mnt/c/Users/<User>/AppData/Roaming/GeminiNexus`).
* In `getAntigravityExecutablePath()`: If WSL, return the Windows executable path (e.g., `/mnt/c/Users/<User>/AppData/Local/Programs/Antigravity/Antigravity.exe`). * In `getGeminiNexusExecutablePath()`: If WSL, return the Windows executable path (e.g., `/mnt/c/Users/<User>/AppData/Local/Programs/GeminiNexus/GeminiNexus.exe`).
* **Challenge:** Determining the correct Windows username. * **Challenge:** Determining the correct Windows username.
* **Strategy:** Assume Windows username matches WSL username, or scan `/mnt/c/Users` for a likely candidate (excluding Public, Default, etc.). * **Strategy:** Assume Windows username matches WSL username, or scan `/mnt/c/Users` for a likely candidate (excluding Public, Default, etc.).
### 2. Process Management (`src/ipc/process/handler.ts`) ### 2. Process Management (`src/ipc/process/handler.ts`)
* In `isProcessRunning()`: If WSL, execute `tasklist.exe` (via `/mnt/c/Windows/System32/tasklist.exe`) to check for `Antigravity.exe`. * In `isProcessRunning()`: If WSL, execute `tasklist.exe` (via `/mnt/c/Windows/System32/tasklist.exe`) to check for `GeminiNexus.exe`.
* In `startAntigravity()`: If WSL, execute the Windows executable directly. * In `startGeminiNexus()`: If WSL, execute the Windows executable directly.
* In `closeAntigravity()`: If WSL, use `taskkill.exe` (via `/mnt/c/Windows/System32/taskkill.exe`). * In `closeGeminiNexus()`: If WSL, use `taskkill.exe` (via `/mnt/c/Windows/System32/taskkill.exe`).
## Acceptance Criteria ## Acceptance Criteria
* \[ ] Application detects it is running in WSL. * \[ ] Application detects it is running in WSL.
* \[ ] Database file is correctly located on the Windows file system. * \[ ] Database file is correctly located on the Windows file system.
* \[ ] "Start" button successfully launches Antigravity on Windows. * \[ ] "Start" button successfully launches Gemini Nexus on Windows.
* \[ ] "Stop" button successfully terminates Antigravity on Windows. * \[ ] "Stop" button successfully terminates Gemini Nexus on Windows.
* \[ ] Process status (Running/Stopped) is correctly reflected in the UI. * \[ ] Process status (Running/Stopped) is correctly reflected in the UI.
@@ -1,6 +1,6 @@
## ADDED Requirements ## ADDED Requirements
### Requirement: New-Format Injection for 1.16.5+ ### Requirement: New-Format Injection for 1.16.5+
The system SHALL write only the new format `antigravityUnifiedStateSync.oauthToken` when IDE version is >= 1.16.5. The system SHALL write only the new format `geminiNexusUnifiedStateSync.oauthToken` when IDE version is >= 1.16.5.
#### Scenario: New-version injection #### Scenario: New-version injection
- **WHEN** IDE version is 1.16.5 or above - **WHEN** IDE version is 1.16.5 or above
+9 -9
View File
@@ -2,11 +2,11 @@
## Purpose ## Purpose
Antigravity Manager is a comprehensive enhancement tool for Antigravity, designed to remove AI development resource limits. It not only solves the lack of native multi-account switching in Antigravity IDE, but also introduces enterprise-grade AI account pool management. By taking control of app configuration state and cloud API resources, it allows users to switch seamlessly between unlimited local accounts and cloud AI services for an effectively "unlimited" AI usage experience. Gemini Nexus is a comprehensive enhancement tool for Gemini Nexus, designed to remove AI development resource limits. It not only solves the lack of native multi-account switching in Gemini Nexus IDE, but also introduces enterprise-grade AI account pool management. By taking control of app configuration state and cloud API resources, it allows users to switch seamlessly between unlimited local accounts and cloud AI services for an effectively "unlimited" AI usage experience.
**Core goals:** **Core goals:**
* **Local multi-account switching**: Seamlessly switch Antigravity IDE local user state while protecting data integrity (automatic backup). * **Local multi-account switching**: Seamlessly switch Gemini Nexus IDE local user state while protecting data integrity (automatic backup).
* **AI resource pool management (new)**: Centrally manage account pools for Google Gemini, Claude 3.5, and similar services. * **AI resource pool management (new)**: Centrally manage account pools for Google Gemini, Claude 3.5, and similar services.
* **Intelligent quota monitoring (new)**: Monitor API quota and health in real time with a visual dashboard. * **Intelligent quota monitoring (new)**: Monitor API quota and health in real time with a visual dashboard.
* **Automatic resource scheduling (new)**: Automatically switch to the best available account when the current one runs out of quota (token keepalive + polling). * **Automatic resource scheduling (new)**: Automatically switch to the best available account when the current one runs out of quota (token keepalive + polling).
@@ -88,17 +88,17 @@ src/
## Domain Context ## Domain Context
### 1. Antigravity IDE Data Structure (Local) ### 1. Gemini Nexus IDE Data Structure (Local)
**Database locations:** **Database locations:**
* macOS: `~/Library/Application Support/Antigravity/User/globalStorage/state.vscdb` * macOS: `~/Library/Application Support/GeminiNexus/User/globalStorage/state.vscdb`
* Windows: `%APPDATA%/Antigravity/User/globalStorage/state.vscdb` * Windows: `%APPDATA%/GeminiNexus/User/globalStorage/state.vscdb`
* Linux: `~/.config/Antigravity/User/globalStorage/state.vscdb` * Linux: `~/.config/GeminiNexus/User/globalStorage/state.vscdb`
**Key database fields:** **Key database fields:**
* `antigravityAuthStatus`: Authentication status and user information. * `geminiNexusAuthStatus`: Authentication status and user information.
### 2. AI Service Resource Structure (Cloud / New) ### 2. AI Service Resource Structure (Cloud / New)
@@ -141,7 +141,7 @@ src/
### System Dependencies ### System Dependencies
* **Antigravity IDE**: Local target to manage. * **Gemini Nexus IDE**: Local target to manage.
* **SQLite**: Local data reads. * **SQLite**: Local data reads.
### Node.js Dependencies (Key) ### Node.js Dependencies (Key)
@@ -159,7 +159,7 @@ src/
### Filesystem Dependencies ### Filesystem Dependencies
* `~/.antigravity-agent/` * `~/.geminiNexus-agent/`
* `accounts.json`: Local IDE account index. * `accounts.json`: Local IDE account index.
* `cloud_accounts.db`: (new) Cloud account pool database (SQLite). * `cloud_accounts.db`: (new) Cloud account pool database (SQLite).
* `backups/`: Backup files. * `backups/`: Backup files.
+5669 -11190
View File
File diff suppressed because it is too large. Load diff
+42 -19
View File
@@ -1,15 +1,19 @@
{ {
"name": "antigravity-manager", "name": "gemini-nexus",
"productName": "Antigravity Manager", "productName": "Gemini Nexus",
"version": "0.11.1", "version": "0.13.0",
"description": "Antigravity Manager - Electron App", "description": "Gemini Nexus - Electron App",
"main": ".vite/build/main.js", "main": ".vite/build/main.js",
"private": true, "private": true,
"scripts": { "scripts": {
"start": "electron-forge start", "start": "cross-env DEBUG=electron-forge:* electron-forge start",
"dev": "cross-env DEBUG=electron-forge:* electron-forge start",
"package": "electron-forge package", "package": "electron-forge package",
"make": "electron-forge make", "make": "electron-forge make",
"make:win": "node scripts/build-windows.js",
"publish": "electron-forge publish", "publish": "electron-forge publish",
"setup": "node scripts/setup-dev.js",
"postinstall": "node scripts/setup-dev.js --check-only",
"lint": "eslint .", "lint": "eslint .",
"format": "prettier --check .", "format": "prettier --check .",
"format:write": "prettier --write .", "format:write": "prettier --write .",
@@ -20,15 +24,15 @@
"test:all": "vitest run && playwright test", "test:all": "vitest run && playwright test",
"type-check": "tsc --noEmit" "type-check": "tsc --noEmit"
}, },
"author": "Draculabo", "author": "evandrodevbr",
"license": "CC-BY-NC-SA-4.0", "license": "CC-BY-NC-SA-4.0",
"devDependencies": { "devDependencies": {
"@electron-forge/cli": "^7.11.1", "@electron-forge/cli": "^7.6.1",
"@electron-forge/maker-deb": "^7.11.1", "@electron-forge/maker-deb": "^7.11.1",
"@electron-forge/maker-dmg": "^7.11.1", "@electron-forge/maker-dmg": "^7.11.1",
"@electron-forge/maker-rpm": "^7.11.1", "@electron-forge/maker-rpm": "^7.11.1",
"@electron-forge/maker-squirrel": "^7.11.1", "@electron-forge/maker-squirrel": "^7.11.1",
"@electron-forge/maker-wix": "^7.11.1", "@electron-forge/maker-wix": "^7.9.0",
"@electron-forge/maker-zip": "^7.11.1", "@electron-forge/maker-zip": "^7.11.1",
"@electron-forge/plugin-auto-unpack-natives": "^7.11.1", "@electron-forge/plugin-auto-unpack-natives": "^7.11.1",
"@electron-forge/plugin-fuses": "^7.11.1", "@electron-forge/plugin-fuses": "^7.11.1",
@@ -39,14 +43,14 @@
"@electron/rebuild": "^3.7.1", "@electron/rebuild": "^3.7.1",
"@eslint/compat": "^1.4.1", "@eslint/compat": "^1.4.1",
"@eslint/js": "^9.39.0", "@eslint/js": "^9.39.0",
"@pengx17/electron-forge-maker-appimage": "^1.2.1", "@pengx17/electron-forge-maker-appimage": "^1.0.2",
"@playwright/test": "^1.56.1", "@playwright/test": "^1.56.1",
"@semantic-release/changelog": "^6.0.3", "@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1", "@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^12.0.6", "@semantic-release/github": "^12.0.6",
"@sentry/vite-plugin": "^4.8.0", "@sentry/vite-plugin": "^4.8.0",
"@swc/core": "^1.15.8", "@swc/core": "^1.15.8",
"@tailwindcss/vite": "^4.1.17", "@tailwindcss/vite": "^4.2.4",
"@tanstack/router-plugin": "^1.135.0", "@tanstack/router-plugin": "^1.135.0",
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.0", "@testing-library/react": "^16.3.0",
@@ -62,7 +66,8 @@
"babel-plugin-react-compiler": "1.0.0", "babel-plugin-react-compiler": "1.0.0",
"code-inspector-plugin": "^1.3.3", "code-inspector-plugin": "^1.3.3",
"conventional-changelog-conventionalcommits": "^9.1.0", "conventional-changelog-conventionalcommits": "^9.1.0",
"electron": "^37.3.1", "cross-env": "^10.1.0",
"electron": "^41.3.0",
"electron-devtools-installer": "^4.0.0", "electron-devtools-installer": "^4.0.0",
"electron-packager-languages": "^0.6.0", "electron-packager-languages": "^0.6.0",
"electron-playwright-helpers": "^1.8.2", "electron-playwright-helpers": "^1.8.2",
@@ -76,6 +81,7 @@
"happy-dom": "^20.8.9", "happy-dom": "^20.8.9",
"icon-gen": "^5.0.0", "icon-gen": "^5.0.0",
"jsdom": "^27.1.0", "jsdom": "^27.1.0",
"node-abi": "^4.28.0",
"node-addon-api": "^8.3.1", "node-addon-api": "^8.3.1",
"prettier": "^3.6.2", "prettier": "^3.6.2",
"prettier-plugin-tailwindcss": "^0.7.1", "prettier-plugin-tailwindcss": "^0.7.1",
@@ -87,18 +93,22 @@
"typescript": "^5.9.3", "typescript": "^5.9.3",
"typescript-eslint": "^8.46.3", "typescript-eslint": "^8.46.3",
"unplugin-swc": "^1.5.9", "unplugin-swc": "^1.5.9",
"vite": "^5.4.21", "vite": "^8.0.10",
"vite-tsconfig-paths": "^6.1.1",
"vitest": "^4.0.8" "vitest": "^4.0.8"
}, },
"dependencies": { "dependencies": {
"@grpc/grpc-js": "^1.14.3",
"@grpc/proto-loader": "^0.8.0",
"@icons-pack/react-simple-icons": "^13.8.0", "@icons-pack/react-simple-icons": "^13.8.0",
"@nestjs/common": "^11.1.18", "@nestjs/common": "^11.1.18",
"@nestjs/core": "^11.1.18", "@nestjs/core": "^11.1.18",
"@nestjs/microservices": "^11.1.18", "@nestjs/microservices": "^11.1.18",
"@nestjs/platform-express": "^11.1.18", "@nestjs/platform-express": "^11.1.18",
"@nestjs/platform-fastify": "^11.1.18", "@nestjs/platform-fastify": "^11.0.20",
"@nestjs/websockets": "^11.1.19",
"@nivo/bar": "^0.99.0",
"@nivo/core": "^0.99.0",
"@nivo/line": "^0.99.0",
"@nivo/pie": "^0.99.0",
"@orpc/client": "^1.13.14", "@orpc/client": "^1.13.14",
"@orpc/server": "^1.13.14", "@orpc/server": "^1.13.14",
"@radix-ui/react-avatar": "^1.1.11", "@radix-ui/react-avatar": "^1.1.11",
@@ -121,7 +131,6 @@
"@tanstack/react-query": "^5.90.7", "@tanstack/react-query": "^5.90.7",
"@tanstack/react-router": "^1.139.3", "@tanstack/react-router": "^1.139.3",
"@tanstack/react-router-devtools": "^1.135.0", "@tanstack/react-router-devtools": "^1.135.0",
"@types/uuid": "^11.0.0",
"axios": "^1.15.0", "axios": "^1.15.0",
"better-sqlite3": "^12.4.6", "better-sqlite3": "^12.4.6",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
@@ -131,8 +140,9 @@
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"electron-squirrel-startup": "^1.0.1", "electron-squirrel-startup": "^1.0.1",
"fastify": "^5.8.4", "fastify": "^5.8.5",
"find-process": "^2.0.0", "find-process": "^2.0.0",
"gpt-tokenizer": "^3.4.0",
"i18next": "^25.6.3", "i18next": "^25.6.3",
"i18next-browser-languagedetector": "^8.2.0", "i18next-browser-languagedetector": "^8.2.0",
"keytar": "^7.9.0", "keytar": "^7.9.0",
@@ -148,7 +158,7 @@
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"undici": "^7.16.0", "undici": "^7.16.0",
"update-electron-app": "^3.1.1", "update-electron-app": "^3.1.1",
"uuid": "^13.0.0", "uuid": "^14.0.0",
"winston": "^3.19.0", "winston": "^3.19.0",
"winston-daily-rotate-file": "^5.0.0", "winston-daily-rotate-file": "^5.0.0",
"yaml": "^2.8.2", "yaml": "^2.8.2",
@@ -160,5 +170,18 @@
"@sentry/cli", "@sentry/cli",
"@swc/core", "@swc/core",
"protobufjs" "protobufjs"
] ],
"pnpm": {
"overrides": {
"node-abi": "^4.28.0",
"fastify": "^5.8.5",
"tar": "^7.5.13",
"@octokit/request-error": "^5.1.1",
"@octokit/plugin-paginate-rest": "^9.2.2",
"@octokit/request": "^8.4.1",
"tmp": "^0.2.4",
"@tootallnate/once": "^3.0.1",
"esbuild": "^0.25.0"
}
}
} }
+8
View File
@@ -0,0 +1,8 @@
const fs = require('fs');
let file = fs.readFileSync('src/routes/proxy.tsx', 'utf8');
// The Proxy layout also uses heavy cards
file = file.replace(/<Card>/g, '<Card className="bg-background border border-white/5 shadow-none">');
fs.writeFileSync('src/routes/proxy.tsx', file);
+11
View File
@@ -0,0 +1,11 @@
const fs = require('fs');
let file = fs.readFileSync('src/routes/settings.tsx', 'utf8');
// The settings page uses standard cards that look bulky in minimal dark mode
file = file.replace(/<div className="flex flex-col gap-6">/g, '<div className="flex flex-col gap-2">');
file = file.replace(/<Card>/g, '<Card className="bg-transparent border-0 shadow-none rounded-none border-b border-white/5 last:border-0 pb-6">');
file = file.replace(/<CardHeader>/g, '<CardHeader className="px-0 pt-4">');
file = file.replace(/<CardContent>/g, '<CardContent className="px-0">');
fs.writeFileSync('src/routes/settings.tsx', file);
+18234
View File
File diff suppressed because it is too large. Load diff
+12
View File
@@ -0,0 +1,12 @@
allowBuilds:
'@bitdisaster/exe-icon-extractor': true
'@nestjs/core': true
'@sentry/cli': true
'@swc/core': true
better-sqlite3: true
electron: true
electron-winstaller: true
esbuild: true
keytar: true
protobufjs: true
sharp: true
+118
View File
@@ -0,0 +1,118 @@
/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require('fs');
const path = require('path');
const projectRoot = process.cwd();
// Extensões permitidas
const allowedExtensions = /\.(ts|tsx|js|jsx|json|md|html|jsonc|yml|yaml|css)$/;
// Arquivos/Pastas a ignorar (já curados ou irrelevantes)
const ignoreDirs = [
'node_modules',
'.git',
'.gemini',
'dist',
'out',
'build',
'images',
'docs',
'.planning',
];
const ignoreFiles = [
'README.md',
'README.pt-BR.md',
'CHANGELOG.md',
'forge.config.ts',
'package.json',
'rename.js',
'rename-deep.js',
'task.md',
'walkthrough.md',
];
function walkAndReplace(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
if (ignoreDirs.includes(file)) continue;
const fullPath = path.join(dir, file);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
walkAndReplace(fullPath);
// Rename directory if it contains 'antigravity'
if (file.toLowerCase().includes('antigravity')) {
const newName = file.replace(/antigravity/gi, (match) => {
if (match === 'antigravity') return 'geminiNexus';
if (match === 'Antigravity') return 'GeminiNexus';
return 'geminiNexus';
});
const newPath = path.join(dir, newName);
fs.renameSync(fullPath, newPath);
console.log(`Renamed directory: ${fullPath} -> ${newPath}`);
}
} else {
if (ignoreFiles.includes(file)) continue;
if (allowedExtensions.test(file)) {
let content = fs.readFileSync(fullPath, 'utf-8');
const originalContent = content;
// Save original GitHub links
const repoUrlRegex = /github\.com\/Draculabo\/AntigravityManager/gi;
const tempUrlMarker = '___TEMP_GITHUB_URL___';
content = content.replace(repoUrlRegex, tempUrlMarker);
// 1. Strings exact match "Antigravity" -> "Gemini Nexus"
content = content.replace(/['"]Antigravity['"]/g, (match) => {
return match[0] + 'Gemini Nexus' + match[0];
});
// 2. String "Antigravity " -> "Gemini Nexus "
content = content.replace(/Antigravity /g, 'Gemini Nexus ');
// 3. String " Antigravity" -> " Gemini Nexus"
content = content.replace(/ Antigravity/g, ' Gemini Nexus');
// 4. Identifiers Antigravity -> GeminiNexus
content = content.replace(/Antigravity/g, 'GeminiNexus');
// 5. Identifiers antigravity -> geminiNexus
content = content.replace(/antigravity/g, 'geminiNexus');
// Restore GitHub links
content = content.replace(
new RegExp(tempUrlMarker, 'g'),
'github.com/Draculabo/AntigravityManager',
);
// Cleanup any double replacements
content = content.replace(/GeminiNexus Nexus/g, 'Gemini Nexus');
if (content !== originalContent) {
fs.writeFileSync(fullPath, content, 'utf-8');
console.log(`Updated file content: ${fullPath}`);
}
// Rename file if it contains 'antigravity'
if (file.toLowerCase().includes('antigravity')) {
const newName = file.replace(/antigravity/gi, (match) => {
if (match === 'antigravity') return 'geminiNexus'; // For files like antigravityVersion.ts -> geminiNexusVersion.ts
if (match === 'Antigravity') return 'GeminiNexus';
return 'geminiNexus';
});
const newPath = path.join(dir, newName);
fs.renameSync(fullPath, newPath);
console.log(`Renamed file: ${fullPath} -> ${newPath}`);
}
}
}
}
}
console.log('Starting global deep rename of Antigravity to GeminiNexus...');
walkAndReplace(projectRoot);
console.log('Rename complete.');
+51
View File
@@ -0,0 +1,51 @@
/* eslint-disable @typescript-eslint/no-require-imports */
const { execSync, spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const WIX_ZIP = path.join(process.cwd(), 'wix314-binaries.zip');
const WIX_DIR = path.join(process.cwd(), 'tools', 'wix314');
function extractWix() {
if (!fs.existsSync(WIX_ZIP)) {
console.error(`WiX zip not found: ${WIX_ZIP}`);
process.exit(1);
}
if (fs.existsSync(WIX_DIR)) {
console.log(`WiX already extracted at ${WIX_DIR}`);
return;
}
console.log(`Extracting WiX binaries to ${WIX_DIR}...`);
fs.mkdirSync(WIX_DIR, { recursive: true });
// Use PowerShell Expand-Archive (built into Windows)
const psCommand = `Expand-Archive -Path "${WIX_ZIP}" -DestinationPath "${WIX_DIR}" -Force`;
execSync(psCommand, { shell: 'powershell.exe', stdio: 'inherit' });
console.log('WiX extraction complete.');
}
function setupWixPath() {
// electron-wix-msi's detect-wix.js runs execSync('candle -?') which relies on PATH
process.env.PATH = `${WIX_DIR};${process.env.PATH}`;
console.log(`Added ${WIX_DIR} to PATH`);
}
function runMake() {
console.log('Running electron-forge make...');
const make = spawn('npx', ['electron-forge', 'make'], {
stdio: 'inherit',
shell: true,
env: process.env,
});
make.on('exit', (code) => {
process.exit(code ?? 0);
});
}
extractWix();
setupWixPath();
runMake();
+619
View File
@@ -0,0 +1,619 @@
/**
* Cross-platform development environment setup for Gemini Nexus.
*
* Detects and installs native build toolchains required by better-sqlite3,
* keytar, and other native Node.js modules used in this Electron project.
*
* Platforms:
* - Windows → Visual Studio 2022 Build Tools (C++ workload)
* - macOS → Xcode Command Line Tools
* - Ubuntu → build-essential, python3, libsecret-1-dev
* - Manjaro/Arch → base-devel, python, libsecret
*
* Usage:
* node scripts/setup-dev.js # auto-detect and install/guide
* node scripts/setup-dev.js --check-only # only verify, don't install
*/
'use strict';
const { execSync, spawnSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
// ─── Terminal Color Helpers ─────────────────────────────────────────────────
const RESET = '\x1b[0m';
const BOLD = '\x1b[1m';
const DIM = '\x1b[2m';
const RED = '\x1b[31m';
const GREEN = '\x1b[32m';
const YELLOW = '\x1b[33m';
const CYAN = '\x1b[36m';
const MAGENTA = '\x1b[35m';
// Disable colors if NO_COLOR is set or output is piped
const useColor = process.env.NO_COLOR === undefined && process.stdout.isTTY;
function color(code, text) {
return useColor ? `${code}${text}${RESET}` : text;
}
function header(text) {
console.log(`\n${color(BOLD + MAGENTA, '══')} ${color(BOLD, text)} ${color(BOLD + MAGENTA, '══')}`);
}
function success(text) {
console.log(` ${color(GREEN, '✓')} ${text}`);
}
function warn(text) {
console.log(` ${color(YELLOW, '⚠')} ${text}`);
}
function error(text) {
console.log(` ${color(RED, '✗')} ${text}`);
}
function info(text) {
console.log(` ${color(CYAN, '→')} ${text}`);
}
function dim(text) {
console.log(` ${color(DIM, text)}`);
}
function section(title) {
console.log(`\n ${color(BOLD, title)}:`);
}
// ─── Platform Detection ─────────────────────────────────────────────────────
const platform = os.platform(); // 'win32' | 'darwin' | 'linux'
const arch = os.arch();
/** Detect Linux distribution from os-release */
function detectLinuxDistro() {
try {
const osRelease = fs.readFileSync('/etc/os-release', 'utf8');
const idMatch = osRelease.match(/^ID="?([^"\n]+)"?/m);
const idLikeMatch = osRelease.match(/^ID_LIKE="?([^"\n]+)"?/m);
const id = idMatch ? idMatch[1].toLowerCase() : '';
const idLike = idLikeMatch ? idLikeMatch[1].toLowerCase() : '';
if (id === 'ubuntu' || id === 'debian' || idLike.includes('debian')) {
return 'debian';
}
if (id === 'arch' || id === 'manjaro' || idLike.includes('arch')) {
return 'arch';
}
if (id === 'fedora' || idLike.includes('fedora') || idLike.includes('rhel')) {
return 'fedora';
}
return id || 'unknown';
} catch {
return 'unknown';
}
}
// ─── Tool Checkers ──────────────────────────────────────────────────────────
/** Check if a command exists on PATH */
function commandExists(cmd) {
try {
const whereCmd = platform === 'win32' ? 'where' : 'which';
execSync(`${whereCmd} "${cmd}"`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
/** Check if running with administrator/sudo privileges */
function hasAdminPrivileges() {
if (platform === 'win32') {
try {
// On Windows, check via net session (requires admin)
execSync('net session', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
// On Unix, check if UID is 0
return process.getuid ? process.getuid() === 0 : false;
}
/** Check Windows: Visual Studio Build Tools */
function checkWindows() {
const results = { ok: true, missing: [] };
// Check for cl.exe (C++ compiler from VS Build Tools)
if (commandExists('cl.exe')) {
success('MSVC Compiler (cl.exe) found');
} else {
// Try to find VS installation via vswhere or registry
let vsFound = false;
// vswhere.exe (shipped with VS 2017+)
const vswherePaths = [
'C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe',
'C:\\Program Files\\Microsoft Visual Studio\\Installer\\vswhere.exe',
];
for (const vswhere of vswherePaths) {
try {
const output = execSync(`"${vswhere}" -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`, {
stdio: ['ignore', 'pipe', 'ignore'],
encoding: 'utf8',
}).trim();
if (output) {
vsFound = true;
success(`Visual Studio found at: ${output}`);
break;
}
} catch {
// vswhere not found, continue
}
}
// Check registry fallback
if (!vsFound) {
try {
execSync(
'reg query "HKLM\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7" /v 17.0',
{ stdio: 'ignore' },
);
vsFound = true;
success('Visual Studio 2022 found (registry)');
} catch {
// Not found in registry either
}
}
if (!vsFound) {
error('MSVC Build Tools not found');
results.ok = false;
results.missing.push('msvc');
}
}
// Check Python (needed by node-gyp)
if (commandExists('python') || commandExists('python3')) {
success('Python found');
} else {
error('Python not found (required by node-gyp)');
results.ok = false;
results.missing.push('python');
}
return results;
}
/** Check macOS: Xcode Command Line Tools */
function checkMacOS() {
const results = { ok: true, missing: [] };
try {
const xcodePath = execSync('xcode-select -p', { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
if (xcodePath) {
success(`Xcode CLT found at: ${xcodePath}`);
}
} catch {
error('Xcode Command Line Tools not found');
results.ok = false;
results.missing.push('xcode-clt');
}
if (commandExists('make') || commandExists('gmake')) {
success('make found');
} else {
error('make not found');
results.ok = false;
results.missing.push('make');
}
return results;
}
/** Check Linux: build-essential, python3, libsecret */
function checkLinux() {
const results = { ok: true, missing: [] };
const distro = detectLinuxDistro();
section(`Linux Distribution Detected: ${distro || 'unknown'}`);
// gcc / g++
if (commandExists('gcc') || commandExists('cc')) {
success('C compiler found');
} else {
error('C compiler not found');
results.ok = false;
results.missing.push('compiler');
}
if (commandExists('g++') || commandExists('c++')) {
success('C++ compiler found');
} else {
error('C++ compiler not found');
results.ok = false;
results.missing.push('compiler');
}
// make
if (commandExists('make')) {
success('make found');
} else {
error('make not found');
results.ok = false;
results.missing.push('make');
}
// Python 3
if (commandExists('python3')) {
success('Python 3 found');
} else if (commandExists('python')) {
// Check if python is python3
try {
const ver = execSync('python --version', { encoding: 'utf8' });
if (ver.includes('3.')) {
success('Python 3 found (as python)');
} else {
error('Python 3 not found (python is v2)');
results.ok = false;
results.missing.push('python3');
}
} catch {
error('Python not found');
results.ok = false;
results.missing.push('python3');
}
} else {
error('Python 3 not found');
results.ok = false;
results.missing.push('python3');
}
// libsecret (needed by keytar)
try {
if (distro === 'debian') {
execSync('dpkg -s libsecret-1-dev', { stdio: 'ignore' });
success('libsecret-1-dev found');
} else if (distro === 'arch') {
execSync('pacman -Qi libsecret', { stdio: 'ignore' });
success('libsecret found');
} else {
// Check for pkg-config
try {
execSync('pkg-config --exists libsecret-1', { stdio: 'ignore' });
success('libsecret (pkg-config) found');
} catch {
warn('libsecret not detected (may not be needed if using prebuilt keytar)');
}
}
} catch {
warn('libsecret not detected (may not be needed if using prebuilt keytar)');
}
return results;
}
// ─── Installation Helpers ───────────────────────────────────────────────────
/** Run a command and stream output, return exit code */
function runCommand(cmd, args, opts = {}) {
return new Promise((resolve) => {
console.log(`\n ${color(CYAN, 'Running:')} ${color(DIM, `${cmd} ${args.join(' ')}`)}`);
const child = spawnSync(cmd, args, {
stdio: 'inherit',
shell: platform === 'win32',
...opts,
});
resolve(child.status);
});
}
/** Install Windows: Visual Studio 2022 Build Tools via winget */
async function installWindows() {
// Check if winget is available
if (!commandExists('winget')) {
console.log('');
console.log(color(RED, ' winget not found. Please install Visual Studio Build Tools manually:'));
console.log(color(CYAN, ' https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022'));
console.log('');
console.log(' During installation, select:');
console.log(color(BOLD, ' "Desktop development with C++" workload'));
console.log('');
console.log(' Or install via PowerShell (as Administrator):');
console.log(color(DIM, ' winget install Microsoft.VisualStudio.2022.BuildTools --override "--wait --quiet --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"'));
return false;
}
console.log('');
info('Attempting automatic installation of Visual Studio 2022 Build Tools...');
dim('This may take several minutes and requires administrator privileges.');
console.log('');
if (!hasAdminPrivileges()) {
warn('Not running as Administrator. winget may prompt for elevation.');
}
const status = await runCommand('winget', [
'install',
'Microsoft.VisualStudio.2022.BuildTools',
'--override',
'"--quiet --wait --norestart --add Microsoft.VisualStudio.Component.VC.Tools.x86.x64 --add Microsoft.VisualStudio.Component.Windows11SDK.22621 --includeRecommended"',
]);
if (status === 0) {
success('Visual Studio 2022 Build Tools installed successfully.');
console.log('');
warn('You may need to restart your terminal for PATH changes to take effect.');
return true;
}
error('Automatic installation failed. Please install manually.');
return false;
}
/** Install macOS: Xcode Command Line Tools */
async function installMacOS() {
console.log('');
info('Installing Xcode Command Line Tools...');
dim('A GUI dialog will appear. Click "Install" to proceed.');
const status = await runCommand('xcode-select', ['--install']);
// xcode-select --install returns 1 if already installed or cancelled
if (status === 0) {
success('Xcode Command Line Tools installation initiated.');
return true;
}
// Check if already installed (common false-negative)
try {
execSync('xcode-select -p', { stdio: 'ignore' });
success('Xcode Command Line Tools are already installed.');
return true;
} catch {
warn('Xcode CLT installation was cancelled or failed.');
warn('You can install manually via: xcode-select --install');
return false;
}
}
/** Install Linux: distribution-specific packages */
async function installLinux() {
const distro = detectLinuxDistro();
if (distro === 'debian') {
// Ubuntu / Debian
if (!hasAdminPrivileges()) {
warn('Root privileges required. You may be prompted for your password.');
}
const status = await runCommand('sudo', [
'apt-get', 'install', '-y',
'build-essential',
'python3',
'libsecret-1-dev',
'pkg-config',
]);
if (status === 0) {
success('Build dependencies installed successfully.');
return true;
}
error('Failed to install build dependencies.');
return false;
}
if (distro === 'arch') {
// Manjaro / Arch
if (!hasAdminPrivileges()) {
warn('Root privileges required. You may be prompted for your password.');
}
const status = await runCommand('sudo', [
'pacman', '-S', '--needed', '--noconfirm',
'base-devel',
'python',
'libsecret',
'pkg-config',
]);
if (status === 0) {
success('Build dependencies installed successfully.');
return true;
}
error('Failed to install build dependencies.');
return false;
}
if (distro === 'fedora') {
if (!hasAdminPrivileges()) {
warn('Root privileges required. You may be prompted for your password.');
}
const status = await runCommand('sudo', [
'dnf', 'install', '-y',
'gcc-c++',
'make',
'python3',
'libsecret-devel',
'pkg-config',
]);
if (status === 0) {
success('Build dependencies installed successfully.');
return true;
}
error('Failed to install build dependencies.');
return false;
}
// Unknown distro - provide generic instructions
console.log('');
warn(`Unknown Linux distribution: ${distro}`);
console.log('');
console.log(' You need the following packages to compile native Node.js modules:');
console.log(' - C/C++ compiler (gcc, g++)');
console.log(' - GNU Make');
console.log(' - Python 3');
console.log(' - libsecret development headers (for keytar)');
console.log(' - pkg-config');
console.log('');
console.log(' Install them using your distribution package manager, then run npm install again.');
return false;
}
// ─── Main ───────────────────────────────────────────────────────────────────
async function main() {
const args = process.argv.slice(2);
const checkOnly = args.includes('--check-only') || args.includes('--check');
console.log('');
console.log(color(BOLD + CYAN, '┌──────────────────────────────────────────┐'));
console.log(color(BOLD + CYAN, '│ Gemini Nexus - Dev Environment Setup │'));
console.log(color(BOLD + CYAN, '└──────────────────────────────────────────┘'));
console.log('');
dim(`Platform: ${platform} (${arch})`);
dim(`Node.js: ${process.version}`);
// Step 1: Check current state
header('Checking Build Toolchain');
let results;
switch (platform) {
case 'win32':
results = checkWindows();
break;
case 'darwin':
results = checkMacOS();
break;
case 'linux':
results = checkLinux();
break;
default:
console.log('');
error(`Unsupported platform: ${platform}`);
process.exit(1);
}
// Print summary
console.log('');
if (results.ok) {
success('All build tools are present and ready.');
console.log('');
dim('You can now run: npm install && npm start');
return;
}
// ── Missing tools ──
console.log('');
error('Some build tools are missing. Native modules like better-sqlite3 and keytar require compilation.');
if (checkOnly) {
console.log('');
warn('Build tools are missing. Native modules (better-sqlite3, keytar) require compilation.');
warn('Run "npm run setup" to install them automatically, or install manually:');
printManualInstructions(platform, results.missing);
console.log('');
dim('npm install succeeded, but npm start / electron-rebuild will fail until build tools are installed.');
// Don't exit with error - allow npm install to succeed (prebuilt binaries may work)
return;
}
// Step 2: Attempt installation
header('Installing Build Dependencies');
let installed = false;
switch (platform) {
case 'win32':
installed = await installWindows();
break;
case 'darwin':
installed = await installMacOS();
break;
case 'linux':
installed = await installLinux();
break;
}
// Step 3: Final status
console.log('');
if (installed) {
success('Setup complete. You can now run: npm install && npm start');
console.log('');
dim('If you encounter issues, restart your terminal and try again.');
} else {
console.log('');
warn('Automatic installation was not successful.');
warn('Please install the required tools manually, then run npm install again.');
printManualInstructions(platform, results.missing);
process.exit(1);
}
}
function printManualInstructions(platform, missing) {
console.log('');
console.log(color(BOLD, ' ── Manual Installation Instructions ──'));
console.log('');
switch (platform) {
case 'win32':
console.log(' 1. Download Visual Studio 2022 Build Tools:');
console.log(color(CYAN, ' https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022'));
console.log('');
console.log(' 2. Run the installer and select:');
console.log(color(BOLD, ' "Desktop development with C++"'));
console.log('');
console.log(' 3. Or install via PowerShell (as Administrator):');
console.log(color(DIM, ' winget install Microsoft.VisualStudio.2022.BuildTools --override "--quiet --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"'));
console.log('');
console.log(' 4. Restart your terminal after installation.');
break;
case 'darwin':
console.log(' Run this command in your terminal:');
console.log(color(DIM, ' xcode-select --install'));
console.log('');
console.log(' Then click "Install" in the dialog that appears.');
break;
case 'linux': {
const distro = detectLinuxDistro();
if (distro === 'debian') {
console.log(' Run:');
console.log(color(DIM, ' sudo apt-get install -y build-essential python3 libsecret-1-dev pkg-config'));
} else if (distro === 'arch') {
console.log(' Run:');
console.log(color(DIM, ' sudo pacman -S --needed base-devel python libsecret pkg-config'));
} else if (distro === 'fedora') {
console.log(' Run:');
console.log(color(DIM, ' sudo dnf install -y gcc-c++ make python3 libsecret-devel pkg-config'));
} else {
console.log(' Install: C/C++ compiler, make, python3, libsecret-dev, pkg-config');
}
break;
}
}
console.log('');
}
// ─── Run ────────────────────────────────────────────────────────────────────
main().catch((err) => {
console.error(color(RED, `\nUnexpected error: ${err.message}`));
process.exit(1);
});
+3 -5
View File
@@ -1,4 +1,4 @@
import React, { useEffect } from 'react'; import { useEffect } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { syncWithLocalTheme } from './actions/theme'; import { syncWithLocalTheme } from './actions/theme';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
@@ -29,12 +29,10 @@ const queryClient = new QueryClient();
const root = createRoot(document.getElementById('app')!); const root = createRoot(document.getElementById('app')!);
root.render( root.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<ThemeProvider storageKey={LOCAL_STORAGE_KEYS.THEME} defaultTheme="system"> <ThemeProvider storageKey={LOCAL_STORAGE_KEYS.THEME} defaultTheme="dark">
<App /> <App />
<Toaster /> <Toaster />
</ThemeProvider> </ThemeProvider>
</QueryClientProvider> </QueryClientProvider>,
</React.StrictMode>,
); );
+4 -4
View File
@@ -4,10 +4,10 @@ export function isProcessRunning() {
return ipc.client.proc.isProcessRunning(); return ipc.client.proc.isProcessRunning();
} }
export function closeAntigravity() { export function closeGeminiNexus() {
return ipc.client.proc.closeAntigravity(); return ipc.client.proc.closeGeminiNexus();
} }
export function startAntigravity() { export function startGeminiNexus() {
return ipc.client.proc.startAntigravity(); return ipc.client.proc.startGeminiNexus();
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 875 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 736 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 736 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 659 B

After

Width:  |  Height:  |  Size: 44 KiB

+2 -2
View File
@@ -114,8 +114,8 @@ export const AccountCard: React.FC<AccountCardProps> = ({
<Card <Card
className={cn( className={cn(
'relative overflow-hidden transition-all duration-200', 'relative overflow-hidden transition-all duration-200',
'hover:shadow-primary/10 hover:shadow-xl',
isCurrent ? 'border-primary/50 bg-primary/5' : 'hover:border-primary/20 cursor-pointer', isCurrent ? 'border-primary/50 bg-primary/10' : 'hover:bg-accent/10 cursor-pointer border-white/5',
(isSwitching || isDeleting) && 'pointer-events-none opacity-60', (isSwitching || isDeleting) && 'pointer-events-none opacity-60',
)} )}
onClick={() => !isCurrent && !isSwitching && !isDeleting && onSwitch(account.id)} onClick={() => !isCurrent && !isSwitching && !isDeleting && onSwitch(account.id)}
+115
View File
@@ -0,0 +1,115 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useCloudAccounts, useSetAccountProxy } from '@/hooks/useCloudAccounts';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { isValidProxyUrl } from '@/utils/url';
import { Loader2 } from 'lucide-react';
import { CloudAccount } from '@/types/cloudAccount';
function AccountProxyItem({ account }: { account: CloudAccount }) {
const { t } = useTranslation();
const setAccountProxy = useSetAccountProxy();
const [proxyUrl, setProxyUrl] = useState(account.proxy_url || '');
const [proxySaved, setProxySaved] = useState(false);
return (
<div className="flex items-center justify-between gap-4 border-b py-3 last:border-0">
<div className="flex items-center gap-3 overflow-hidden">
{account.avatar_url ? (
<img
src={account.avatar_url}
alt={account.name || ''}
className="bg-muted h-8 w-8 shrink-0 rounded-full border"
/>
) : (
<div className="bg-primary/10 text-primary flex h-8 w-8 shrink-0 items-center justify-center rounded-full border">
{account.name?.[0]?.toUpperCase() || 'A'}
</div>
)}
<div className="flex flex-col overflow-hidden">
<span className="truncate text-sm font-semibold">
{account.name || t('cloud.card.unknown')}
</span>
<span className="text-muted-foreground truncate text-xs">{account.email}</span>
</div>
</div>
<div className="flex items-center gap-2">
<Input
value={proxyUrl}
onChange={(e) => {
setProxyUrl(e.target.value);
setProxySaved(false);
}}
onBlur={() => {
const trimmed = proxyUrl.trim();
if (trimmed && !isValidProxyUrl(trimmed)) {
setProxyUrl(account.proxy_url || '');
return;
}
if (trimmed !== (account.proxy_url || '')) {
setAccountProxy.mutate({
accountId: account.id,
proxyUrl: trimmed || null,
});
setProxySaved(true);
setTimeout(() => setProxySaved(false), 2000);
}
}}
placeholder={t('cloud.card.proxyPlaceholder') || 'e.g. http://127.0.0.1:7890'}
className="h-8 w-48 text-sm"
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
}
}}
/>
<div className="w-16">
{proxySaved && (
<span className="text-[10px] whitespace-nowrap text-emerald-400">
{t('cloud.card.proxySaved')}
</span>
)}
</div>
</div>
</div>
);
}
export function AccountProxySettings() {
const { t } = useTranslation();
const { data: accounts, isLoading } = useCloudAccounts();
if (isLoading) {
return (
<Card>
<CardHeader>
<CardTitle>{t('settings.proxy.accountProxies.title')}</CardTitle>
<CardDescription>{t('settings.proxy.accountProxies.description')}</CardDescription>
</CardHeader>
<CardContent className="flex justify-center p-6">
<Loader2 className="text-muted-foreground animate-spin" />
</CardContent>
</Card>
);
}
if (!accounts || accounts.length === 0) {
return null;
}
return (
<Card>
<CardHeader>
<CardTitle>{t('settings.proxy.accountProxies.title')}</CardTitle>
<CardDescription>{t('settings.proxy.accountProxies.description')}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col">
{accounts.map((account) => (
<AccountProxyItem key={account.id} account={account} />
))}
</CardContent>
</Card>
);
}
+16 -57
View File
@@ -17,7 +17,6 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
import { Checkbox } from '@/components/ui/checkbox'; import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { MoreVertical, Trash, RefreshCw, Box, Power, Fingerprint, Eye, EyeOff } from 'lucide-react'; import { MoreVertical, Trash, RefreshCw, Box, Power, Fingerprint, Eye, EyeOff } from 'lucide-react';
@@ -35,9 +34,6 @@ import {
getQuotaStatus, getQuotaStatus,
type QuotaStatus, type QuotaStatus,
} from '@/utils/quota-display'; } from '@/utils/quota-display';
import { useState } from 'react';
import { useSetAccountProxy } from '@/hooks/useCloudAccounts';
import { isValidProxyUrl } from '@/utils/url';
import { getValidationBlockedStatusLabel } from '@/components/accountValidationStatus'; import { getValidationBlockedStatusLabel } from '@/components/accountValidationStatus';
type ModelQuotaEntry = [string, CloudQuotaModelInfo]; type ModelQuotaEntry = [string, CloudQuotaModelInfo];
@@ -62,9 +58,9 @@ const MODEL_DISPLAY_REPLACEMENTS: Array<[string, string]> = [
]; ];
const QUOTA_TEXT_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = { const QUOTA_TEXT_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = {
high: 'text-green-500', high: 'text-emerald-400',
medium: 'text-yellow-500', medium: 'text-amber-400',
low: 'text-red-500', low: 'text-rose-400',
}; };
const QUOTA_BAR_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = { const QUOTA_BAR_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = {
@@ -186,9 +182,6 @@ export function CloudAccountCard({
isProviderCollapsed, isProviderCollapsed,
toggleProviderCollapse, toggleProviderCollapse,
} = useProviderGrouping(); } = useProviderGrouping();
const setAccountProxy = useSetAccountProxy();
const [proxyUrl, setProxyUrl] = useState(account.proxy_url || '');
const [proxySaved, setProxySaved] = useState(false);
const getQuotaTextColorClass = (percentage: number) => { const getQuotaTextColorClass = (percentage: number) => {
const quotaStatus = getQuotaStatus(percentage); const quotaStatus = getQuotaStatus(percentage);
@@ -247,12 +240,12 @@ export function CloudAccountCard({
<span className="text-muted-foreground/70 text-[10px] font-bold tracking-wider uppercase"> <span className="text-muted-foreground/70 text-[10px] font-bold tracking-wider uppercase">
{title} {title}
</span> </span>
<div className="bg-border/50 h-[1px] flex-1" /> <div className="h-[1px] flex-1 bg-white/[0.04]" />
</div> </div>
{models.map(([modelName, info]) => ( {models.map(([modelName, info]) => (
<div <div
key={modelName} key={modelName}
className="group/item hover:bg-muted/60 hover:border-border/60 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 rounded-lg border border-transparent px-2 py-1.5 text-sm transition-all" className="group/item grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 rounded-lg border border-transparent px-2 py-1.5 text-[13px] transition-all hover:bg-white/[0.03]"
> >
<span <span
className="text-muted-foreground group-hover/item:text-foreground min-w-0 truncate font-semibold" className="text-muted-foreground group-hover/item:text-foreground min-w-0 truncate font-semibold"
@@ -298,7 +291,7 @@ export function CloudAccountCard({
const providerGroupedQuotaSection = const providerGroupedQuotaSection =
providerStats && providerStats.visibleModels > 0 ? ( providerStats && providerStats.visibleModels > 0 ? (
<> <>
<div className="bg-muted/40 flex items-center justify-between rounded-lg px-3 py-1.5 text-xs"> <div className="flex items-center justify-between rounded-lg bg-white/[0.03] px-3 py-1.5 text-xs">
<span className="font-medium">{t('settings.providerGroupings.overall')}</span> <span className="font-medium">{t('settings.providerGroupings.overall')}</span>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span <span
@@ -350,7 +343,7 @@ export function CloudAccountCard({
return ( return (
<Card <Card
className={`group bg-card hover:border-primary/40 flex h-full flex-col overflow-hidden border transition-all duration-200 hover:shadow-sm ${isSelected ? 'ring-primary border-primary/50 ring-2' : ''}`} className={`group flex h-full flex-col overflow-hidden rounded-xl border border-white/[0.06] bg-card transition-all duration-200 hover:border-white/[0.12] ${isSelected ? 'ring-accent/30 border-accent/40 ring-2' : ''}`}
> >
<CardHeader className="relative flex flex-row items-center gap-4 space-y-0 pb-2"> <CardHeader className="relative flex flex-row items-center gap-4 space-y-0 pb-2">
{onToggleSelection && ( {onToggleSelection && (
@@ -372,7 +365,7 @@ export function CloudAccountCard({
className="bg-muted h-10 w-10 rounded-full border" className="bg-muted h-10 w-10 rounded-full border"
/> />
) : ( ) : (
<div className="bg-primary/10 text-primary flex h-10 w-10 items-center justify-center rounded-full border"> <div className="flex h-10 w-10 items-center justify-center rounded-full bg-white/[0.06] text-muted-foreground">
{account.name?.[0]?.toUpperCase() || 'A'} {account.name?.[0]?.toUpperCase() || 'A'}
</div> </div>
)} )}
@@ -500,7 +493,7 @@ export function CloudAccountCard({
{account.provider.toUpperCase()} {account.provider.toUpperCase()}
</Badge> </Badge>
{account.is_active && ( {account.is_active && (
<Badge variant="default" className="bg-green-500 text-xs hover:bg-green-600"> <Badge variant="default" className="bg-emerald-500/15 text-emerald-400 border-emerald-500/20 text-xs hover:bg-emerald-500/20">
{t('cloud.card.active')} {t('cloud.card.active')}
</Badge> </Badge>
)} )}
@@ -521,7 +514,7 @@ export function CloudAccountCard({
)} )}
{account.is_active ? ( {account.is_active ? (
<Button variant="ghost" size="sm" disabled className="text-green-600 opacity-100"> <Button variant="ghost" size="sm" disabled className="text-emerald-400 opacity-100">
<Power className="mr-1 h-3 w-3" /> <Power className="mr-1 h-3 w-3" />
{t('cloud.card.active')} {t('cloud.card.active')}
</Button> </Button>
@@ -558,45 +551,11 @@ export function CloudAccountCard({
</div> </div>
</CardContent> </CardContent>
<CardFooter className="bg-muted/20 text-muted-foreground justify-between border-t p-2 px-4 text-xs"> <CardFooter className="justify-center border-t border-white/[0.04] p-2 px-4 text-xs text-muted-foreground">
<span> <span>
{t('cloud.card.used')}{' '} {t('cloud.card.used')}{' '}
{formatDistanceToNow(account.last_used * 1000, { addSuffix: true })} {formatDistanceToNow(account.last_used * 1000, { addSuffix: true })}
</span> </span>
<div className="flex items-center gap-2">
<Input
value={proxyUrl}
onChange={(e) => {
setProxyUrl(e.target.value);
setProxySaved(false);
}}
onBlur={() => {
const trimmed = proxyUrl.trim();
if (trimmed && !isValidProxyUrl(trimmed)) {
setProxyUrl(account.proxy_url || '');
return;
}
if (trimmed !== (account.proxy_url || '')) {
setAccountProxy.mutate({
accountId: account.id,
proxyUrl: trimmed || null,
});
setProxySaved(true);
setTimeout(() => setProxySaved(false), 2000);
}
}}
placeholder={t('cloud.card.proxyPlaceholder')}
className="h-6 w-40 text-xs"
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.currentTarget.blur();
}
}}
/>
{proxySaved && (
<span className="text-[10px] text-green-500">{t('cloud.card.proxySaved')}</span>
)}
</div>
</CardFooter> </CardFooter>
</Card> </Card>
); );
@@ -654,7 +613,7 @@ export function CompactCloudAccountCard({
); );
return ( return (
<div className="group bg-card hover:border-primary/40 flex items-center gap-3 rounded-lg border px-3 py-2 transition-all duration-200"> <div className="group flex items-center gap-3 rounded-xl border border-white/[0.06] bg-card px-3 py-2 transition-all duration-200 hover:border-white/[0.12]">
{account.avatar_url ? ( {account.avatar_url ? (
<img <img
src={account.avatar_url} src={account.avatar_url}
@@ -662,14 +621,14 @@ export function CompactCloudAccountCard({
className="bg-muted h-7 w-7 rounded-full border" className="bg-muted h-7 w-7 rounded-full border"
/> />
) : ( ) : (
<div className="bg-primary/10 text-primary flex h-7 w-7 items-center justify-center rounded-full border text-xs font-semibold"> <div className="flex h-7 w-7 items-center justify-center rounded-full bg-white/[0.06] text-xs font-semibold text-muted-foreground">
{account.name?.[0]?.toUpperCase() || 'A'} {account.name?.[0]?.toUpperCase() || 'A'}
</div> </div>
)} )}
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="truncate text-sm font-semibold"> <span className="truncate text-[13px] font-semibold">
{account.name || t('cloud.card.unknown')} {account.name || t('cloud.card.unknown')}
</span> </span>
<Badge <Badge
@@ -685,7 +644,7 @@ export function CompactCloudAccountCard({
{account.is_active && ( {account.is_active && (
<Badge <Badge
variant="default" variant="default"
className="shrink-0 bg-green-500 text-[10px] hover:bg-green-600" className="shrink-0 bg-emerald-500/15 text-emerald-400 border-emerald-500/20 text-[10px] hover:bg-emerald-500/20"
> >
{t('cloud.card.active')} {t('cloud.card.active')}
</Badge> </Badge>
@@ -797,7 +756,7 @@ export function CompactCloudAccountCard({
variant="ghost" variant="ghost"
size="sm" size="sm"
disabled disabled
className="h-7 text-xs text-green-600 opacity-100" className="h-7 text-xs text-emerald-400 opacity-100"
> >
<Power className="mr-1 h-3 w-3" /> <Power className="mr-1 h-3 w-3" />
{t('cloud.card.active')} {t('cloud.card.active')}
+23 -29
View File
@@ -85,10 +85,10 @@ import { shouldAutoSubmitGoogleAuthCode } from '@/utils/googleAuthSubmission';
export type GridLayout = 'auto' | '2-col' | '3-col' | 'list' | 'compact'; export type GridLayout = 'auto' | '2-col' | '3-col' | 'list' | 'compact';
const GRID_LAYOUT_CLASSES: Record<GridLayout, string> = { const GRID_LAYOUT_CLASSES: Record<GridLayout, string> = {
auto: 'grid gap-4 md:grid-cols-2 xl:grid-cols-3', auto: 'grid gap-3 md:grid-cols-2 xl:grid-cols-3',
'2-col': 'grid gap-4 grid-cols-2', '2-col': 'grid gap-3 grid-cols-2',
'3-col': 'grid gap-4 grid-cols-3', '3-col': 'grid gap-3 grid-cols-3',
list: 'grid gap-4 grid-cols-1', list: 'grid gap-3 grid-cols-1',
compact: 'flex flex-col gap-2', compact: 'flex flex-col gap-2',
}; };
@@ -99,9 +99,9 @@ const GLOBAL_QUOTA_BAR_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = {
}; };
const GLOBAL_QUOTA_TEXT_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = { const GLOBAL_QUOTA_TEXT_COLOR_CLASS_BY_STATUS: Record<QuotaStatus, string> = {
high: 'text-emerald-600 dark:text-emerald-400', high: 'text-emerald-400',
medium: 'text-amber-600 dark:text-amber-400', medium: 'text-amber-400',
low: 'text-rose-600 dark:text-rose-400', low: 'text-rose-400',
}; };
export function CloudAccountList() { export function CloudAccountList() {
@@ -259,16 +259,12 @@ export function CloudAccountList() {
return; return;
} }
const activeClientKey = oauthClients.find((client) => client.is_active)?.key; const activeClientKey = oauthClients.find((client) => client.is_active)?.key;
if (activeClientKey) { if (activeClientKey && activeClientKey !== selectedOAuthClientKey) { setTimeout(() => setSelectedOAuthClientKey(activeClientKey), 0); }
setSelectedOAuthClientKey(activeClientKey);
}
}, [oauthClients, selectedOAuthClientKey]); }, [oauthClients, selectedOAuthClientKey]);
// Listen for Google Auth Code // Listen for Google Auth Code
useEffect(() => { useEffect(() => {
if (window.electron?.onGoogleAuthCode) { if (window.electron?.onGoogleAuthCode) {
console.log('[OAuth] Registering Google auth code IPC listener');
const cleanup = window.electron.onGoogleAuthCode((code) => { const cleanup = window.electron.onGoogleAuthCode((code) => {
console.log('[OAuth] Received Google auth code via IPC:', code?.substring(0, 10) + '...');
lastSubmittedAuthCodeRef.current = null; lastSubmittedAuthCodeRef.current = null;
setAuthCode(code); setAuthCode(code);
}); });
@@ -286,7 +282,6 @@ export function CloudAccountList() {
lastSubmittedAuthCode: lastSubmittedAuthCodeRef.current, lastSubmittedAuthCode: lastSubmittedAuthCodeRef.current,
}) })
) { ) {
console.log('[OAuth] Auto-submitting Google auth code');
submitAuthCode(authCode); submitAuthCode(authCode);
} }
}, [addMutation.isPending, authCode, isAddDialogOpen, submitAuthCode]); }, [addMutation.isPending, authCode, isAddDialogOpen, submitAuthCode]);
@@ -308,7 +303,6 @@ export function CloudAccountList() {
}, [error, errorUpdatedAt, isError, t, toast]); }, [error, errorUpdatedAt, isError, t, toast]);
const handleRefresh = (id: string) => { const handleRefresh = (id: string) => {
console.log(`[Renderer] Triggering refresh for: ${id}`);
refreshMutation.mutate( refreshMutation.mutate(
{ accountId: id }, { accountId: id },
{ {
@@ -669,34 +663,34 @@ export function CloudAccountList() {
return ( return (
<div className="space-y-5 pb-20"> <div className="space-y-5 pb-20">
<div className="bg-card rounded-lg border p-5"> <div className="rounded-xl border border-white/[0.06] p-5">
<div className="flex flex-wrap items-start justify-between gap-4"> <div className="flex flex-wrap items-start justify-between gap-4">
<div className="flex shrink-0 flex-col gap-1"> <div className="flex shrink-0 flex-col gap-1">
<h2 className="text-2xl font-bold tracking-tight">{t('cloud.title')}</h2> <h2 className="text-lg font-semibold tracking-tight">{t('cloud.title')}</h2>
<p className="text-muted-foreground max-w-2xl">{t('cloud.description')}</p> <p className="text-muted-foreground max-w-2xl text-[13px]">{t('cloud.description')}</p>
</div> </div>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<div className="bg-muted/50 rounded-md border px-3 py-2"> <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase"> <div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.card.actions')} {t('cloud.card.actions')}
</div> </div>
<div className="text-base font-semibold">{totalAccounts}</div> <div className="text-sm font-semibold tabular-nums">{totalAccounts}</div>
</div> </div>
<div className="bg-muted/50 rounded-md border px-3 py-2"> <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase"> <div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.card.active')} {t('cloud.card.active')}
</div> </div>
<div className="text-base font-semibold text-emerald-600">{activeAccounts}</div> <div className="text-sm font-semibold text-emerald-400">{activeAccounts}</div>
</div> </div>
<div className="bg-muted/50 rounded-md border px-3 py-2"> <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase"> <div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.card.rateLimited')} {t('cloud.card.rateLimited')}
</div> </div>
<div className="text-base font-semibold text-rose-600">{rateLimitedAccounts}</div> <div className="text-sm font-semibold text-rose-400">{rateLimitedAccounts}</div>
</div> </div>
{/* Global Quota */} {/* Global Quota */}
{overallQuotaPercentage !== null && ( {overallQuotaPercentage !== null && (
<div className="bg-muted/50 rounded-md border px-3 py-2"> <div className="rounded-lg border border-white/[0.06] bg-white/[0.02] px-3 py-2">
<div className="text-muted-foreground text-[11px] uppercase"> <div className="text-muted-foreground text-[11px] uppercase">
{t('cloud.globalQuota')} {t('cloud.globalQuota')}
</div> </div>
@@ -719,13 +713,13 @@ export function CloudAccountList() {
</div> </div>
</div> </div>
<div className="bg-card flex flex-wrap items-center gap-2 rounded-lg border p-3"> <div className="flex flex-wrap items-center gap-2 rounded-xl border border-white/[0.06] bg-card p-2.5">
<div className="bg-muted/50 flex items-center gap-2 rounded-md border px-3 py-2"> <div className="flex items-center gap-2 rounded-lg border border-white/[0.06] px-3 py-1.5">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Zap <Zap
className={`h-4 w-4 ${autoSwitchEnabled ? 'fill-yellow-500 text-yellow-500' : 'text-muted-foreground'}`} className={`h-4 w-4 ${autoSwitchEnabled ? 'fill-yellow-500 text-yellow-500' : 'text-muted-foreground'}`}
/> />
<Label htmlFor="auto-switch" className="cursor-pointer text-sm font-medium"> <Label htmlFor="auto-switch" className="cursor-pointer text-[13px] font-medium">
{t('cloud.autoSwitch')} {t('cloud.autoSwitch')}
</Label> </Label>
</div> </div>
@@ -1114,7 +1108,7 @@ export function CloudAccountList() {
)} )}
{sortedAccounts.length === 0 && ( {sortedAccounts.length === 0 && (
<div className="text-muted-foreground bg-muted/20 col-span-full rounded-lg border border-dashed py-14 text-center"> <div className="text-muted-foreground col-span-full rounded-xl border border-dashed border-white/[0.1] py-14 text-center">
<Cloud className="mx-auto mb-3 h-10 w-10 opacity-40" /> <Cloud className="mx-auto mb-3 h-10 w-10 opacity-40" />
<div className="text-sm">{t('cloud.list.noAccounts')}</div> <div className="text-sm">{t('cloud.list.noAccounts')}</div>
</div> </div>
@@ -1123,7 +1117,7 @@ export function CloudAccountList() {
{/* Batch Action Bar */} {/* Batch Action Bar */}
{selectedIds.size > 0 && ( {selectedIds.size > 0 && (
<div className="bg-card animate-in fade-in slide-in-from-bottom-4 fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border px-6 py-2 shadow-lg"> <div className="bg-card animate-in fade-in slide-in-from-bottom-4 fixed bottom-6 left-1/2 z-50 flex -translate-x-1/2 items-center gap-4 rounded-full border border-white/[0.1] px-6 py-2 shadow-2xl shadow-black/30">
<div className="flex items-center gap-2 border-r pr-4"> <div className="flex items-center gap-2 border-r pr-4">
<span className="text-sm font-semibold"> <span className="text-sm font-semibold">
{t('cloud.batch.selected', { count: selectedIds.size })} {t('cloud.batch.selected', { count: selectedIds.size })}
+2 -3
View File
@@ -134,8 +134,7 @@ export function IdentityProfileDialog({ account, open, onOpenChange }: IdentityP
if (!open) { if (!open) {
return; return;
} }
void refreshProfiles(); setTimeout(() => { void refreshProfiles(); }, 0); }, [open, refreshProfiles]);
}, [open, refreshProfiles]);
const runAction = async (key: string, action: () => Promise<void>) => { const runAction = async (key: string, action: () => Promise<void>) => {
if (actionLockRef.current) { if (actionLockRef.current) {
@@ -344,7 +343,7 @@ export function IdentityProfileDialog({ account, open, onOpenChange }: IdentityP
{!showLoadingPlaceholder {!showLoadingPlaceholder
? history.map((version) => ( ? history.map((version) => (
<div key={version.id} className="bg-muted/20 rounded-xl border p-3"> <div key={version.id} className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-3">
<div className="mb-2 flex items-center justify-between gap-3"> <div className="mb-2 flex items-center justify-between gap-3">
<div className="min-w-0"> <div className="min-w-0">
<div className="truncate text-sm font-medium">{version.label}</div> <div className="truncate text-sm font-medium">{version.label}</div>
+27 -9
View File
@@ -9,7 +9,7 @@ import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch'; import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { Loader2, Search, RotateCcw, Save } from 'lucide-react'; import { Loader2, Search, RotateCcw, Save, Copy, CheckCircle } from 'lucide-react';
import { filter, flatMap, includes, size, sortBy, sumBy, uniq, values } from 'lodash-es'; import { filter, flatMap, includes, size, sortBy, sumBy, uniq, values } from 'lodash-es';
import type { CloudAccount } from '@/types/cloudAccount'; import type { CloudAccount } from '@/types/cloudAccount';
@@ -44,15 +44,12 @@ export function ModelVisibilitySettings() {
const [modelVisibilityMap, setModelVisibilityMap] = useState<Record<string, boolean>>({}); const [modelVisibilityMap, setModelVisibilityMap] = useState<Record<string, boolean>>({});
const [providerGroupingEnabled, setProviderGroupingEnabled] = useState(false); const [providerGroupingEnabled, setProviderGroupingEnabled] = useState(false);
const [isSavingSettings, setIsSavingSettings] = useState(false); const [isSavingSettings, setIsSavingSettings] = useState(false);
const [copiedModel, setCopiedModel] = useState<string | null>(null);
// Initialize model visibility and provider groupings from config // Initialize model visibility and provider groupings from config
useEffect(() => { useEffect(() => {
if (config?.model_visibility) { if (config?.model_visibility) { setTimeout(() => setModelVisibilityMap(config.model_visibility), 0); }
setModelVisibilityMap(config.model_visibility); if (config?.provider_groupings_enabled !== undefined) { setTimeout(() => setProviderGroupingEnabled(config.provider_groupings_enabled), 0); }
}
if (config?.provider_groupings_enabled !== undefined) {
setProviderGroupingEnabled(config.provider_groupings_enabled);
}
}, [config?.model_visibility, config?.provider_groupings_enabled]); }, [config?.model_visibility, config?.provider_groupings_enabled]);
// Get all unique models from all accounts // Get all unique models from all accounts
@@ -114,6 +111,14 @@ export function ModelVisibilitySettings() {
})); }));
}; };
const copyModelId = (modelId: string, e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
navigator.clipboard.writeText(modelId);
setCopiedModel(modelId);
setTimeout(() => setCopiedModel(null), 2000);
};
if (accountsLoading) { if (accountsLoading) {
return ( return (
<Card> <Card>
@@ -179,7 +184,7 @@ export function ModelVisibilitySettings() {
return ( return (
<div <div
key={modelId} key={modelId}
className="hover:bg-muted/50 flex items-center space-x-3 rounded p-2" className="flex items-center space-x-3 rounded-lg p-2 hover:bg-white/[0.03] transition-colors"
> >
<Checkbox <Checkbox
id={`model-${modelId}`} id={`model-${modelId}`}
@@ -188,12 +193,25 @@ export function ModelVisibilitySettings() {
handleModelVisibilityChange(modelId, checked as boolean) handleModelVisibilityChange(modelId, checked as boolean)
} }
/> />
<div className="flex flex-1 items-center gap-2">
<label <label
htmlFor={`model-${modelId}`} htmlFor={`model-${modelId}`}
className="flex-1 cursor-pointer text-sm font-medium" className="cursor-pointer text-sm font-medium"
> >
{modelId} {modelId}
</label> </label>
<button
onClick={(e) => copyModelId(modelId, e)}
className="text-muted-foreground hover:text-foreground transition-colors"
title={t('proxy.copy')}
>
{copiedModel === modelId ? (
<CheckCircle className="h-4 w-4 text-emerald-400" />
) : (
<Copy className="h-4 w-4" />
)}
</button>
</div>
{!isVisible && ( {!isVisible && (
<Badge variant="secondary" className="text-xs"> <Badge variant="secondary" className="text-xs">
{t('settings.modelVisibility.hidden')} {t('settings.modelVisibility.hidden')}
+7 -7
View File
@@ -37,12 +37,12 @@ export const ProviderGroup: React.FC<ProviderGroupProps> = ({
} }
return ( return (
<div className="border-border/60 overflow-hidden rounded-lg border"> <div className="overflow-hidden rounded-xl border border-white/[0.06]">
{/* Provider Header */} {/* Provider Header */}
<button <button
type="button" type="button"
onClick={onToggleCollapse} onClick={onToggleCollapse}
className="hover:bg-muted/60 flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-sm transition-colors" className="flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-[13px] transition-colors hover:bg-white/[0.03]"
> >
{isCollapsed ? ( {isCollapsed ? (
<ChevronRight className="text-muted-foreground h-3.5 w-3.5 shrink-0" /> <ChevronRight className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
@@ -87,7 +87,7 @@ export const ProviderGroup: React.FC<ProviderGroupProps> = ({
</span> </span>
)} )}
</div> </div>
<div className="bg-muted h-1.5 w-16 overflow-hidden rounded-full"> <div className="h-1.5 w-16 overflow-hidden rounded-full bg-white/[0.06]">
<div <div
className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColorClass(avgPercentage)}`} className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColorClass(avgPercentage)}`}
style={{ width: `${clampQuotaPercentage(avgPercentage)}%` }} style={{ width: `${clampQuotaPercentage(avgPercentage)}%` }}
@@ -98,12 +98,12 @@ export const ProviderGroup: React.FC<ProviderGroupProps> = ({
{/* Individual model rows (shown when expanded) */} {/* Individual model rows (shown when expanded) */}
{!isCollapsed && ( {!isCollapsed && (
<div className="border-border/40 border-t"> <div className="border-t border-white/[0.06]">
{visibleModels.map((model, index) => ( {visibleModels.map((model, index) => (
<div <div
key={model.id} key={model.id}
className={`hover:bg-muted/60 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 px-3 py-2 pl-9 text-sm transition-colors ${ className={`grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3 px-3 py-2 pl-9 text-[13px] transition-colors hover:bg-white/[0.03] ${
index < visibleModels.length - 1 ? 'border-border/20 border-b' : '' index < visibleModels.length - 1 ? 'border-b border-white/[0.04]' : ''
}`} }`}
> >
<span className="text-muted-foreground min-w-0 truncate" title={model.id}> <span className="text-muted-foreground min-w-0 truncate" title={model.id}>
@@ -126,7 +126,7 @@ export const ProviderGroup: React.FC<ProviderGroupProps> = ({
<span className="text-muted-foreground text-[10px]">{leftLabel}</span> <span className="text-muted-foreground text-[10px]">{leftLabel}</span>
)} )}
</div> </div>
<div className="bg-muted h-1.5 w-24 overflow-hidden rounded-full"> <div className="h-1.5 w-24 overflow-hidden rounded-full bg-white/[0.06]">
<div <div
className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColorClass(model.percentage)}`} className={`h-full rounded-full transition-all duration-300 ${getQuotaBarColorClass(model.percentage)}`}
style={{ width: `${clampQuotaPercentage(model.percentage)}%` }} style={{ width: `${clampQuotaPercentage(model.percentage)}%` }}
+47 -37
View File
@@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { isProcessRunning, startAntigravity, closeAntigravity } from '@/actions/process'; import { isProcessRunning, startGeminiNexus, closeGeminiNexus } from '@/actions/process';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Play, Square, Loader2, Power } from 'lucide-react'; import { Play, Square, Loader2, Power } from 'lucide-react';
@@ -18,18 +18,18 @@ export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) =>
const { data: isRunning, isLoading } = useQuery({ const { data: isRunning, isLoading } = useQuery({
queryKey: ['process', 'status'], queryKey: ['process', 'status'],
queryFn: isProcessRunning, queryFn: isProcessRunning,
refetchInterval: 10000, refetchInterval: 30000,
}); });
const startMutation = useMutation({ const startMutation = useMutation({
mutationFn: startAntigravity, mutationFn: startGeminiNexus,
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['process', 'status'] }); queryClient.invalidateQueries({ queryKey: ['process', 'status'] });
}, },
}); });
const stopMutation = useMutation({ const stopMutation = useMutation({
mutationFn: closeAntigravity, mutationFn: closeGeminiNexus,
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['process', 'status'] }); queryClient.invalidateQueries({ queryKey: ['process', 'status'] });
}, },
@@ -52,36 +52,38 @@ export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) =>
<TooltipProvider> <TooltipProvider>
<Tooltip delayDuration={0}> <Tooltip delayDuration={0}>
<TooltipTrigger asChild> <TooltipTrigger asChild>
<Button <button
variant="ghost"
size="icon"
onClick={handleToggle} onClick={handleToggle}
disabled={isLoading || isPending} disabled={isLoading || isPending}
className={cn( className={cn(
'h-10 w-10 rounded-lg transition-all duration-300', 'flex h-8 w-8 items-center justify-center rounded-lg transition-all duration-200',
'disabled:opacity-50 disabled:cursor-not-allowed',
isRunning 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-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20'
: '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', : 'bg-white/[0.04] text-muted-foreground hover:bg-white/[0.08] hover:text-foreground',
)} )}
> >
{isPending ? ( {isPending ? (
<Loader2 className="h-5 w-5 animate-spin" /> <Loader2 className="h-4 w-4 animate-spin" />
) : ( ) : (
<Power className="h-5 w-5" /> <Power className="h-4 w-4" />
)} )}
</Button> </button>
</TooltipTrigger> </TooltipTrigger>
<TooltipContent side="right" className="flex items-center gap-2"> <TooltipContent side="right" className="flex items-center gap-2 text-xs">
<div <div
className={cn('h-2 w-2 rounded-full', isRunning ? 'bg-green-500' : 'bg-red-500')} className={cn(
'h-1.5 w-1.5 rounded-full',
isRunning ? 'bg-emerald-400' : 'bg-muted-foreground',
)}
/> />
<p> <span>
{isLoading {isLoading
? t('status.checking') ? t('status.checking')
: isRunning : isRunning
? t('status.running') ? t('status.running')
: t('status.stopped')} : t('status.stopped')}
</p> </span>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
</TooltipProvider> </TooltipProvider>
@@ -93,23 +95,33 @@ export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) =>
return ( return (
<div <div
className={cn( 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 rounded-lg px-3 py-2 transition-all duration-200',
isRunning 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-emerald-500/[0.08]'
: 'bg-red-100 text-red-900 ring-red-200 dark:bg-red-900/20 dark:text-red-100 dark:ring-red-900/50', : 'bg-white/[0.02]',
)} )}
> >
<div className="flex flex-1 items-start gap-3"> <div className="flex items-center gap-2.5">
{isLoading ? ( {isLoading ? (
<Loader2 className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin" /> <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" />
) : 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="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={cn(
'h-2 w-2 shrink-0 rounded-full transition-colors duration-300',
isRunning
? 'bg-emerald-400 shadow-[0_0_6px_rgba(16,185,129,0.4)]'
: 'bg-muted-foreground/50',
)} )}
<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"> <div className="flex flex-col">
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
Status
</span>
<span className={cn(
'text-xs font-medium leading-tight',
isRunning ? 'text-emerald-400' : 'text-muted-foreground',
)}>
{isLoading {isLoading
? t('status.checking') ? t('status.checking')
: isRunning : isRunning
@@ -124,22 +136,20 @@ export const StatusBar: React.FC<StatusBarProps> = ({ isCollapsed = false }) =>
onClick={handleToggle} onClick={handleToggle}
disabled={isLoading || isPending} disabled={isLoading || isPending}
className={cn( className={cn(
'ml-2 h-8 shrink-0 rounded-md border px-3 transition-all', 'h-7 gap-1.5 rounded-md px-2.5 text-xs',
isRunning 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' ? 'text-emerald-400 hover:bg-emerald-500/10'
: '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', : 'text-muted-foreground hover:bg-white/[0.06]',
)} )}
> >
{isPending ? ( {isPending ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" /> <Loader2 className="h-3 w-3 animate-spin" />
) : isRunning ? ( ) : isRunning ? (
<Square className="h-3.5 w-3.5 fill-current" /> <Square className="h-3 w-3 fill-current" />
) : ( ) : (
<Play className="h-3.5 w-3.5 fill-current" /> <Play className="h-3 w-3 fill-current" />
)} )}
<span className="ml-2 font-semibold"> <span>{isRunning ? t('action.stop') : t('action.start')}</span>
{isRunning ? t('action.stop') : t('action.start')}
</span>
</Button> </Button>
</div> </div>
); );
+1 -1
View File
@@ -35,7 +35,7 @@ export default function DragWindowRegion({ title }: DragWindowRegionProps) {
<div className="flex w-screen items-stretch justify-between"> <div className="flex w-screen items-stretch justify-between">
<div className="draglayer w-full"> <div className="draglayer w-full">
{title && !isMacOS && ( {title && !isMacOS && (
<div className="flex flex-1 p-2 text-xs whitespace-nowrap text-gray-400 select-none"> <div className="flex flex-1 p-2 text-xs whitespace-nowrap text-muted-foreground select-none">
{title} {title}
</div> </div>
)} )}
+39
View File
@@ -0,0 +1,39 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { MonitorTab } from './advanced/MonitorTab';
import { ToolsTab } from './advanced/ToolsTab';
import { ReplayTab } from './advanced/ReplayTab';
import { CapabilitiesTab } from './advanced/CapabilitiesTab';
import type { ProxyConfig } from '@/types/config';
interface ProxyAdvancedTabProps {
proxyConfig: ProxyConfig;
}
export const ProxyAdvancedTab: React.FC<ProxyAdvancedTabProps> = () => {
const { t } = useTranslation();
return (
<Tabs defaultValue="monitor" className="space-y-5">
<TabsList className="grid w-full grid-cols-4">
<TabsTrigger value="monitor">{t('proxy.advanced.monitor')}</TabsTrigger>
<TabsTrigger value="tools">{t('proxy.advanced.tabs.tools')}</TabsTrigger>
<TabsTrigger value="replay">{t('proxy.advanced.tabs.replay')}</TabsTrigger>
<TabsTrigger value="capabilities">{t('proxy.advanced.tabs.capabilities')}</TabsTrigger>
</TabsList>
<TabsContent value="monitor">
<MonitorTab />
</TabsContent>
<TabsContent value="tools">
<ToolsTab />
</TabsContent>
<TabsContent value="replay">
<ReplayTab />
</TabsContent>
<TabsContent value="capabilities">
<CapabilitiesTab />
</TabsContent>
</Tabs>
);
};
@@ -0,0 +1,231 @@
import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { groupBy } from 'lodash-es';
import { ipc } from '@/ipc/manager';
import { Badge } from '@/components/ui/badge';
import { Loader2, Eye, Zap, Code, Brain, Star, Layers } from 'lucide-react';
interface ModelCapability {
id: string;
object: string;
displayName?: string;
capabilities: {
vision: boolean;
thinking: boolean;
streaming: boolean;
jsonMode: boolean;
recommended: boolean;
};
limits: {
maxTokens?: number;
maxOutputTokens?: number;
thinkingBudget?: number;
};
}
const CAPABILITY_ICONS = {
vision: Eye,
thinking: Brain,
streaming: Zap,
jsonMode: Code,
recommended: Star,
} as const;
const CAPABILITY_LABELS = {
vision: 'Vision',
thinking: 'Thinking',
streaming: 'Streaming',
jsonMode: 'JSON Mode',
recommended: 'Recommended',
} as const;
function getProvider(modelId: string): string {
const id = modelId.toLowerCase();
if (id.startsWith('gemini')) return 'Google';
if (id.startsWith('claude')) return 'Anthropic';
if (id.startsWith('gpt') || id.startsWith('o1') || id.startsWith('o3') || id.startsWith('text-'))
return 'OpenAI';
if (id.startsWith('deepseek')) return 'DeepSeek';
if (id.startsWith('meta-llama') || id.startsWith('llama')) return 'Meta';
if (id.startsWith('mistral') || id.startsWith('mixtral')) return 'Mistral';
if (id.startsWith('qwen')) return 'Alibaba';
if (id.startsWith('x-ai') || id.startsWith('grok')) return 'xAI';
if (id.startsWith('sonar')) return 'Perplexity';
if (id.startsWith('command')) return 'Cohere';
return 'Other';
}
/** Format large token counts with K/M suffixes */
function formatTokenCount(value: number): string {
if (value >= 1_000_000) {
return `${(value / 1_000_000).toFixed(1)}M`;
}
if (value >= 1_000) {
return `${(value / 1_000).toFixed(0)}K`;
}
return value.toLocaleString();
}
export const CapabilitiesTab: React.FC = () => {
const { t } = useTranslation();
const { data: capabilitiesData, isLoading } = useQuery({
queryKey: ['proxyAdvanced', 'modelCapabilities'],
queryFn: () => ipc.client.proxyAdvanced.getModelCapabilities(),
refetchInterval: 60000,
});
const models: ModelCapability[] = capabilitiesData?.success
? (capabilitiesData.data as ModelCapability[])
: [];
const groupedModels = useMemo(() => {
return groupBy(models, (m) => getProvider(m.id));
}, [models]);
const sortedProviders = Object.keys(groupedModels).sort((a, b) => {
if (a === 'Other') return 1;
if (b === 'Other') return -1;
return a.localeCompare(b);
});
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold">
{t('proxy.advanced.capabilities.title', 'Model Capabilities')}
</h3>
<p className="text-[13px] text-muted-foreground">
{t('proxy.advanced.capabilities.description', 'Discover what each model can do')}
</p>
</div>
{models.length > 0 && (
<Badge variant="outline" className="text-xs tabular-nums">
<Layers className="mr-1.5 h-3 w-3" />
{models.length} models
</Badge>
)}
</div>
{/* Content */}
{isLoading ? (
<div className="flex h-40 items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-8">
{sortedProviders.map((provider) => (
<div key={provider} className="space-y-3">
{/* Provider header */}
<div className="flex items-center gap-3">
<h4 className="text-[13px] font-semibold tracking-wide uppercase text-muted-foreground">
{provider}
</h4>
<div className="h-px flex-1 bg-white/[0.06]" />
<span className="text-[11px] text-muted-foreground/60 tabular-nums">
{groupedModels[provider].length}
</span>
</div>
{/* Model cards */}
<div className="grid grid-cols-1 gap-3 md:grid-cols-2 lg:grid-cols-3">
{groupedModels[provider].map((model) => {
const enabledCount = Object.values(model.capabilities).filter(Boolean).length;
const totalCount = Object.values(model.capabilities).length;
const hasLimits = Object.values(model.limits).some((v) => v != null);
return (
<div
key={model.id}
className="group flex flex-col rounded-xl border border-white/[0.06] bg-card p-4 transition-all hover:border-white/[0.12] hover:bg-white/[0.02]"
>
{/* Model header */}
<div className="mb-3 space-y-1">
<div className="flex items-start justify-between gap-2">
<h5
className="text-[13px] font-semibold leading-tight truncate"
title={model.displayName || model.id}
>
{model.displayName || model.id}
</h5>
<span className="shrink-0 text-[10px] font-medium text-muted-foreground/60 rounded-md bg-white/[0.04] px-1.5 py-0.5">
{enabledCount}/{totalCount}
</span>
</div>
<p
className="font-mono text-[11px] text-muted-foreground truncate"
title={model.id}
>
{model.id}
</p>
</div>
{/* Capability pills */}
<div className="flex flex-wrap gap-1.5 mb-3">
{Object.entries(model.capabilities).map(([key, supported]) => {
const iconKey = key as keyof typeof CAPABILITY_ICONS;
const Icon = CAPABILITY_ICONS[iconKey];
const label = CAPABILITY_LABELS[iconKey];
return (
<div
key={key}
className={`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${
supported
? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/15'
: 'bg-white/[0.02] text-muted-foreground/50 border border-white/[0.04]'
}`}
title={label}
>
<Icon className="h-3 w-3 shrink-0" />
{label}
</div>
);
})}
</div>
{/* Limits section */}
{hasLimits && (
<div className="mt-auto flex flex-wrap gap-1.5 border-t border-white/[0.04] pt-3">
{model.limits.maxTokens != null && (
<span className="inline-flex items-center rounded-md bg-white/[0.04] px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
CTX {formatTokenCount(model.limits.maxTokens)}
</span>
)}
{model.limits.maxOutputTokens != null && (
<span className="inline-flex items-center rounded-md bg-white/[0.04] px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
OUT {formatTokenCount(model.limits.maxOutputTokens)}
</span>
)}
{model.limits.thinkingBudget != null && (
<span className="inline-flex items-center rounded-md bg-blue-500/10 border border-blue-500/15 px-1.5 py-0.5 font-mono text-[10px] text-blue-300">
THINK {formatTokenCount(model.limits.thinkingBudget)}
</span>
)}
</div>
)}
</div>
);
})}
</div>
</div>
))}
{models.length === 0 && (
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-white/[0.1] py-16 text-center">
<Layers className="h-8 w-8 text-muted-foreground/30" />
<div className="space-y-1">
<p className="text-[13px] font-medium">No models found</p>
<p className="text-xs text-muted-foreground">
Check your provider configurations
</p>
</div>
</div>
)}
</div>
)}
</div>
);
};
@@ -0,0 +1,206 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { ipc } from '@/ipc/manager';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { StatCard } from '@/components/usage/StatCard';
import { TrafficLogTable } from './TrafficLogTable';
import { Loader2, Zap, Clock, AlertTriangle, Network, HardDrive } from 'lucide-react';
export const MonitorTab: React.FC = () => {
const { t } = useTranslation();
const { toast } = useToast();
const [direction, setDirection] = useState<string>('all');
const { data: metricsData, isLoading: metricsLoading } = useQuery({
queryKey: ['proxyAdvanced', 'metrics'],
queryFn: () => ipc.client.proxyAdvanced.getProxyMetrics(),
refetchInterval: 30000,
});
const { data: cbData, isLoading: cbLoading } = useQuery({
queryKey: ['proxyAdvanced', 'circuitBreaker'],
queryFn: () => ipc.client.proxyAdvanced.getCircuitBreakerStatus(),
refetchInterval: 30000,
});
const { data: logsData, isLoading: logsLoading } = useQuery({
queryKey: ['proxyAdvanced', 'logs', direction],
queryFn: () =>
ipc.client.proxyAdvanced.getRecentTrafficLogs({
limit: 50,
direction: direction === 'all' ? undefined : direction,
}),
refetchInterval: 30000,
});
const { data: statsData } = useQuery({
queryKey: ['proxyAdvanced', 'stats'],
queryFn: () => ipc.client.proxyAdvanced.getTrafficLogStats(),
refetchInterval: 30000,
});
const metrics = metricsData?.success ? metricsData.data : undefined;
const circuitBreakers = cbData?.success ? cbData.data : undefined;
const logs = logsData?.success ? logsData.data : [];
const stats = statsData?.success ? statsData.data : undefined;
const handleExport = async (format: 'json' | 'csv') => {
const result = await ipc.client.proxyAdvanced.exportTrafficLogs({ format });
if (result.success && result.data) {
navigator.clipboard.writeText(result.data);
toast({ title: t('proxy.advanced.tools.copyConfig') });
} else {
toast({ title: t('common.error'), description: result.error });
}
};
const getCircuitBadgeVariant = (state: string): React.ComponentProps<typeof Badge>['variant'] => {
if (state === 'closed') return 'default';
if (state === 'open') return 'destructive';
return 'secondary';
};
return (
<div className="space-y-5">
{/* Metrics */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
<StatCard
label={t('proxy.advanced.metrics.requestsPerMinute')}
value={metrics ? Math.round(metrics.requestsPerMinute) : 0}
icon={Zap}
isLoading={metricsLoading}
accent="amber"
/>
<StatCard
label={t('proxy.advanced.metrics.avgLatency')}
value={metrics ? Math.round(metrics.avgLatency) : 0}
icon={Clock}
isLoading={metricsLoading}
accent="blue"
/>
<StatCard
label={t('proxy.advanced.metrics.errorRate')}
value={metrics ? Math.round(metrics.errorRate * 100) : 0}
icon={AlertTriangle}
isLoading={metricsLoading}
accent="amber"
/>
<StatCard
label={t('proxy.advanced.metrics.activeConnections')}
value={metrics?.activeConnections ?? 0}
icon={Network}
isLoading={metricsLoading}
accent="green"
/>
<StatCard
label={t('proxy.advanced.metrics.cacheStatus')}
value={metrics?.cacheHitRate ? `${Math.round(metrics.cacheHitRate * 100)}%` : 'N/A'}
icon={HardDrive}
isLoading={metricsLoading}
accent="purple"
/>
</div>
{/* Circuit Breakers */}
<div className="overflow-hidden rounded-xl border border-white/[0.06] bg-card">
<div className="border-b border-white/[0.06] px-5 py-4">
<h4 className="text-[13px] font-semibold">
{t('proxy.advanced.circuitBreaker.title')}
</h4>
</div>
<div className="p-5">
{cbLoading ? (
<div className="flex h-20 items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
) : !circuitBreakers ? (
<p className="text-[13px] text-muted-foreground">No data</p>
) : (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{Object.entries(circuitBreakers.states).map(([api, state]) => (
<div key={api} className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-4">
<div className="flex items-center justify-between">
<span className="text-[13px] font-medium">{api}</span>
<Badge variant={getCircuitBadgeVariant(state.state)}>
{state.state}
</Badge>
</div>
<div className="mt-2 text-xs text-muted-foreground">
{t('proxy.advanced.circuitBreaker.failures')}: {state.failures}
</div>
{state.lastFailure && (
<div className="text-xs text-muted-foreground">
{t('proxy.advanced.circuitBreaker.lastFailure')}:{' '}
{new Date(state.lastFailure).toLocaleString()}
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
{/* Traffic Logs */}
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-3">
<h3 className="text-[13px] font-semibold">
{t('proxy.advanced.trafficLog.title')}
</h3>
{stats && (
<span className="text-xs text-muted-foreground">
Total: {stats.total}
</span>
)}
</div>
<div className="flex items-center gap-2">
<Select value={direction} onValueChange={setDirection}>
<SelectTrigger className="h-8 w-[140px] text-xs">
<SelectValue placeholder={t('proxy.advanced.trafficLog.direction')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">
{t('proxy.advanced.trafficLog.all')}
</SelectItem>
<SelectItem value="inbound">
{t('proxy.advanced.trafficLog.inbound')}
</SelectItem>
<SelectItem value="outbound">
{t('proxy.advanced.trafficLog.outbound')}
</SelectItem>
</SelectContent>
</Select>
<Button
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={() => handleExport('json')}
>
{t('proxy.advanced.trafficLog.exportJson')}
</Button>
<Button
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={() => handleExport('csv')}
>
{t('proxy.advanced.trafficLog.exportCsv')}
</Button>
</div>
</div>
<TrafficLogTable logs={logs || []} isLoading={logsLoading} />
</div>
</div>
);
};
+173
View File
@@ -0,0 +1,173 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ipc } from '@/ipc/manager';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Play, RefreshCw, Clock, AlertCircle, CheckCircle } from 'lucide-react';
interface ReplayEntry {
id: string;
timestamp: number;
method: string;
endpoint: string;
status?: number;
duration?: number;
body?: unknown;
}
export const ReplayTab: React.FC = () => {
const { t } = useTranslation();
const { toast } = useToast();
const queryClient = useQueryClient();
const [selectedRequestId, setSelectedRequestId] = useState<string | null>(null);
const {
data: requestsData,
isLoading: requestsLoading,
refetch: refetchRequests,
} = useQuery({
queryKey: ['proxyAdvanced', 'recentRequests'],
queryFn: () => ipc.client.proxyAdvanced.getRecentRequests(),
refetchInterval: 10000,
});
const replayMutation = useMutation({
mutationFn: (requestId: string) => ipc.client.proxyAdvanced.replayRequest({ requestId }),
onSuccess: (data) => {
if (data.success) {
toast({
title: t('proxy.advanced.replay.success'),
description: t('proxy.advanced.replay.replayedSuccessfully'),
});
} else {
toast({
title: t('proxy.advanced.replay.error'),
description: data.error || t('proxy.advanced.replay.unknownError'),
variant: 'destructive',
});
}
setSelectedRequestId(null);
},
onError: (error) => {
toast({
title: t('proxy.advanced.replay.error'),
description: error instanceof Error ? error.message : t('proxy.advanced.replay.unknownError'),
variant: 'destructive',
});
setSelectedRequestId(null);
},
});
const requests: ReplayEntry[] = requestsData?.success ? (requestsData.data as ReplayEntry[]) : [];
const handleReplay = (requestId: string) => {
setSelectedRequestId(requestId);
replayMutation.mutate(requestId);
};
const formatTimestamp = (timestamp: number): string => {
return new Date(timestamp).toLocaleTimeString();
};
const getStatusBadge = (status?: number) => {
if (!status) return <Badge variant="outline">{t('proxy.advanced.replay.pending')}</Badge>;
if (status >= 200 && status < 300) {
return (
<Badge variant="default" className="bg-emerald-500/15 text-emerald-400 border-emerald-500/20 hover:bg-emerald-500/20">
<CheckCircle className="mr-1 h-3 w-3" />
{status}
</Badge>
);
}
if (status >= 400) {
return (
<Badge variant="destructive">
<AlertCircle className="mr-1 h-3 w-3" />
{status}
</Badge>
);
}
return <Badge variant="secondary">{status}</Badge>;
};
return (
<div className="space-y-5">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-base font-semibold">{t('proxy.advanced.replay.title')}</h3>
<p className="text-[13px] text-muted-foreground">{t('proxy.advanced.replay.description')}</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => refetchRequests()}
disabled={requestsLoading}
>
<RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${requestsLoading ? 'animate-spin' : ''}`} />
{t('proxy.advanced.replay.refresh')}
</Button>
</div>
{/* Requests List */}
<div className="overflow-hidden rounded-xl border border-white/[0.06] bg-card">
<div className="border-b border-white/[0.06] px-5 py-4 space-y-1">
<h4 className="text-[13px] font-semibold">{t('proxy.advanced.replay.recentRequests')}</h4>
<p className="text-xs text-muted-foreground">{t('proxy.advanced.replay.clickToReplay')}</p>
</div>
<div className="p-5">
{requestsLoading ? (
<div className="flex h-32 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : requests.length === 0 ? (
<div className="flex h-32 flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-white/[0.1]">
<Clock className="h-6 w-6 text-muted-foreground/30" />
<p className="text-[13px] text-muted-foreground">
{t('proxy.advanced.replay.noRequests')}
</p>
</div>
) : (
<div className="space-y-2">
{requests.map((request) => (
<div
key={request.id}
className="flex items-center justify-between rounded-xl border border-white/[0.06] p-3 transition-colors hover:bg-white/[0.02]"
>
<div className="flex items-center gap-3">
{getStatusBadge(request.status)}
<div className="flex flex-col">
<span className="text-[13px] font-medium">
{request.method} {request.endpoint}
</span>
<span className="text-xs text-muted-foreground">
{formatTimestamp(request.timestamp)}
{request.duration && ` · ${request.duration}ms`}
</span>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleReplay(request.id)}
disabled={replayMutation.isPending && selectedRequestId === request.id}
>
{replayMutation.isPending && selectedRequestId === request.id ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Play className="mr-2 h-4 w-4" />
)}
{t('proxy.advanced.replay.replay')}
</Button>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
};
+134
View File
@@ -0,0 +1,134 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useQueries } from '@tanstack/react-query';
import { ipc } from '@/ipc/manager';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { StatCard } from '@/components/usage/StatCard';
import { Loader2, Copy, CheckCircle, ShieldAlert, XCircle, Terminal, Code2, Braces } from 'lucide-react';
const IDE_CONFIGS = [
{ key: 'vscode', label: 'VS Code', icon: Code2 },
{ key: 'cursor', label: 'Cursor', icon: Terminal },
{ key: 'claude-code', label: 'Claude Code', icon: Braces },
] as const;
export const ToolsTab: React.FC = () => {
const { t } = useTranslation();
const { toast } = useToast();
const { data: parityData, isLoading: parityLoading } = useQuery({
queryKey: ['proxyAdvanced', 'parityCounters'],
queryFn: () => ipc.client.proxyAdvanced.getParityCounters(),
refetchInterval: 30000,
});
const ideQueries = useQueries({
queries: [
{
queryKey: ['proxyAdvanced', 'ideConfig', 'vscode'],
queryFn: () => ipc.client.proxyAdvanced.generateIdeConfig({ ide: 'vscode' }),
},
{
queryKey: ['proxyAdvanced', 'ideConfig', 'cursor'],
queryFn: () => ipc.client.proxyAdvanced.generateIdeConfig({ ide: 'cursor' }),
},
],
});
const parity = parityData?.success ? parityData.data : undefined;
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
toast({ title: t('proxy.advanced.tools.copyConfig') });
};
const getIdeInstructions = (key: string): string => {
if (key === 'claude-code') {
return 'export ANTHROPIC_BASE_URL=http://localhost:8045/v1\nexport ANTHROPIC_API_KEY=YOUR_API_KEY';
}
const index = key === 'vscode' ? 0 : 1;
const result = ideQueries[index].data;
if (result?.success && result.data) {
const d = result.data;
return `${d.instructions}\n${d.proxySetting}: http://localhost:8045\n${d.apiKeySetting}: YOUR_API_KEY`;
}
return '';
};
const isIdeLoading = ideQueries.some((q) => q.isLoading);
return (
<div className="space-y-5">
{/* Parity Counters */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<StatCard
label={t('proxy.advanced.tools.totalRequests')}
value={parity?.totalRequests ?? 0}
icon={CheckCircle}
isLoading={parityLoading}
accent="blue"
/>
<StatCard
label={t('proxy.advanced.tools.matchedRequests')}
value={parity?.matchedRequests ?? 0}
icon={ShieldAlert}
isLoading={parityLoading}
accent="green"
/>
<StatCard
label={t('proxy.advanced.tools.parityViolations')}
value={parity?.parityViolations ?? 0}
icon={XCircle}
isLoading={parityLoading}
accent="amber"
/>
</div>
{/* IDE Quick Setup */}
<div className="overflow-hidden rounded-xl border border-white/[0.06] bg-card">
<div className="border-b border-white/[0.06] px-5 py-4 space-y-1">
<h4 className="text-[13px] font-semibold">{t('proxy.advanced.tools.ideSetup')}</h4>
<p className="text-xs text-muted-foreground">Quick configuration for popular IDEs</p>
</div>
<div className="p-5 space-y-3">
{isIdeLoading ? (
<div className="flex h-20 items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
) : (
IDE_CONFIGS.map(({ key, label, icon: Icon }) => {
const instructions = getIdeInstructions(key);
return (
<div key={key} className="overflow-hidden rounded-xl border border-white/[0.06]">
<div className="flex items-center justify-between p-3">
<div className="flex items-center gap-2">
<Icon className="h-4 w-4 text-muted-foreground" />
<span className="text-[13px] font-medium">{label}</span>
</div>
<Button
variant="ghost"
size="sm"
className="h-8 text-xs"
onClick={() => copyToClipboard(instructions)}
>
<Copy className="mr-1.5 h-3.5 w-3.5" />
{t('proxy.advanced.tools.copyConfig')}
</Button>
</div>
{instructions && (
<pre className="overflow-x-auto border-t border-white/[0.06] bg-card p-3 font-mono text-xs whitespace-pre-wrap text-foreground/90">
{instructions}
</pre>
)}
</div>
);
})
)}
</div>
</div>
</div>
);
};
@@ -0,0 +1,190 @@
import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Loader2, ArrowUp, ArrowDown } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
interface TrafficLogEntry {
timestamp: string;
direction: string;
requestId: string;
endpoint: string;
method?: string;
status?: number;
durationMs?: number;
}
interface TrafficLogTableProps {
logs: TrafficLogEntry[];
isLoading: boolean;
}
type SortKey = 'timestamp' | 'direction' | 'endpoint' | 'method' | 'status' | 'duration';
type SortDir = 'asc' | 'desc';
function SortIcon({ column, sortKey, sortDir }: { column: SortKey; sortKey: SortKey; sortDir: SortDir }) {
if (sortKey !== column) return <span className="ml-1 inline-block w-3" />;
return sortDir === 'asc' ? (
<ArrowUp className="ml-1 inline h-3 w-3" />
) : (
<ArrowDown className="ml-1 inline h-3 w-3" />
);
}
export const TrafficLogTable: React.FC<TrafficLogTableProps> = ({ logs, isLoading }) => {
const { t } = useTranslation();
const [sortKey, setSortKey] = useState<SortKey>('timestamp');
const [sortDir, setSortDir] = useState<SortDir>('desc');
const toggleSort = (key: SortKey) => {
if (sortKey === key) {
setSortDir((prev) => (prev === 'asc' ? 'desc' : 'asc'));
} else {
setSortKey(key);
setSortDir('asc');
}
};
const sortedLogs = useMemo(() => {
const dir = sortDir === 'asc' ? 1 : -1;
return [...logs].sort((a, b) => {
switch (sortKey) {
case 'timestamp':
return (new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()) * dir;
case 'direction':
return (a.direction || '').localeCompare(b.direction || '') * dir;
case 'endpoint':
return (a.endpoint || '').localeCompare(b.endpoint || '') * dir;
case 'method':
return (a.method || '').localeCompare(b.method || '') * dir;
case 'status': {
const aStatus = a.status ?? -1;
const bStatus = b.status ?? -1;
return (aStatus - bStatus) * dir;
}
case 'duration': {
const aDur = a.durationMs ?? -1;
const bDur = b.durationMs ?? -1;
return (aDur - bDur) * dir;
}
default:
return 0;
}
});
}, [logs, sortKey, sortDir]);
return (
<div className="overflow-hidden rounded-xl border border-white/[0.06] bg-card">
<div className="border-b border-white/[0.06] px-5 py-4">
<h4 className="text-[13px] font-semibold">
{t('proxy.advanced.trafficLog.title')}
</h4>
</div>
<div className="p-5">
{isLoading ? (
<div className="flex h-32 items-center justify-center">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
) : logs.length === 0 ? (
<div className="py-8 text-center text-[13px] text-muted-foreground">
{t('proxy.advanced.trafficLog.noLogs')}
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-white/[0.06] text-left text-[10px] font-medium tracking-wider uppercase text-muted-foreground">
<th
className="cursor-pointer pb-2 pr-4 font-medium select-none"
onClick={() => toggleSort('timestamp')}
>
{t('proxy.advanced.trafficLog.timestamp')}
<SortIcon column="timestamp" sortKey={sortKey} sortDir={sortDir} />
</th>
<th
className="cursor-pointer pb-2 pr-4 font-medium select-none"
onClick={() => toggleSort('direction')}
>
{t('proxy.advanced.trafficLog.direction')}
<SortIcon column="direction" sortKey={sortKey} sortDir={sortDir} />
</th>
<th
className="cursor-pointer pb-2 pr-4 font-medium select-none"
onClick={() => toggleSort('endpoint')}
>
{t('proxy.advanced.trafficLog.endpoint')}
<SortIcon column="endpoint" sortKey={sortKey} sortDir={sortDir} />
</th>
<th
className="cursor-pointer pb-2 pr-4 font-medium select-none"
onClick={() => toggleSort('method')}
>
{t('proxy.advanced.trafficLog.method')}
<SortIcon column="method" sortKey={sortKey} sortDir={sortDir} />
</th>
<th
className="cursor-pointer pb-2 pr-4 font-medium select-none"
onClick={() => toggleSort('status')}
>
{t('proxy.advanced.trafficLog.status')}
<SortIcon column="status" sortKey={sortKey} sortDir={sortDir} />
</th>
<th
className="cursor-pointer pb-2 font-medium select-none"
onClick={() => toggleSort('duration')}
>
{t('proxy.advanced.trafficLog.duration')}
<SortIcon column="duration" sortKey={sortKey} sortDir={sortDir} />
</th>
</tr>
</thead>
<tbody>
{sortedLogs.map((log, i) => (
<tr
key={`${log.requestId}-${i}`}
className="border-b border-white/[0.04] last:border-0"
>
<td className="py-2 pr-4 font-mono text-xs text-muted-foreground">
{new Date(log.timestamp).toLocaleTimeString()}
</td>
<td className="py-2 pr-4">
<Badge
variant="outline"
className={
log.direction === 'inbound'
? 'border-blue-500/30 text-blue-400'
: log.direction === 'outbound'
? 'border-emerald-500/30 text-emerald-400'
: 'border-slate-500/30 text-slate-400'
}
>
{log.direction}
</Badge>
</td>
<td className="py-2 pr-4 font-mono text-xs">{log.endpoint}</td>
<td className="py-2 pr-4 text-xs">{log.method || '—'}</td>
<td className="py-2 pr-4 text-xs">
{log.status != null ? (
<Badge
variant={log.status >= 400 ? 'destructive' : 'secondary'}
className="text-xs"
>
{log.status}
</Badge>
) : (
'—'
)}
</td>
<td className="py-2 text-xs">
{log.durationMs != null ? `${log.durationMs}ms` : '—'}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
);
};
+11 -12
View File
@@ -1,18 +1,16 @@
import * as React from 'react'; import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { cva, type VariantProps } from 'class-variance-authority';
const badgeVariants = cva( const badgeVariants = cva(
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2', 'inline-flex items-center rounded-md px-2 py-0.5 text-[11px] font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-ring/30',
{ {
variants: { variants: {
variant: { variant: {
default: 'border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80', default: 'bg-accent/15 text-accent border border-accent/20',
secondary: secondary: 'bg-secondary text-secondary-foreground border border-white/[0.06]',
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80', destructive: 'bg-destructive/15 text-red-400 border border-destructive/20',
destructive: outline: 'border border-white/[0.1] text-muted-foreground',
'border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80',
outline: 'text-foreground',
}, },
}, },
defaultVariants: { defaultVariants: {
@@ -21,10 +19,11 @@ const badgeVariants = cva(
}, },
); );
export interface BadgeProps function Badge({
extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {} className,
variant,
function Badge({ className, variant, ...props }: BadgeProps) { ...props
}: React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof badgeVariants>) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />; return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
} }
+14 -11
View File
@@ -5,24 +5,27 @@ import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const buttonVariants = cva( const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-[13px] font-medium transition-all duration-200 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-1 focus-visible:ring-offset-background",
{ {
variants: { variants: {
variant: { variant: {
default: 'bg-primary text-primary-foreground shadow-xs hover:bg-primary/90', default:
'bg-primary text-primary-foreground hover:bg-primary/90 active:scale-[0.98]',
destructive: destructive:
'bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60', 'bg-destructive/90 text-white hover:bg-destructive active:scale-[0.98] focus-visible:ring-destructive/30',
outline: outline:
'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50', 'border border-white/[0.08] bg-transparent hover:bg-white/[0.04] hover:border-white/[0.12] text-foreground',
secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80', secondary:
ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50', 'bg-secondary text-secondary-foreground hover:bg-secondary/80 active:scale-[0.98]',
link: 'text-primary underline-offset-4 hover:underline', ghost:
'hover:bg-white/[0.06] text-muted-foreground hover:text-foreground',
link: 'text-accent underline-offset-4 hover:underline',
}, },
size: { size: {
default: 'h-9 px-4 py-2 has-[>svg]:px-3', default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5', sm: 'h-8 rounded-md gap-1.5 px-3 text-xs',
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4', lg: 'h-10 rounded-lg px-6',
icon: 'size-9', icon: 'size-8 rounded-lg',
}, },
}, },
defaultVariants: { defaultVariants: {
+6 -3
View File
@@ -5,7 +5,10 @@ const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElemen
({ className, ...props }, ref) => ( ({ className, ...props }, ref) => (
<div <div
ref={ref} ref={ref}
className={cn('bg-card text-card-foreground rounded-xl border shadow', className)} className={cn(
'bg-card text-card-foreground rounded-xl border border-white/[0.06] shadow-sm transition-colors duration-200',
className,
)}
{...props} {...props}
/> />
), ),
@@ -23,7 +26,7 @@ const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HT
({ className, ...props }, ref) => ( ({ className, ...props }, ref) => (
<h3 <h3
ref={ref} ref={ref}
className={cn('leading-none font-semibold tracking-tight', className)} className={cn('text-sm font-semibold leading-none tracking-tight', className)}
{...props} {...props}
/> />
), ),
@@ -34,7 +37,7 @@ const CardDescription = React.forwardRef<
HTMLParagraphElement, HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement> React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<p ref={ref} className={cn('text-muted-foreground text-sm', className)} {...props} /> <p ref={ref} className={cn('text-muted-foreground text-[13px]', className)} {...props} />
)); ));
CardDescription.displayName = 'CardDescription'; CardDescription.displayName = 'CardDescription';
+1 -1
View File
@@ -13,7 +13,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root <CheckboxPrimitive.Root
ref={ref} ref={ref}
className={cn( className={cn(
'peer border-primary ring-offset-background focus-visible:ring-ring data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground h-4 w-4 shrink-0 rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50', 'peer h-4 w-4 shrink-0 rounded-[4px] border border-white/[0.15] bg-transparent ring-offset-background transition-colors focus-visible:ring-2 focus-visible:ring-accent/30 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-accent data-[state=checked]:bg-accent data-[state=checked]:text-background',
className, className,
)} )}
{...props} {...props}
+12 -7
View File
@@ -1,6 +1,6 @@
import * as React from 'react'; import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog'; import * as DialogPrimitive from '@radix-ui/react-dialog';
import { Cross2Icon } from '@radix-ui/react-icons'; import { X } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -19,7 +19,8 @@ const DialogOverlay = React.forwardRef<
<DialogPrimitive.Overlay <DialogPrimitive.Overlay
ref={ref} ref={ref}
className={cn( className={cn(
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80', 'fixed inset-0 z-50 bg-black/60 backdrop-blur-sm',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className, className,
)} )}
{...props} {...props}
@@ -36,14 +37,18 @@ const DialogContent = React.forwardRef<
<DialogPrimitive.Content <DialogPrimitive.Content
ref={ref} ref={ref}
className={cn( className={cn(
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg', 'fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%]',
'gap-4 rounded-xl border border-white/[0.08] bg-card p-6 shadow-2xl shadow-black/30',
'duration-200',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',
className, className,
)} )}
{...props} {...props}
> >
{children} {children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none"> <DialogPrimitive.Close className="absolute top-4 right-4 flex h-6 w-6 items-center justify-center rounded-md opacity-50 transition-all hover:bg-white/[0.06] hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring/30 disabled:pointer-events-none">
<Cross2Icon className="h-4 w-4" /> <X className="h-4 w-4" />
<span className="sr-only">Close</span> <span className="sr-only">Close</span>
</DialogPrimitive.Close> </DialogPrimitive.Close>
</DialogPrimitive.Content> </DialogPrimitive.Content>
@@ -70,7 +75,7 @@ const DialogTitle = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<DialogPrimitive.Title <DialogPrimitive.Title
ref={ref} ref={ref}
className={cn('text-lg leading-none font-semibold tracking-tight', className)} className={cn('text-base leading-none font-semibold tracking-tight', className)}
{...props} {...props}
/> />
)); ));
@@ -82,7 +87,7 @@ const DialogDescription = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<DialogPrimitive.Description <DialogPrimitive.Description
ref={ref} ref={ref}
className={cn('text-muted-foreground text-sm', className)} className={cn('text-muted-foreground text-[13px]', className)}
{...props} {...props}
/> />
)); ));
+8 -8
View File
@@ -20,7 +20,7 @@ const DropdownMenuSubTrigger = React.forwardRef<
<DropdownMenuPrimitive.SubTrigger <DropdownMenuPrimitive.SubTrigger
ref={ref} ref={ref}
className={cn( className={cn(
'focus:bg-accent data-[state=open]:bg-accent flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none', 'flex cursor-default items-center rounded-md px-2 py-1.5 text-[13px] outline-none select-none transition-colors focus:bg-white/[0.06] data-[state=open]:bg-white/[0.06]',
inset && 'pl-8', inset && 'pl-8',
className, className,
)} )}
@@ -39,7 +39,7 @@ const DropdownMenuSubContent = React.forwardRef<
<DropdownMenuPrimitive.SubContent <DropdownMenuPrimitive.SubContent
ref={ref} ref={ref}
className={cn( className={cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 min-w-[8rem] overflow-hidden rounded-md border p-1 shadow-lg', 'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 min-w-[8rem] overflow-hidden rounded-lg border border-white/[0.08] p-1 shadow-xl shadow-black/20',
className, className,
)} )}
{...props} {...props}
@@ -72,7 +72,7 @@ const DropdownMenuContent = React.forwardRef<
sideOffset={sideOffset} sideOffset={sideOffset}
collisionPadding={collisionPadding} collisionPadding={collisionPadding}
className={cn( className={cn(
'bg-popover text-popover-foreground z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-hidden overflow-y-auto rounded-md border p-1 shadow-md', 'bg-popover text-popover-foreground z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-hidden overflow-y-auto rounded-lg border border-white/[0.08] p-1 shadow-xl shadow-black/20',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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', 'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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',
className, className,
)} )}
@@ -92,7 +92,7 @@ const DropdownMenuItem = React.forwardRef<
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm transition-colors outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50', 'relative flex cursor-default items-center rounded-md px-2 py-1.5 text-[13px] transition-colors outline-none select-none focus:bg-white/[0.06] focus:text-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
inset && 'pl-8', inset && 'pl-8',
className, className,
)} )}
@@ -108,7 +108,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
<DropdownMenuPrimitive.CheckboxItem <DropdownMenuPrimitive.CheckboxItem
ref={ref} ref={ref}
className={cn( className={cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center rounded-sm py-1.5 pr-2 pl-8 text-sm transition-colors outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50', 'relative flex cursor-default items-center rounded-md py-1.5 pr-2 pl-8 text-[13px] transition-colors outline-none select-none focus:bg-white/[0.06] focus:text-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className, className,
)} )}
checked={checked} checked={checked}
@@ -131,7 +131,7 @@ const DropdownMenuRadioItem = React.forwardRef<
<DropdownMenuPrimitive.RadioItem <DropdownMenuPrimitive.RadioItem
ref={ref} ref={ref}
className={cn( className={cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center rounded-sm py-1.5 pr-2 pl-8 text-sm transition-colors outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50', 'relative flex cursor-default items-center rounded-md py-1.5 pr-2 pl-8 text-[13px] transition-colors outline-none select-none focus:bg-white/[0.06] focus:text-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className, className,
)} )}
{...props} {...props}
@@ -154,7 +154,7 @@ const DropdownMenuLabel = React.forwardRef<
>(({ className, inset, ...props }, ref) => ( >(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
ref={ref} ref={ref}
className={cn('px-2 py-1.5 text-sm font-semibold', inset && 'pl-8', className)} className={cn('px-2 py-1.5 text-xs font-medium text-muted-foreground', inset && 'pl-8', className)}
{...props} {...props}
/> />
)); ));
@@ -166,7 +166,7 @@ const DropdownMenuSeparator = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator <DropdownMenuPrimitive.Separator
ref={ref} ref={ref}
className={cn('bg-muted -mx-1 my-1 h-px', className)} className={cn('-mx-1 my-1 h-px bg-white/[0.06]', className)}
{...props} {...props}
/> />
)); ));
+7 -4
View File
@@ -1,15 +1,18 @@
import * as React from 'react'; import * as React from 'react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {} const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => { ({ className, type, ...props }, ref) => {
return ( return (
<input <input
type={type} type={type}
className={cn( className={cn(
'border-input placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50', 'flex h-9 w-full rounded-lg border border-white/[0.08] bg-muted/50 px-3 py-1 text-[13px] text-foreground shadow-none transition-colors duration-200',
'file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground',
'placeholder:text-muted-foreground',
'focus-visible:outline-none focus-visible:border-accent/50 focus-visible:ring-1 focus-visible:ring-accent/20',
'disabled:cursor-not-allowed disabled:opacity-50',
className, className,
)} )}
ref={ref} ref={ref}
+1 -1
View File
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
const labelVariants = cva( const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70', 'text-[13px] font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70',
); );
const Label = React.forwardRef< const Label = React.forwardRef<
+17 -9
View File
@@ -19,14 +19,18 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger <SelectPrimitive.Trigger
ref={ref} ref={ref}
className={cn( className={cn(
'border-input bg-background ring-offset-background placeholder:text-muted-foreground focus:ring-ring flex h-10 w-full items-center justify-between rounded-md border px-3 py-2 text-sm focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1', 'flex h-9 w-full items-center justify-between rounded-lg border border-white/[0.08] bg-muted/50 px-3 py-2 text-[13px] text-foreground transition-colors duration-200',
'placeholder:text-muted-foreground',
'focus:outline-none focus:border-accent/50 focus:ring-1 focus:ring-accent/20',
'disabled:cursor-not-allowed disabled:opacity-50',
'[&>span]:line-clamp-1',
className, className,
)} )}
{...props} {...props}
> >
{children} {children}
<SelectPrimitive.Icon asChild> <SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" /> <ChevronDown className="h-3.5 w-3.5 opacity-40" />
</SelectPrimitive.Icon> </SelectPrimitive.Icon>
</SelectPrimitive.Trigger> </SelectPrimitive.Trigger>
)); ));
@@ -41,7 +45,7 @@ const SelectScrollUpButton = React.forwardRef<
className={cn('flex cursor-default items-center justify-center py-1', className)} className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props} {...props}
> >
<ChevronUp className="h-4 w-4" /> <ChevronUp className="h-3.5 w-3.5" />
</SelectPrimitive.ScrollUpButton> </SelectPrimitive.ScrollUpButton>
)); ));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName; SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
@@ -55,7 +59,7 @@ const SelectScrollDownButton = React.forwardRef<
className={cn('flex cursor-default items-center justify-center py-1', className)} className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props} {...props}
> >
<ChevronDown className="h-4 w-4" /> <ChevronDown className="h-3.5 w-3.5" />
</SelectPrimitive.ScrollDownButton> </SelectPrimitive.ScrollDownButton>
)); ));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName; SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
@@ -68,7 +72,9 @@ const SelectContent = React.forwardRef<
<SelectPrimitive.Content <SelectPrimitive.Content
ref={ref} ref={ref}
className={cn( className={cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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 relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border shadow-md', 'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-lg border border-white/[0.08] bg-popover text-popover-foreground shadow-xl shadow-black/20',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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',
position === 'popper' && position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1', 'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className, className,
@@ -98,7 +104,7 @@ const SelectLabel = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SelectPrimitive.Label <SelectPrimitive.Label
ref={ref} ref={ref}
className={cn('py-1.5 pr-2 pl-8 text-sm font-semibold', className)} className={cn('py-1.5 pr-2 pl-8 text-xs font-medium text-muted-foreground', className)}
{...props} {...props}
/> />
)); ));
@@ -111,14 +117,16 @@ const SelectItem = React.forwardRef<
<SelectPrimitive.Item <SelectPrimitive.Item
ref={ref} ref={ref}
className={cn( className={cn(
'focus:bg-accent focus:text-accent-foreground relative flex w-full cursor-default items-center rounded-sm py-1.5 pr-2 pl-8 text-sm outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50', 'relative flex w-full cursor-default items-center rounded-md py-1.5 pr-2 pl-8 text-[13px] outline-none select-none transition-colors',
'focus:bg-white/[0.06] focus:text-foreground',
'data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className, className,
)} )}
{...props} {...props}
> >
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center"> <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator> <SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" /> <Check className="h-3.5 w-3.5 text-accent" />
</SelectPrimitive.ItemIndicator> </SelectPrimitive.ItemIndicator>
</span> </span>
@@ -133,7 +141,7 @@ const SelectSeparator = React.forwardRef<
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<SelectPrimitive.Separator <SelectPrimitive.Separator
ref={ref} ref={ref}
className={cn('bg-muted -mx-1 my-1 h-px', className)} className={cn('-mx-1 my-1 h-px bg-white/[0.06]', className)}
{...props} {...props}
/> />
)); ));
+12
View File
@@ -0,0 +1,12 @@
import { cn } from '@/lib/utils';
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn('animate-pulse rounded-lg bg-white/[0.04]', className)}
{...props}
/>
);
}
export { Skeleton };
Loaded 100 of 470 files, more files were not shown because too many files have changed in this diff. Show more