From 8363ec98f2f1a0bbe13589ac6fadc71a67acfb3f Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sat, 7 Nov 2026 22:12:04 +0400 Subject: [PATCH 01/74] refactor(accounts): drop automatic account switching Runs stay on the account the user chose: no switch on rate limits, usage thresholds, capacity or auth failures. A rate-limited task waits for its account's reset and resumes on it. Only an account that is removed or signed out is still replaced, since nothing can run on it. Removes the settings rows, the auto-switch settings and IPC, proactive swaps in the usage monitor, reactive swaps for tasks and terminals, the profile scorer, the swap notification and the unused queue API. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 +- package-lock.json | 4 +- package.json | 2 +- .../integration/claude-profile-ipc.test.ts | 2 - src/main/__tests__/best-profile-env.test.ts | 48 +- .../claude-profile-runtime-store.test.ts | 2 +- .../claude-profile-startup-heal.test.ts | 14 +- .../rate-limit-auto-recovery.test.ts | 605 ---------------- .../__tests__/rate-limit-detector.test.ts | 1 - src/main/agent/agent-manager.test.ts | 95 +-- src/main/agent/agent-manager.ts | 106 +-- src/main/agent/agent-state.ts | 13 +- src/main/agent/types.ts | 2 +- src/main/claude-code/__tests__/env.test.ts | 2 +- src/main/claude-code/env.ts | 15 +- src/main/claude-code/task-runner.ts | 4 +- src/main/claude-profile-manager.ts | 125 +--- .../__tests__/operation-registry.test.ts | 669 ------------------ .../usage-monitor-account-switch.test.ts | 8 +- src/main/claude-profile/operation-registry.ts | 473 ------------- src/main/claude-profile/profile-scorer.ts | 493 ------------- src/main/claude-profile/profile-storage.ts | 20 +- src/main/claude-profile/profile-utils.ts | 2 +- src/main/claude-profile/usage-monitor.test.ts | 137 +--- src/main/claude-profile/usage-monitor.ts | 348 +-------- src/main/index.ts | 4 +- .../ipc-handlers/agent-events-handlers.ts | 61 +- src/main/ipc-handlers/terminal-handlers.ts | 62 -- src/main/rate-limit-detector.ts | 199 +----- src/main/services/profile/profile-manager.ts | 23 - .../rate-limit-terminal-output.test.ts | 4 +- src/main/terminal/cli-integration-handler.ts | 23 +- src/main/terminal/terminal-event-handler.ts | 6 +- src/main/terminal/terminal-manager.ts | 5 +- src/main/terminal/types.ts | 3 - src/preload/api/index.ts | 9 +- src/preload/api/queue-api.ts | 172 ----- src/preload/api/terminal-api.ts | 38 +- src/renderer/App.tsx | 2 - .../components/ProactiveSwapListener.tsx | 83 --- .../components/settings/AccountSettings.tsx | 191 +---- src/renderer/lib/browser-mock.ts | 13 +- src/renderer/lib/mocks/claude-profile-mock.ts | 24 +- src/shared/constants/ipc.ts | 21 +- src/shared/i18n/locales/en/common.json | 6 - src/shared/i18n/locales/en/settings.json | 15 - src/shared/types/agent.ts | 62 -- src/shared/types/index.ts | 1 - src/shared/types/ipc.ts | 19 +- src/shared/types/terminal.ts | 16 - src/shared/types/unified-account.ts | 85 --- src/shared/utils/unified-account.ts | 111 --- 52 files changed, 176 insertions(+), 4280 deletions(-) delete mode 100644 src/main/__tests__/rate-limit-auto-recovery.test.ts delete mode 100644 src/main/claude-profile/__tests__/operation-registry.test.ts delete mode 100644 src/main/claude-profile/operation-registry.ts delete mode 100644 src/main/claude-profile/profile-scorer.ts delete mode 100644 src/preload/api/queue-api.ts delete mode 100644 src/renderer/components/ProactiveSwapListener.tsx delete mode 100644 src/shared/types/unified-account.ts delete mode 100644 src/shared/utils/unified-account.ts diff --git a/CLAUDE.md b/CLAUDE.md index 38e232b0ba..131278530d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,8 @@ reviews, requests changes (same session continues) or merges. - **Isolated Workspaces** — Git worktree isolation for every build; AI-powered semantic merge - **Authentication** — Claude subscription accounts (each a `CLAUDE_CONFIG_DIR`) or API profiles with any Anthropic-compatible endpoint -- **Multi-Account Swapping** — When one Claude account hits a rate limit, switch to an available one automatically +- **Multiple accounts** — Each project runs on the Claude account chosen for it; work never moves to another account by + itself: a rate-limited account's tasks wait for its reset and resume on it - **Cross-Platform** — Windows, macOS, and Linux with in-app updates (Settings > Updates) ## Critical Rules @@ -208,8 +209,9 @@ workbench/ task list (TaskCreate/TaskUpdate, enabled with `CLAUDE_CODE_ENABLE_TODO_TOOLS=1`) is mirrored as the task's subtasks. - **One-shot calls** (`run-text.ts`, `runClaudeText`) — `claude -p --output-format json --no-session-persistence`, tools off unless asked, optional `--json-schema`. -- **Process + env** (`process.ts`, `env.ts`) — async spawn, stream-json parsing (`stream-types.ts`), best available - Claude profile (rate-limit aware) or the active API profile. +- **Process + env** (`process.ts`, `env.ts`) — async spawn, stream-json parsing (`stream-types.ts`), the run's Claude + profile (the project's account, else the account in use; never another one because of limits, only instead of an + account that is removed or signed out) or the active API profile. - **Session costs** (`project-sessions.ts`, `session-spending.ts`, `session-pricing.ts`) — a project's other Claude Code sessions (agent windows, Claude chat, `claude` in a terminal), found by the directory they ran in, and what they cost per day from their transcripts (Metrics, `src/main/project-metrics.ts`). diff --git a/package-lock.json b/package-lock.json index 7018b6100e..617807417b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.5.65", + "version": "1.6.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.5.65", + "version": "1.6.1", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index c639c3caa5..88e4ac3af6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.5.65", + "version": "1.6.1", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/__tests__/integration/claude-profile-ipc.test.ts b/src/__tests__/integration/claude-profile-ipc.test.ts index f202af8811..c65b2ca574 100644 --- a/src/__tests__/integration/claude-profile-ipc.test.ts +++ b/src/__tests__/integration/claude-profile-ipc.test.ts @@ -51,8 +51,6 @@ const mockProfileManager = { setActiveProfile: vi.fn(() => true), deleteProfile: vi.fn(() => true), renameProfile: vi.fn(() => true), - getAutoSwitchSettings: vi.fn(), - updateAutoSwitchSettings: vi.fn(() => true), isInitialized: vi.fn(() => true), findAbandonedProfileByName: vi.fn((_name: string): ClaudeProfile | undefined => undefined), findProfileByName: vi.fn((_name: string): ClaudeProfile | undefined => undefined) diff --git a/src/main/__tests__/best-profile-env.test.ts b/src/main/__tests__/best-profile-env.test.ts index 8a59f7f4ef..69d779d475 100644 --- a/src/main/__tests__/best-profile-env.test.ts +++ b/src/main/__tests__/best-profile-env.test.ts @@ -1,6 +1,6 @@ /** - * Automatic account switching never moves runs (or the active account) to an account without - * credentials, and moves away from one. + * Runs stay on the account in use, also when it is rate limited; only an account without + * credentials (which can't run at all) is replaced by a signed-in one. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; import type { ClaudeProfile } from '../../shared/types'; @@ -10,46 +10,43 @@ type Profile = Pick & { signedIn: bo const state = vi.hoisted(() => ({ profiles: [] as Array<{ id: string; name: string; configDir?: string; signedIn: boolean; limited?: boolean }>, activeId: '', - best: null as string | null, })); const manager = vi.hoisted(() => ({ getActiveProfile: vi.fn(() => state.profiles.find(p => p.id === state.activeId)), getProfile: vi.fn((id: string) => state.profiles.find(p => p.id === id)), + getSettings: vi.fn(() => ({ profiles: state.profiles, activeProfileId: state.activeId })), hasValidAuth: vi.fn((id: string) => !!state.profiles.find(p => p.id === id)?.signedIn), isProfileRateLimited: vi.fn((id: string) => ({ limited: !!state.profiles.find(p => p.id === id)?.limited })), - getBestAvailableProfile: vi.fn(() => state.profiles.find(p => p.id === state.best) ?? null), setActiveProfile: vi.fn((id: string) => { state.activeId = id; return true; }), getProfileEnv: vi.fn((id: string) => ({ CLAUDE_CONFIG_DIR: `/profiles/${id}` })), getActiveProfileEnv: vi.fn(() => ({ CLAUDE_CONFIG_DIR: `/profiles/${state.activeId}` })), })); vi.mock('../claude-profile-manager', () => ({ getClaudeProfileManager: () => manager })); -vi.mock('../claude-profile/usage-monitor', () => ({ - getUsageMonitor: () => ({ getAllProfilesUsage: vi.fn(async () => null), emit: vi.fn() }), -})); +vi.mock('../app-logger', () => ({ appLog: { warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() } })); -import { getBestAvailableProfileEnv, getUsableProfileEnv } from '../rate-limit-detector'; +import { getRunnableProfileEnv, getUsableProfileEnv } from '../rate-limit-detector'; -function setProfiles(profiles: Profile[], activeId: string, best: string | null): void { +function setProfiles(profiles: Profile[], activeId: string): void { state.profiles = profiles; state.activeId = activeId; - state.best = best; } -describe('getBestAvailableProfileEnv', () => { +describe('getRunnableProfileEnv', () => { beforeEach(() => vi.clearAllMocks()); - it('stays on a rate-limited account rather than switching to one without credentials', () => { + it('stays on a rate-limited account even when another signed-in account is free', () => { setProfiles([ { id: 'primary', name: 'Primary', configDir: '/profiles/primary', signedIn: true, limited: true }, - { id: 'primary-1', name: 'Primary', configDir: '/profiles/primary-1', signedIn: false }, - ], 'primary', 'primary-1'); + { id: 'second', name: 'Second', configDir: '/profiles/second', signedIn: true }, + ], 'primary'); - const result = getBestAvailableProfileEnv(); + const result = getRunnableProfileEnv(); expect(result.profileId).toBe('primary'); - expect(result.wasSwapped).toBe(false); + expect(result.wasSignedOut).toBe(false); + expect(result.env.CLAUDE_CONFIG_DIR).toBe('/profiles/primary'); expect(manager.setActiveProfile).not.toHaveBeenCalled(); }); @@ -57,14 +54,25 @@ describe('getBestAvailableProfileEnv', () => { setProfiles([ { id: 'primary', name: 'Primary', configDir: '/profiles/primary', signedIn: true }, { id: 'primary-1', name: 'Primary', configDir: '/profiles/primary-1', signedIn: false }, - ], 'primary-1', 'primary'); + ], 'primary-1'); - const result = getBestAvailableProfileEnv(); + const result = getRunnableProfileEnv(); - expect(result).toMatchObject({ profileId: 'primary', wasSwapped: true, swapReason: 'not_authenticated' }); + expect(result).toMatchObject({ profileId: 'primary', wasSignedOut: true }); expect(result.env.CLAUDE_CONFIG_DIR).toBe('/profiles/primary'); expect(manager.setActiveProfile).toHaveBeenCalledWith('primary'); }); + + it('stays on an account without credentials when no other account is signed in', () => { + setProfiles([ + { id: 'primary', name: 'Primary', configDir: '/profiles/primary', signedIn: false }, + ], 'primary'); + + const result = getRunnableProfileEnv(); + + expect(result.profileId).toBe('primary'); + expect(manager.setActiveProfile).not.toHaveBeenCalled(); + }); }); describe('getUsableProfileEnv', () => { @@ -72,7 +80,7 @@ describe('getUsableProfileEnv', () => { setProfiles([ { id: 'primary', name: 'Primary', configDir: '/profiles/primary', signedIn: true }, { id: 'primary-1', name: 'Primary', configDir: '/profiles/primary-1', signedIn: false }, - ], 'primary', null); + ], 'primary'); expect(getUsableProfileEnv('primary')).toEqual({ CLAUDE_CONFIG_DIR: '/profiles/primary' }); expect(getUsableProfileEnv('primary-1')).toBeNull(); diff --git a/src/main/__tests__/claude-profile-runtime-store.test.ts b/src/main/__tests__/claude-profile-runtime-store.test.ts index 3a780b32fb..4a419035f6 100644 --- a/src/main/__tests__/claude-profile-runtime-store.test.ts +++ b/src/main/__tests__/claude-profile-runtime-store.test.ts @@ -100,7 +100,7 @@ describe('profile store per runtime', () => { const manager = new ClaudeProfileManager(); const initializing = manager.initialize(); - manager.updateAutoSwitchSettings({ enabled: true }); + manager.renameProfile('primary', 'Renamed'); expect(existsSync(store('claude-profiles.json'))).toBe(false); finishDetection(); diff --git a/src/main/__tests__/claude-profile-startup-heal.test.ts b/src/main/__tests__/claude-profile-startup-heal.test.ts index 87bb4e354c..e87b3b7554 100644 --- a/src/main/__tests__/claude-profile-startup-heal.test.ts +++ b/src/main/__tests__/claude-profile-startup-heal.test.ts @@ -40,8 +40,6 @@ vi.mock('../claude-profile/claude-code-detection', () => ({ })); import { ClaudeProfileManager } from '../claude-profile-manager'; -import { getBestAvailableProfile } from '../claude-profile/profile-scorer'; -import { DEFAULT_AUTO_SWITCH_SETTINGS } from '../claude-profile/profile-storage'; import type { ClaudeProfile } from '../../shared/types'; const ESC = '\u001b'; @@ -106,7 +104,8 @@ describe('ClaudeProfileManager startup repair', () => { }, ], activeProfileId: 'primary-1', - autoSwitch: DEFAULT_AUTO_SWITCH_SETTINGS, + // Saved before automatic account switching was removed: still loads, and is dropped + autoSwitch: { enabled: true, proactiveSwapEnabled: true, sessionThreshold: 95, weeklyThreshold: 99 }, })); }); @@ -135,6 +134,7 @@ describe('ClaudeProfileManager startup repair', () => { expect(stored.profiles.map((p: ClaudeProfile) => p.id)).toEqual(['primary']); expect(stored.activeProfileId).toBe('primary'); expect(stored.profiles[0].rateLimitEvents).toEqual([]); + expect(stored.autoSwitch).toBeUndefined(); expect(existsSync(duplicateDir)).toBe(true); }); @@ -151,14 +151,6 @@ describe('ClaudeProfileManager startup repair', () => { expect(manager.getSettings().activeProfileId).toBe('primary'); expect(manager.findAbandonedProfileByName('work')?.id).toBe('primary-1'); }); - - it('never picks an account without credentials when switching away from a rate-limited one', () => { - const profiles: ClaudeProfile[] = [ - { id: 'primary', name: 'Primary', configDir: primaryDir, isDefault: true, createdAt: new Date() }, - { id: 'primary-1', name: 'Primary', configDir: duplicateDir, isDefault: false, createdAt: new Date() }, - ]; - expect(getBestAvailableProfile(profiles, DEFAULT_AUTO_SWITCH_SETTINGS, 'primary')).toBeNull(); - }); }); describe('ClaudeProfileManager rate limit recording', () => { diff --git a/src/main/__tests__/rate-limit-auto-recovery.test.ts b/src/main/__tests__/rate-limit-auto-recovery.test.ts deleted file mode 100644 index 32a0737504..0000000000 --- a/src/main/__tests__/rate-limit-auto-recovery.test.ts +++ /dev/null @@ -1,605 +0,0 @@ -/** - * Integration tests for Rate Limit Auto-Recovery System - * Tests the complete flow: rate limit detection → account swap → task restart - */ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { EventEmitter } from 'events'; - -// Mock data -const mockProfiles = { - mai: { - id: 'profile-mai', - name: 'MAI', - email: 'mai@example.com', - isDefault: true, - oauthToken: 'encrypted-token-mai', - createdAt: new Date(), - rateLimitEvents: [] - }, - mu: { - id: 'profile-mu', - name: 'MU', - email: 'mu@example.com', - isDefault: false, - oauthToken: 'encrypted-token-mu', - createdAt: new Date(), - rateLimitEvents: [] - } -}; - -const mockAutoSwitchSettings = { - enabled: true, - proactiveSwapEnabled: true, - sessionThreshold: 95, - weeklyThreshold: 99, - autoSwitchOnRateLimit: true, - usageCheckInterval: 30000 -}; - -// Create mock profile manager -function createMockProfileManager(options: { - activeProfileId?: string; - profiles?: typeof mockProfiles; - autoSwitchSettings?: typeof mockAutoSwitchSettings; - bestAvailableProfile?: typeof mockProfiles.mai | null; -} = {}) { - const activeId = options.activeProfileId || 'profile-mai'; - const profiles = options.profiles || mockProfiles; - const settings = options.autoSwitchSettings || mockAutoSwitchSettings; - const bestProfile = options.bestAvailableProfile !== undefined - ? options.bestAvailableProfile - : profiles.mu; - - return { - getActiveProfile: vi.fn(() => profiles[activeId === 'profile-mai' ? 'mai' : 'mu']), - getProfile: vi.fn((id: string) => { - if (id === 'profile-mai') return profiles.mai; - if (id === 'profile-mu') return profiles.mu; - return null; - }), - getBestAvailableProfile: vi.fn((_excludeProfileId?: string) => bestProfile), - setActiveProfile: vi.fn(), - recordRateLimitEvent: vi.fn(), - getAutoSwitchSettings: vi.fn(() => settings), - getProfileToken: vi.fn(() => 'decrypted-token'), - getActiveProfileToken: vi.fn(() => 'decrypted-token') - }; -} - -describe('Rate Limit Auto-Recovery Integration', () => { - let mockProfileManager: ReturnType; - - beforeEach(() => { - vi.resetModules(); - mockProfileManager = createMockProfileManager(); - }); - - afterEach(() => { - vi.clearAllMocks(); - }); - - describe('Rate Limit Detection Patterns', () => { - beforeEach(() => { - vi.doMock('../claude-profile-manager', () => ({ - getClaudeProfileManager: vi.fn(() => mockProfileManager) - })); - }); - - it('should detect standard Claude rate limit message', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - const output = 'Limit reached · resets Dec 17 at 6am (Europe/Oslo)'; - const result = detectRateLimit(output); - - expect(result.isRateLimited).toBe(true); - expect(result.resetTime).toBe('Dec 17 at 6am (Europe/Oslo)'); - expect(result.limitType).toBe('weekly'); - }); - - it('should detect session limit (time only reset)', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - const output = 'Limit reached • resets 11:59pm'; - const result = detectRateLimit(output); - - expect(result.isRateLimited).toBe(true); - expect(result.limitType).toBe('session'); - }); - - it('should detect rate limit in multiline output', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - const output = `Processing task... -Some output here -Limit reached · resets Dec 20 at 3pm (America/New_York) -Stack trace follows`; - - const result = detectRateLimit(output); - - expect(result.isRateLimited).toBe(true); - expect(result.resetTime).toBe('Dec 20 at 3pm (America/New_York)'); - }); - - it('should suggest alternative profile when rate limited', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - const output = 'Limit reached · resets Dec 17 at 6am'; - const result = detectRateLimit(output, 'profile-mai'); - - expect(result.isRateLimited).toBe(true); - expect(result.suggestedProfile).toBeDefined(); - expect(result.suggestedProfile?.id).toBe('profile-mu'); - }); - - it('should record rate limit event in profile manager', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - detectRateLimit('Limit reached · resets Dec 17 at 6am', 'profile-mai'); - - expect(mockProfileManager.recordRateLimitEvent).toHaveBeenCalledWith( - 'profile-mai', - 'Dec 17 at 6am' - ); - }); - }); - - describe('Auto-Switch Settings Verification', () => { - it('should respect enabled flag', async () => { - const disabledManager = createMockProfileManager({ - autoSwitchSettings: { ...mockAutoSwitchSettings, enabled: false } - }); - - vi.doMock('../claude-profile-manager', () => ({ - getClaudeProfileManager: vi.fn(() => disabledManager) - })); - - const settings = disabledManager.getAutoSwitchSettings(); - - expect(settings.enabled).toBe(false); - // When enabled is false, auto-swap should NOT happen even if autoSwitchOnRateLimit is true - }); - - it('should respect autoSwitchOnRateLimit flag', async () => { - const manualManager = createMockProfileManager({ - autoSwitchSettings: { ...mockAutoSwitchSettings, autoSwitchOnRateLimit: false } - }); - - const settings = manualManager.getAutoSwitchSettings(); - - expect(settings.enabled).toBe(true); - expect(settings.autoSwitchOnRateLimit).toBe(false); - // When autoSwitchOnRateLimit is false, should show manual modal instead - }); - - it('should have both enabled and autoSwitchOnRateLimit for auto-recovery', () => { - const settings = mockProfileManager.getAutoSwitchSettings(); - - // Both must be true for automatic recovery - const shouldAutoRecover = settings.enabled && settings.autoSwitchOnRateLimit; - expect(shouldAutoRecover).toBe(true); - }); - }); - - describe('Profile Scoring and Selection', () => { - it('should return alternative profile when one is available', () => { - const bestProfile = mockProfileManager.getBestAvailableProfile('profile-mai'); - - expect(bestProfile).toBeDefined(); - expect(bestProfile?.id).toBe('profile-mu'); - }); - - it('should return null when no alternative profile is available', () => { - const noAlternativeManager = createMockProfileManager({ - bestAvailableProfile: null - }); - - const bestProfile = noAlternativeManager.getBestAvailableProfile('profile-mai'); - - expect(bestProfile).toBeNull(); - }); - - it('should not return the same profile that hit the limit', () => { - const bestProfile = mockProfileManager.getBestAvailableProfile('profile-mai'); - - // Best profile should be different from the one that hit the limit - expect(bestProfile?.id).not.toBe('profile-mai'); - }); - }); - - describe('Auto-Recovery Flow Simulation', () => { - /** - * Simulates the flow in agent-process.ts lines 274-327 - */ - function simulateRateLimitRecovery( - output: string, - exitCode: number, - profileManager: ReturnType - ): { - rateLimitDetected: boolean; - autoSwapped: boolean; - taskRestarted: boolean; - modalShown: boolean; - swappedToProfile?: { id: string; name: string }; - } { - const result = { - rateLimitDetected: false, - autoSwapped: false, - taskRestarted: false, - modalShown: false, - swappedToProfile: undefined as { id: string; name: string } | undefined - }; - - // Only check rate limit if process failed - if (exitCode !== 0) { - // Simulate detectRateLimit - const rateLimitPattern = /Limit reached\s*[·•]\s*resets\s+(.+?)(?:\s*$|\n)/im; - const rateIndicators = [/rate\s*limit/i, /usage\s*limit/i, /limit\s*reached/i]; - - const isRateLimited = rateLimitPattern.test(output) || - rateIndicators.some(p => p.test(output)); - - if (isRateLimited) { - result.rateLimitDetected = true; - - const settings = profileManager.getAutoSwitchSettings(); - - if (settings.enabled && settings.autoSwitchOnRateLimit) { - const bestProfile = profileManager.getBestAvailableProfile('current-profile'); - - if (bestProfile) { - // Auto-swap - profileManager.setActiveProfile(bestProfile.id); - result.autoSwapped = true; - result.swappedToProfile = { id: bestProfile.id, name: bestProfile.name }; - result.taskRestarted = true; - result.modalShown = true; // Notification modal - } else { - // No alternative - show manual modal - result.modalShown = true; - } - } else { - // Auto-switch disabled - show manual modal - result.modalShown = true; - } - } - } - - return result; - } - - it('should auto-swap and restart when all conditions met', () => { - const result = simulateRateLimitRecovery( - 'Limit reached · resets Dec 17 at 6am', - 1, // non-zero exit - mockProfileManager - ); - - expect(result.rateLimitDetected).toBe(true); - expect(result.autoSwapped).toBe(true); - expect(result.taskRestarted).toBe(true); - expect(result.modalShown).toBe(true); - expect(result.swappedToProfile?.id).toBe('profile-mu'); - }); - - it('should NOT auto-swap when exit code is 0', () => { - const result = simulateRateLimitRecovery( - 'Limit reached · resets Dec 17 at 6am', - 0, // success exit - mockProfileManager - ); - - expect(result.rateLimitDetected).toBe(false); - expect(result.autoSwapped).toBe(false); - expect(result.taskRestarted).toBe(false); - }); - - it('should NOT auto-swap when enabled is false', () => { - const disabledManager = createMockProfileManager({ - autoSwitchSettings: { ...mockAutoSwitchSettings, enabled: false } - }); - - const result = simulateRateLimitRecovery( - 'Limit reached · resets Dec 17 at 6am', - 1, - disabledManager - ); - - expect(result.rateLimitDetected).toBe(true); - expect(result.autoSwapped).toBe(false); - expect(result.modalShown).toBe(true); // Manual modal - }); - - it('should NOT auto-swap when autoSwitchOnRateLimit is false', () => { - const manualManager = createMockProfileManager({ - autoSwitchSettings: { ...mockAutoSwitchSettings, autoSwitchOnRateLimit: false } - }); - - const result = simulateRateLimitRecovery( - 'Limit reached · resets Dec 17 at 6am', - 1, - manualManager - ); - - expect(result.rateLimitDetected).toBe(true); - expect(result.autoSwapped).toBe(false); - expect(result.modalShown).toBe(true); // Manual modal - }); - - it('should show manual modal when no alternative profile available', () => { - const noAlternativeManager = createMockProfileManager({ - bestAvailableProfile: null - }); - - const result = simulateRateLimitRecovery( - 'Limit reached · resets Dec 17 at 6am', - 1, - noAlternativeManager - ); - - expect(result.rateLimitDetected).toBe(true); - expect(result.autoSwapped).toBe(false); - expect(result.taskRestarted).toBe(false); - expect(result.modalShown).toBe(true); // Manual modal because no alternative - }); - - it('should NOT detect rate limit for normal errors', () => { - const result = simulateRateLimitRecovery( - 'Error: File not found', - 1, - mockProfileManager - ); - - expect(result.rateLimitDetected).toBe(false); - expect(result.autoSwapped).toBe(false); - expect(result.modalShown).toBe(false); - }); - }); - - describe('Task Restart Context Preservation', () => { - it('should preserve task context for restart', () => { - // Simulate task execution context - const taskContext = { - taskId: 'task-123', - projectPath: '/path/to/project', - specId: 'spec-001', - options: { qa: false }, - swapCount: 0, - isSpecCreation: false - }; - - // After swap, swapCount should increment - taskContext.swapCount++; - - expect(taskContext.swapCount).toBe(1); - }); - - it('should limit swap retries to prevent infinite loops', () => { - const MAX_SWAPS = 2; - let swapCount = 0; - - // Simulate multiple rate limits - for (let i = 0; i < 5; i++) { - if (swapCount >= MAX_SWAPS) { - break; // Should stop after 2 swaps - } - swapCount++; - } - - expect(swapCount).toBe(MAX_SWAPS); - }); - }); - - describe('Event Emission Verification', () => { - it('should emit sdk-rate-limit event on rate limit', () => { - const emitter = new EventEmitter(); - const sdkRateLimitHandler = vi.fn(); - - emitter.on('sdk-rate-limit', sdkRateLimitHandler); - - // Simulate rate limit detected with auto-swap - const rateLimitInfo = { - source: 'task' as const, - taskId: 'task-123', - resetTime: 'Dec 17 at 6am', - limitType: 'weekly' as const, - profileId: 'profile-mai', - profileName: 'MAI', - wasAutoSwapped: true, - swappedToProfile: { id: 'profile-mu', name: 'MU' }, - swapReason: 'reactive' as const, - detectedAt: new Date() - }; - - emitter.emit('sdk-rate-limit', rateLimitInfo); - - expect(sdkRateLimitHandler).toHaveBeenCalledWith(rateLimitInfo); - expect(sdkRateLimitHandler).toHaveBeenCalledTimes(1); - }); - - it('should emit auto-swap-restart-task event for task restart', () => { - const emitter = new EventEmitter(); - const restartHandler = vi.fn(); - - emitter.on('auto-swap-restart-task', restartHandler); - - emitter.emit('auto-swap-restart-task', 'task-123', 'profile-mu'); - - expect(restartHandler).toHaveBeenCalledWith('task-123', 'profile-mu'); - }); - - it('should handle event chain: rate-limit → swap → restart', () => { - const emitter = new EventEmitter(); - const events: string[] = []; - - emitter.on('sdk-rate-limit', () => events.push('sdk-rate-limit')); - emitter.on('auto-swap-restart-task', () => events.push('auto-swap-restart-task')); - - // Simulate the flow - emitter.emit('sdk-rate-limit', { /* info */ }); - emitter.emit('auto-swap-restart-task', 'task-123', 'profile-mu'); - - expect(events).toEqual(['sdk-rate-limit', 'auto-swap-restart-task']); - }); - }); -}); - -describe('Rate Limit Edge Cases', () => { - beforeEach(() => { - vi.resetModules(); - }); - - afterEach(() => { - vi.clearAllMocks(); - }); - - describe('Pattern Matching Edge Cases', () => { - const mockManager = createMockProfileManager(); - - beforeEach(() => { - vi.doMock('../claude-profile-manager', () => ({ - getClaudeProfileManager: vi.fn(() => mockManager) - })); - }); - - it('should handle different bullet characters', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - // Middle dot (·) - expect(detectRateLimit('Limit reached · resets 5pm').isRateLimited).toBe(true); - - // Bullet (•) - expect(detectRateLimit('Limit reached • resets 5pm').isRateLimited).toBe(true); - }); - - it('should handle different timezone formats', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - const timezones = [ - 'Dec 17 at 6am (Europe/Oslo)', - 'Dec 17 at 6am (America/New_York)', - 'Dec 17 at 6am (Asia/Tokyo)', - 'Dec 17 at 6am (UTC)', - 'Dec 17 at 6am' // No timezone - ]; - - for (const tz of timezones) { - const result = detectRateLimit(`Limit reached · resets ${tz}`); - expect(result.isRateLimited).toBe(true); - } - }); - - it('should handle 12-hour and 24-hour time formats', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - expect(detectRateLimit('Limit reached · resets 11:59pm').isRateLimited).toBe(true); - expect(detectRateLimit('Limit reached · resets 6am').isRateLimited).toBe(true); - expect(detectRateLimit('Limit reached · resets 18:00').isRateLimited).toBe(true); - }); - - it('should NOT false-positive on similar messages', async () => { - const { detectRateLimit } = await import('../rate-limit-detector'); - - // These should NOT trigger rate limit detection - const falsePositives = [ - 'Limit your requests to avoid issues', // Contains 'limit' but not rate limit - 'The speed limit is 60mph', // Unrelated limit - 'Character limit reached for input field' // Different kind of limit - ]; - - for (const msg of falsePositives) { - detectRateLimit(msg); - // Note: Some may still match secondary indicators - that's intentional - // The primary pattern should NOT match these - const primaryPattern = /Limit reached\s*[·•]\s*resets/i; - expect(primaryPattern.test(msg)).toBe(false); - } - }); - }); - - describe('Both Profiles Rate Limited', () => { - it('should return null when all profiles are rate limited', () => { - const bothLimitedManager = createMockProfileManager({ - bestAvailableProfile: null - }); - - const best = bothLimitedManager.getBestAvailableProfile('profile-mai'); - expect(best).toBeNull(); - }); - - it('should show manual modal when no profiles available', () => { - // User must either wait or add a new account - const bothLimitedManager = createMockProfileManager({ - bestAvailableProfile: null - }); - - const settings = bothLimitedManager.getAutoSwitchSettings(); - const bestProfile = bothLimitedManager.getBestAvailableProfile('profile-mai'); - - // Even with auto-switch enabled, should show modal since no alternative - const shouldShowManualModal = settings.enabled && settings.autoSwitchOnRateLimit && !bestProfile; - expect(shouldShowManualModal).toBe(true); - }); - }); - - describe('Rapid Rate Limit Succession', () => { - it('should enforce max swap count', () => { - const MAX_SWAP_COUNT = 2; - const context = { swapCount: 0 }; - - // First swap - context.swapCount++; - expect(context.swapCount < MAX_SWAP_COUNT).toBe(true); - - // Second swap - context.swapCount++; - expect(context.swapCount >= MAX_SWAP_COUNT).toBe(true); - - // Third swap should be blocked - const shouldAllowSwap = context.swapCount < MAX_SWAP_COUNT; - expect(shouldAllowSwap).toBe(false); - }); - }); -}); - -describe('Modal Behavior with Reactive Recovery', () => { - describe('Modal Content Variations', () => { - it('should show notification-style modal when auto-swapped', () => { - const rateLimitInfo = { - source: 'task' as const, - wasAutoSwapped: true, - swappedToProfile: { id: 'profile-mu', name: 'MU' }, - swapReason: 'reactive' as const - }; - - // When wasAutoSwapped is true, modal should be informational - expect(rateLimitInfo.wasAutoSwapped).toBe(true); - expect(rateLimitInfo.swapReason).toBe('reactive'); - }); - - it('should show action-required modal when NOT auto-swapped', () => { - const rateLimitInfo = { - source: 'task' as const, - wasAutoSwapped: false, - suggestedProfile: { id: 'profile-mu', name: 'MU' } - }; - - // When wasAutoSwapped is false, user needs to take action - expect(rateLimitInfo.wasAutoSwapped).toBe(false); - }); - - it('should distinguish proactive vs reactive swaps', () => { - const proactiveSwap = { - wasAutoSwapped: true, - swapReason: 'proactive' as const // Before limit hit - }; - - const reactiveSwap = { - wasAutoSwapped: true, - swapReason: 'reactive' as const // After limit hit - }; - - expect(proactiveSwap.swapReason).toBe('proactive'); - expect(reactiveSwap.swapReason).toBe('reactive'); - }); - }); -}); diff --git a/src/main/__tests__/rate-limit-detector.test.ts b/src/main/__tests__/rate-limit-detector.test.ts index 905c8382f8..7c78a1f2f8 100644 --- a/src/main/__tests__/rate-limit-detector.test.ts +++ b/src/main/__tests__/rate-limit-detector.test.ts @@ -17,7 +17,6 @@ vi.mock('../claude-profile-manager', () => ({ name: 'Test Profile', isDefault: true })), - getBestAvailableProfile: vi.fn(() => null), recordRateLimitEvent: vi.fn() })) })); diff --git a/src/main/agent/agent-manager.test.ts b/src/main/agent/agent-manager.test.ts index 90e1da648c..c749bf689a 100644 --- a/src/main/agent/agent-manager.test.ts +++ b/src/main/agent/agent-manager.test.ts @@ -106,11 +106,6 @@ vi.mock('../claude-profile-manager', () => ({ getClaudeProfileManager: () => profileManager, })); -const registry = { registerOperation: vi.fn(), unregisterOperation: vi.fn() }; -vi.mock('../claude-profile/operation-registry', () => ({ - getOperationRegistry: () => registry, -})); - vi.mock('../services/profile', () => ({ getAPIProfileEnv: vi.fn(async () => ({})), })); @@ -253,9 +248,7 @@ describe('AgentManager', () => { expect(run.config.settings.fixedModel).toBe('opus'); expect(run.config.mode).toBe('start'); expect(manager.isRunning('001-add-login')).toBe(true); - expect(registry.registerOperation).toHaveBeenCalledWith( - 'task:project-1:001-add-login', 'task-execution', 'profile-a', 'Account A', expect.any(Function), expect.anything() - ); + expect(manager.getTaskProfileAssignment('001-add-login', 'project-1')).toMatchObject({ profileId: 'profile-a' }); }); it('applies a pending local merge on start only to a task without a pull request', async () => { @@ -552,33 +545,7 @@ describe('AgentManager', () => { expect(manager.isRunning('001-add-login', 'project-2')).toBe(false); }); - it('restarts the run of the project it is told, not a same-named task in another', async () => { - const other = { ...project, id: 'project-2', path: '/other' } as unknown as Project; - - await manager.startTask('001-add-login', { project, task: makeTask(), mode: 'start' }); - const first = await nextRun(1); - await manager.startTask('001-add-login', { - project: other, - task: makeTask({ projectId: 'project-2' }), - mode: 'start', - }); - const second = await nextRun(2); - - expect(manager.restartTask('001-add-login', 'profile-b', 'project-2')).toBe(true); - - expect(second.stop).toHaveBeenCalled(); - expect(first.stop).not.toHaveBeenCalled(); - const restarted = await nextRun(3); - expect(restarted.config.projectId).toBe('project-2'); - expect(restarted.config.profileId).toBe('profile-b'); - }); - - /** - * The operation registry keys its operations by the id it is handed, so a bare task id would - * let the second project's run replace the first's registration - and the first run to end - * would then unregister whichever entry was left behind. - */ - it('registers the same task id in two projects as two operations', async () => { + it('tracks the same task id in two projects as two runs on the account', async () => { const other = { ...project, id: 'project-2', path: '/other' } as unknown as Project; await manager.startTask('001-add-login', { project, task: makeTask(), mode: 'start' }); @@ -590,18 +557,14 @@ describe('AgentManager', () => { }); await nextRun(2); - const ids = registry.registerOperation.mock.calls.map((call) => call[0]); - expect(ids).toEqual(['task:project-1:001-add-login', 'task:project-2:001-add-login']); - // Both runs are on the same account, and the queue sees two of them rather than one expect(manager.getRunningTasksByProfile()).toEqual({ byProfile: { 'profile-a': ['001-add-login', '001-add-login'] }, totalRunning: 2, }); - // And stopping one takes only its own registration with it + // And stopping one takes only its own run with it manager.killTask('001-add-login', 'project-2'); - expect(registry.unregisterOperation.mock.calls).toEqual([['task:project-2:001-add-login']]); expect(manager.getRunningTasksByProfile().totalRunning).toBe(1); }); @@ -635,35 +598,6 @@ describe('AgentManager', () => { expect(first.stop).toHaveBeenCalled(); }); - it('restarts the right project\'s run when the swap comes through the operation registry', async () => { - // A rate limit swaps the run through the callback registered with the operation registry, and - // that callback has to name its project: with the same 001 running in two projects, the task - // id alone would let the swap stop and restart the other project's run - const other = { ...project, id: 'project-2', path: '/other' } as unknown as Project; - - await manager.startTask('001-add-login', { project, task: makeTask(), mode: 'start' }); - const first = await nextRun(1); - await manager.startTask('001-add-login', { - project: other, - task: makeTask({ projectId: 'project-2' }), - mode: 'start', - }); - const second = await nextRun(2); - - // The registration of the second project's run, told apart by the project path it carries - const registration = registry.registerOperation.mock.calls.find( - (call) => (call[5] as { metadata?: { projectPath?: string } } | undefined)?.metadata?.projectPath === '/other' - ); - const swap = registration?.[4] as (profileId: string) => boolean; - expect(swap('profile-b')).toBe(true); - - expect(second.stop).toHaveBeenCalled(); - expect(first.stop).not.toHaveBeenCalled(); - const restarted = await nextRun(3); - expect(restarted.config.projectId).toBe('project-2'); - expect(restarted.config.profileId).toBe('profile-b'); - }); - it('records a rate limit on the profile the run used and tags the event with it', async () => { const taskEvents: Array> = []; manager.on('task-event', (_taskId: string, event: Record) => taskEvents.push(event)); @@ -680,29 +614,6 @@ describe('AgentManager', () => { expect(taskEvents[0]).toMatchObject({ type: 'RATE_LIMIT_HOLD', profileId: 'profile-a', phase: 'coding' }); }); - it('restarts a run on another profile once the previous run settled', async () => { - await manager.startTask('001-add-login', { project, task: makeTask(), mode: 'start' }); - const first = await nextRun(1); - - expect(manager.restartTask('001-add-login', 'profile-b')).toBe(true); - expect(first.stop).toHaveBeenCalled(); - expect(profileManager.setActiveProfile).toHaveBeenCalledWith('profile-b'); - - const second = await nextRun(2); - expect(second.config.profileId).toBe('profile-b'); - expect(manager.isRunning('001-add-login')).toBe(true); - }); - - it('gives up restarting after repeated swaps', async () => { - await manager.startTask('001-add-login', { project, task: makeTask(), mode: 'start' }); - await nextRun(1); - expect(manager.restartTask('001-add-login', 'profile-b')).toBe(true); - await nextRun(2); - expect(manager.restartTask('001-add-login', 'profile-c')).toBe(true); - await nextRun(3); - expect(manager.restartTask('001-add-login', 'profile-d')).toBe(false); - }); - it('reports a failed start when the worktree cannot be created', async () => { const { createOrGetWorktree } = await import('../worktree'); vi.mocked(createOrGetWorktree).mockRejectedValueOnce(new Error('git worktree add failed')); diff --git a/src/main/agent/agent-manager.ts b/src/main/agent/agent-manager.ts index 27db440505..1acd1e610c 100644 --- a/src/main/agent/agent-manager.ts +++ b/src/main/agent/agent-manager.ts @@ -27,7 +27,6 @@ import { getAugmentedEnvAsync } from '../env-utils'; import { isWslRuntime } from '../platform/shell-runtime'; import { git } from '../utils/git-exec'; import { getClaudeProfileManager } from '../claude-profile-manager'; -import { getOperationRegistry } from '../claude-profile/operation-registry'; import { getAPIProfileEnv } from '../services/profile'; import { getSpecsDir } from '../../shared/constants'; import { getTaskWorktreeBranch } from '../../shared/utils/claude-run'; @@ -41,8 +40,6 @@ import { branchMergeBlocker, waitForBranchSync } from '../worktree/merge-guard'; import { keepsLocalMergeOut, readResyncRequest } from '../task-resync/request'; -/** Restarts after a rate limit or auth problem before giving up (prevents swap loops) */ -const MAX_SWAPS_PER_TASK = 2; /** How long killAll waits for runs to wind down */ const KILL_ALL_TIMEOUT_MS = 10_000; @@ -61,11 +58,11 @@ interface RunEntry { taskId: string; /** Set once setup finished and the run was created */ run?: ClaudeTaskRun; - /** Claude profile the run was started on (undefined: best available at start) */ + /** Claude profile the run was started on (undefined: the account in use at start) */ profileId?: string; /** An API profile (Anthropic-compatible endpoint) is active: Claude profiles are not used */ apiProfileActive: boolean; - /** Stopped by killTask/restartTask: its outcome is not reported */ + /** Stopped by killTask: its outcome is not reported */ killed: boolean; /** Settles when the run (and its state flush) finished */ done: Promise; @@ -85,24 +82,9 @@ interface RunEntry { */ const runKey = (projectId: string, taskId: string): string => `${projectId}\u0000${taskId}`; -/** - * The id a run is registered under in the operation registry (account swaps). The registry keys - * its operations by whatever id it is handed, so a bare task id would let the second project's - * run overwrite the first's registration, and the first run to finish would unregister whichever - * entry was left - leaving one run without a swap registration and the other with a stale one - * pointing at a run that has ended. The registry and its other reader (`usage-monitor.ts`, which - * groups ids by profile and logs them) treat the id as opaque, so naming the project here is - * free; it is spelled out rather than reusing `runKey` because it is read by people in logs. - */ -const operationId = (projectId: string, taskId: string): string => `task:${projectId}:${taskId}`; - export class AgentManager extends EventEmitter { private state = new AgentState(); private runs = new Map(); - /** Options of the latest run per project and task, for restarts after it ended */ - private lastOptions = new Map(); - /** Automatic restarts (profile swaps) per project and task since the user last started it */ - private swapCounts = new Map(); /** Last task event sequence per project and task (monotonic across runs and app restarts) */ private sequences = new Map(); @@ -116,14 +98,14 @@ export class AgentManager extends EventEmitter { * renderer older than the field it now sends - and for internal callers that never had one. * * With two projects running the same task id there is no run such a caller can be meaning, and - * the arbitrary first match would stop or restart a run the user never touched, so that case is + * the arbitrary first match would stop a run the user never touched, so that case is * logged and refused: the caller reads it as "not running", which the user can repeat from the * project's own board, where the project travels with the request. */ private keyOf(taskId: string, projectId?: string): string | undefined { if (projectId) { const key = runKey(projectId, taskId); - return this.runs.has(key) || this.lastOptions.has(key) ? key : undefined; + return this.runs.has(key) ? key : undefined; } let found: string | undefined; for (const [key, entry] of this.runs) { @@ -148,13 +130,9 @@ export class AgentManager extends EventEmitter { * Run state lives in `/claude_run.json`, so a started task continues where it * stopped (triage, plan and implementation aren't repeated once completed). */ - async startTask(taskId: string, options: StartTaskOptions): Promise { - return this.launch(taskId, options, false); - } - - private async launch(taskId: string, startOptions: StartTaskOptions, isRestart: boolean): Promise { - // The project's Claude account (Settings > Project) unless the run is pinned to another one - // (e.g. a restart after an account swap); none: the account in use + async startTask(taskId: string, startOptions: StartTaskOptions): Promise { + // The project's Claude account (Settings > Project) unless the run is pinned to another one; + // none: the account in use const options: StartTaskOptions = { ...startOptions, profileId: startOptions.profileId ?? startOptions.project.settings?.claudeProfileId, @@ -170,8 +148,6 @@ export class AgentManager extends EventEmitter { this.killTask(taskId, projectId); await previous.done; } - if (!isRestart) this.swapCounts.delete(key); - this.lastOptions.set(key, options); let resolveDone!: () => void; const entry: RunEntry = { @@ -260,7 +236,7 @@ export class AgentManager extends EventEmitter { }); entry.run = run; - this.registerWithOperationRegistry(taskId, entry); + this.recordTaskProfile(taskId, entry); run.run() .then((outcome) => this.handleRunFinished(taskId, entry, outcome)) @@ -294,7 +270,6 @@ export class AgentManager extends EventEmitter { this.runs.delete(key); // The run the key found owns the project, which the caller may not have named this.state.removeRunning(taskId, entry.projectId); - getOperationRegistry().unregisterOperation(operationId(entry.projectId, taskId)); return entry.projectId; } @@ -328,47 +303,11 @@ export class AgentManager extends EventEmitter { return Array.from(this.runs.values()).map((entry) => entry.taskId); } - /** - * Restart a task's run on another Claude profile (rate limit or proactive swap). The run - * continues from its saved state. Returns false when the task can't be restarted. - */ - restartTask(taskId: string, newProfileId?: string, projectId?: string): boolean { - const key = this.keyOf(taskId, projectId); - const options = (key ? this.runs.get(key)?.options ?? this.lastOptions.get(key) : undefined); - if (!key || !options) { - appLog.warn(`[AgentManager] restartTask: no run options for ${taskId}`); - return false; - } - const swaps = this.swapCounts.get(key) ?? 0; - if (swaps >= MAX_SWAPS_PER_TASK) { - appLog.warn(`[AgentManager] restartTask: ${taskId} already restarted ${swaps} times, not restarting again`); - return false; - } - this.swapCounts.set(key, swaps + 1); - - if (newProfileId) { - const profileManager = getClaudeProfileManager(); - if (profileManager.getActiveProfile()?.id !== newProfileId) { - profileManager.setActiveProfile(newProfileId); - } - } - - const previous = this.runs.get(key); - this.killTask(taskId, options.project.id); - const restartOptions: StartTaskOptions = { ...options, profileId: newProfileId ?? options.profileId }; - void (previous?.done ?? Promise.resolve()).then(() => - this.launch(taskId, restartOptions, true).catch((error) => - appLog.error(`[AgentManager] Restarting ${taskId} failed:`, error) - ) - ); - return true; - } - // ============================================ - // Queue Routing Methods (Rate Limit Recovery) + // Profile and session of tasks // ============================================ - /** Running tasks grouped by profile (queue routing) */ + /** Running tasks grouped by profile */ getRunningTasksByProfile(): { byProfile: Record; totalRunning: number } { return this.state.getRunningTasksByProfile(); } @@ -417,7 +356,7 @@ export class AgentManager extends EventEmitter { const specDir = path.join(project.path, getSpecsDir(project.autoBuildPath), task.specId); // A base branch the user chose - on the task, or as the project's main branch - may have been - // deleted or renamed since. Nothing stands in for it: this throws, `launch()` turns the message + // deleted or renamed since. Nothing stands in for it: this throws, `startTask()` turns the message // into a recoverable failure, and the user gives the task a base branch that exists instead of // getting a run built on code they never chose. A branch the repository has never heard of is // not the same thing as a branch that is gone - a teammate may have pushed it, or it may have @@ -701,8 +640,8 @@ export class AgentManager extends EventEmitter { } /** - * Record a rate limit on the Claude profile the run used, so the next runs (and an - * automatic swap) pick another profile. Returns that profile's ID. + * Record a rate limit on the Claude profile the run used (shown with the account until its + * reset). Returns that profile's ID. */ private recordRateLimit(entry: RunEntry, payload: Record): string | undefined { if (entry.apiProfileActive) return undefined; @@ -727,7 +666,8 @@ export class AgentManager extends EventEmitter { } } - private registerWithOperationRegistry(taskId: string, entry: RunEntry): void { + /** Record which Claude profile the task runs on */ + private recordTaskProfile(taskId: string, entry: RunEntry): void { if (entry.apiProfileActive) return; try { const profileManager = getClaudeProfileManager(); @@ -740,21 +680,8 @@ export class AgentManager extends EventEmitter { entry.profileId ? 'reactive' : 'proactive', entry.projectId ); - // No stopFn: restartTask stops the run itself. Both the id the run is registered under and - // the swap name the project as well as the task, because a task id only tells the projects - // apart together with it: left out, the second project's run would replace the first's - // registration, and restartTask would take whichever run happens to carry that id, so a - // rate-limit swap here could stop and restart another project's run instead of this one - getOperationRegistry().registerOperation( - operationId(entry.projectId, taskId), - 'task-execution', - profile.id, - profile.name, - (newProfileId: string) => this.restartTask(taskId, newProfileId, entry.projectId), - { metadata: { projectPath: entry.options.project.path, specId: entry.options.task.specId } } - ); } catch (error) { - appLog.warn('[AgentManager] Could not register the task for profile swaps:', error); + appLog.warn('[AgentManager] Could not record the task\'s profile:', error); } } @@ -768,7 +695,6 @@ export class AgentManager extends EventEmitter { if (this.runs.get(key) === entry) { this.runs.delete(key); this.state.removeRunning(taskId, entry.projectId); - getOperationRegistry().unregisterOperation(operationId(entry.projectId, taskId)); } // Stopped by the user or replaced by a restart: nothing to report if (entry.killed || outcome.status === 'stopped') return; diff --git a/src/main/agent/agent-state.ts b/src/main/agent/agent-state.ts index 8454615834..1e4be1f7e2 100644 --- a/src/main/agent/agent-state.ts +++ b/src/main/agent/agent-state.ts @@ -39,7 +39,7 @@ const stateKey = (taskId: string, projectId?: string): string => `${projectId ?? export class AgentState { private running: Map = new Map(); - // Queue routing state (rate limit recovery) + // The Claude profile and session of each task private taskProfileAssignments: Map = new Map(); /** @@ -124,17 +124,16 @@ export class AgentState { } // ============================================ - // Queue Routing Methods (Rate Limit Recovery) + // Profile and session of tasks // ============================================ /** * Running tasks grouped by profile. * - * The task ids are reported as they are, without the project they are keyed under: this shape - * is the `RunningTasksByProfile` IPC payload (`shared/types/agent.ts`), whose task ids are read - * as task ids. Two projects running the same task therefore show up as that id twice, which is - * the truth about how many runs are on the profile. Each one's assignment is looked up by its - * own project, so the two never read each other's profile. + * The task ids are reported as they are, without the project they are keyed under. Two + * projects running the same task therefore show up as that id twice, which is the truth about + * how many runs are on the profile. Each one's assignment is looked up by its own project, so + * the two never read each other's profile. */ getRunningTasksByProfile(): { byProfile: Record; totalRunning: number } { const byProfile: Record = {}; diff --git a/src/main/agent/types.ts b/src/main/agent/types.ts index 0f20bbaeea..a38c7e1157 100644 --- a/src/main/agent/types.ts +++ b/src/main/agent/types.ts @@ -28,7 +28,7 @@ export interface StartTaskOptions { feedback?: string; /** Absolute paths of images attached to the feedback */ feedbackImagePaths?: string[]; - /** Claude profile to run on (undefined = best available) */ + /** Claude profile to run on (undefined = the project's account, else the account in use) */ profileId?: string; } diff --git a/src/main/claude-code/__tests__/env.test.ts b/src/main/claude-code/__tests__/env.test.ts index a28f0bd8d2..9f0e15fbbb 100644 --- a/src/main/claude-code/__tests__/env.test.ts +++ b/src/main/claude-code/__tests__/env.test.ts @@ -31,7 +31,7 @@ vi.mock('../../platform/shell-runtime', () => ({ vi.mock('../../services/profile', () => ({ getAPIProfileEnv: async () => ({}) })); vi.mock('../../rate-limit-detector', () => ({ getUsableProfileEnv: () => profileEnvRef.env, - getBestAvailableProfileEnv: () => ({ env: profileEnvRef.env, profileId: 'p', profileName: 'P' }), + getRunnableProfileEnv: () => ({ env: profileEnvRef.env, profileId: 'p', profileName: 'P' }), isDetectedClaudeCodeProfile: () => profileEnvRef.detected, })); diff --git a/src/main/claude-code/env.ts b/src/main/claude-code/env.ts index 9db2985c13..a40c299a66 100644 --- a/src/main/claude-code/env.ts +++ b/src/main/claude-code/env.ts @@ -15,7 +15,7 @@ import path from 'path'; import { existsSync } from 'fs'; import { getClaudeCliInvocationAsync } from '../cli-utils'; import { getToolInfoAsync } from '../cli-tool-manager'; -import { getBestAvailableProfileEnv, getUsableProfileEnv, isDetectedClaudeCodeProfile } from '../rate-limit-detector'; +import { getRunnableProfileEnv, getUsableProfileEnv, isDetectedClaudeCodeProfile } from '../rate-limit-detector'; import { getAPIProfileEnv } from '../services/profile'; import { isWindows } from '../platform'; import { getWslInfo, whenShellRuntimeReady } from '../platform/shell-runtime'; @@ -63,7 +63,8 @@ function deriveGitBashPath(gitExePath: string): string | null { /** * Resolve the `claude` command and the environment to run it with. - * Picks the best available Claude profile (rate-limit aware) unless one is given. + * Runs on the given Claude profile, else the account in use (never another account because of + * rate limits; see getRunnableProfileEnv). */ export async function resolveClaudeEnv(options: ClaudeEnvOptions = {}): Promise { // Runs spawned right after startup must know whether Claude Code runs in WSL @@ -98,16 +99,16 @@ export async function resolveClaudeEnv(options: ClaudeEnvOptions = {}): Promise< let profileId: string | undefined; let profileName: string | undefined; // A requested profile is used while it exists and is signed in; otherwise (removed, or never - // signed in) the best available profile runs instead of a run that can only fail + // signed in) the account in use runs instead of a run that can only fail const pinnedEnv = options.profileId ? getUsableProfileEnv(options.profileId) : null; if (options.profileId && pinnedEnv) { profileEnv = pinnedEnv; profileId = options.profileId; } else { - const best = getBestAvailableProfileEnv(); - profileEnv = best.env; - profileId = best.profileId; - profileName = best.profileName; + const runnable = getRunnableProfileEnv(); + profileEnv = runnable.env; + profileId = runnable.profileId; + profileName = runnable.profileName; } // Subscription sign-in: never let a shell API key take over billing. A detected Claude Code diff --git a/src/main/claude-code/task-runner.ts b/src/main/claude-code/task-runner.ts index 700710a560..ba8ac70da7 100644 --- a/src/main/claude-code/task-runner.ts +++ b/src/main/claude-code/task-runner.ts @@ -1269,8 +1269,8 @@ no notes came with the request, so review the change against the task with fresh }, tempDir: string | undefined): Promise { const { messaging } = this; const { settings } = this.config; - // Stay on the profile that holds the session transcript, unless the caller switched profiles - // (rate-limit swap); then the transcript is copied to the new profile below + // Stay on the profile that holds the session transcript, unless the caller names another one + // (the project's account was changed); then the transcript is copied to the new profile below const { command, env, profileId } = await resolveClaudeEnv({ profileId: this.config.profileId ?? (params.resume ? this.info.profileId : undefined), extraEnv: { diff --git a/src/main/claude-profile-manager.ts b/src/main/claude-profile-manager.ts index a676a323e2..e32720cd29 100644 --- a/src/main/claude-profile-manager.ts +++ b/src/main/claude-profile-manager.ts @@ -7,7 +7,6 @@ * - usage-parser: Usage data parsing and reset time calculations * - rate-limit-manager: Rate limit event tracking * - profile-storage: Disk persistence - * - profile-scorer: Profile availability scoring and auto-switch logic * - profile-utils: Helper utilities */ @@ -19,11 +18,8 @@ import type { ClaudeProfile, ClaudeProfileSettings, ClaudeUsageData, - ClaudeRateLimitEvent, - ClaudeAutoSwitchSettings, - APIProfile + ClaudeRateLimitEvent } from '../shared/types'; -import type { UnifiedAccount } from '../shared/types/unified-account'; // Module imports import { encryptToken, decryptToken } from './claude-profile/token-encryption'; @@ -38,17 +34,9 @@ import { import { loadProfileStoreAsync, saveProfileStore, - ProfileStoreData, - DEFAULT_AUTO_SWITCH_SETTINGS + ProfileStoreData } from './claude-profile/profile-storage'; -import { - getBestAvailableProfile, - shouldProactivelySwitch as shouldProactivelySwitchImpl, - getProfilesSortedByAvailability as getProfilesSortedByAvailabilityImpl, - getBestAvailableUnifiedAccount -} from './claude-profile/profile-scorer'; import { getCredentialsFromKeychain, getKeychainServiceName, normalizeWindowsPath, updateProfileSubscriptionMetadata } from './claude-profile/credential-utils'; -import { loadProfilesFile } from './services/profile/profile-manager'; import { getClaudeProfilesDir, generateProfileId as generateProfileIdImpl, @@ -119,7 +107,7 @@ export class ClaudeProfileManager { private initialized: boolean = false; /** Set once the store for this session's runtime (native or WSL) is chosen; nothing is saved before */ private storeReady: boolean = false; - /** Called whenever the account in use changes, from any caller (Settings, swaps, terminals) */ + /** Called whenever the account in use changes, from any caller (Settings, terminals) */ private activeProfileListeners = new Set<(profileId: string, previousProfileId: string) => void>(); constructor() { @@ -614,8 +602,7 @@ export class ClaudeProfileManager { return { version: 3, profiles: [defaultProfile], - activeProfileId: sanitizedName, - autoSwitch: DEFAULT_AUTO_SWITCH_SETTINGS + activeProfileId: sanitizedName }; } @@ -641,29 +628,10 @@ export class ClaudeProfileManager { return { profiles: profilesWithAuth, - activeProfileId: this.data.activeProfileId, - autoSwitch: this.data.autoSwitch || DEFAULT_AUTO_SWITCH_SETTINGS + activeProfileId: this.data.activeProfileId }; } - /** - * Get auto-switch settings - */ - getAutoSwitchSettings(): ClaudeAutoSwitchSettings { - return this.data.autoSwitch || DEFAULT_AUTO_SWITCH_SETTINGS; - } - - /** - * Update auto-switch settings - */ - updateAutoSwitchSettings(settings: Partial): void { - this.data.autoSwitch = { - ...(this.data.autoSwitch || DEFAULT_AUTO_SWITCH_SETTINGS), - ...settings - }; - this.save(); - } - /** * The profiles' Claude Code config dirs (as stored), without checking their credentials */ @@ -1108,82 +1076,6 @@ export class ClaudeProfileManager { return isProfileRateLimitedImpl(profile); } - /** - * Get the best profile to switch to based on availability and usage - * Returns null if no good alternative is available - * - * Selection logic: - * 1. Filters by availability (authenticated, not rate-limited, below thresholds) - * 2. Returns the available profile with the most headroom (lowest usage) - * 3. Falls back to "least bad" option if no profile meets all criteria - */ - getBestAvailableProfile(excludeProfileId?: string): ClaudeProfile | null { - const settings = this.getAutoSwitchSettings(); - return getBestAvailableProfile(this.data.profiles, settings, excludeProfileId); - } - - /** - * Load API profiles from profiles.json with error handling - * Shared helper to avoid duplication across methods - */ - private async loadProfilesFileSafe(): Promise<{ profiles: APIProfile[]; activeProfileId?: string }> { - try { - const file = await loadProfilesFile(); - return { profiles: file.profiles, activeProfileId: file.activeProfileId ?? undefined }; - } catch (error) { - console.error('[ClaudeProfileManager] Failed to load profiles file:', error); - return { profiles: [] }; - } - } - - /** - * Load API profiles from profiles.json - * Used by the unified account selection to consider API profiles as fallback - */ - async loadAPIProfiles(): Promise { - const { profiles } = await this.loadProfilesFileSafe(); - return profiles; - } - - /** - * Get the best available unified account from both OAuth and API profiles - * This enables cross-type account switching when OAuth profiles are exhausted - * - * @param excludeAccountId - Unified account ID to exclude (e.g., 'oauth-profile1') - * @returns The best available UnifiedAccount, or null if none available - */ - async getBestAvailableUnifiedAccount(excludeAccountId?: string): Promise { - const settings = this.getAutoSwitchSettings(); - const activeOAuthId = this.data.activeProfileId; - - // Load API profiles and active API profile ID from profiles.json - const { profiles: apiProfiles, activeProfileId: activeAPIId } = await this.loadProfilesFileSafe(); - - return getBestAvailableUnifiedAccount( - this.data.profiles, - apiProfiles, - settings, - { - excludeAccountId, - activeOAuthId, - activeAPIId - } - ); - } - - /** - * Determine if we should proactively switch profiles based on current usage - */ - shouldProactivelySwitch(profileId: string): { shouldSwitch: boolean; reason?: string; suggestedProfile?: ClaudeProfile } { - const profile = this.getProfile(profileId); - if (!profile) { - return { shouldSwitch: false }; - } - - const settings = this.getAutoSwitchSettings(); - return shouldProactivelySwitchImpl(profile, this.data.profiles, settings); - } - /** * Generate a unique ID for a new profile */ @@ -1322,13 +1214,6 @@ export class ClaudeProfileManager { } } - /** - * Get profiles sorted by availability (best first) - */ - getProfilesSortedByAvailability(): ClaudeProfile[] { - return getProfilesSortedByAvailabilityImpl(this.data.profiles); - } - /** * Get the list of profile IDs that were migrated from shared ~/.claude to isolated directories. * These profiles need re-authentication since their credentials are in the old location. diff --git a/src/main/claude-profile/__tests__/operation-registry.test.ts b/src/main/claude-profile/__tests__/operation-registry.test.ts deleted file mode 100644 index ef6be3a1c8..0000000000 --- a/src/main/claude-profile/__tests__/operation-registry.test.ts +++ /dev/null @@ -1,669 +0,0 @@ -/** - * Unit tests for OperationRegistry - * - * Tests cover: - * - Singleton pattern - * - Operation registration/unregistration - * - Profile-based querying - * - Summary generation - * - Operation restart functionality - * - Event emissions - * - Edge cases - */ - -import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { - getOperationRegistry, - resetOperationRegistry, - type OperationType, -} from '../operation-registry'; - -describe('OperationRegistry', () => { - beforeEach(() => { - // Reset registry before each test - resetOperationRegistry(); - }); - - afterEach(() => { - // Clean up after each test - resetOperationRegistry(); - }); - - describe('Singleton Pattern', () => { - it('should return the same instance on multiple calls', () => { - const instance1 = getOperationRegistry(); - const instance2 = getOperationRegistry(); - - expect(instance1).toBe(instance2); - }); - - it('should create new instance after reset', () => { - const instance1 = getOperationRegistry(); - resetOperationRegistry(); - const instance2 = getOperationRegistry(); - - expect(instance1).not.toBe(instance2); - }); - - it('should clear all operations on reset', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation( - 'op1', - 'spec-creation', - 'profile1', - 'Profile 1', - mockRestart - ); - - expect(registry.getOperationCount()).toBe(1); - - resetOperationRegistry(); - const newRegistry = getOperationRegistry(); - - expect(newRegistry.getOperationCount()).toBe(0); - }); - }); - - describe('registerOperation', () => { - it('should register a basic operation', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation( - 'op1', - 'spec-creation', - 'profile1', - 'Profile 1', - mockRestart - ); - - const operation = registry.getOperation('op1'); - expect(operation).toBeDefined(); - expect(operation?.id).toBe('op1'); - expect(operation?.type).toBe('spec-creation'); - expect(operation?.profileId).toBe('profile1'); - expect(operation?.profileName).toBe('Profile 1'); - expect(operation?.restartFn).toBe(mockRestart); - expect(operation?.startedAt).toBeInstanceOf(Date); - }); - - it('should register operation with optional stopFn', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - const mockStop = vi.fn(); - - registry.registerOperation( - 'op1', - 'mr-review', - 'profile1', - 'Profile 1', - mockRestart, - { stopFn: mockStop } - ); - - const operation = registry.getOperation('op1'); - expect(operation?.stopFn).toBe(mockStop); - }); - - it('should register operation with metadata', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - const metadata = { projectId: 'proj1', prNumber: 123 }; - - registry.registerOperation( - 'op1', - 'mr-review', - 'profile1', - 'Profile 1', - mockRestart, - { metadata } - ); - - const operation = registry.getOperation('op1'); - expect(operation?.metadata).toEqual(metadata); - }); - - it('should emit operation-registered event', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - const eventListener = vi.fn(); - - registry.on('operation-registered', eventListener); - - registry.registerOperation( - 'op1', - 'task-execution', - 'profile1', - 'Profile 1', - mockRestart - ); - - expect(eventListener).toHaveBeenCalledTimes(1); - const emittedOperation = eventListener.mock.calls[0][0]; - expect(emittedOperation.id).toBe('op1'); - expect(emittedOperation.type).toBe('task-execution'); - }); - - it('should increment operation count', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - expect(registry.getOperationCount()).toBe(0); - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - expect(registry.getOperationCount()).toBe(1); - - registry.registerOperation('op2', 'triage', 'profile1', 'Profile 1', mockRestart); - expect(registry.getOperationCount()).toBe(2); - }); - - it('should allow registering multiple operation types', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - const types: OperationType[] = [ - 'spec-creation', - 'task-execution', - 'mr-review', - 'insights', - 'triage', - 'other', - ]; - - types.forEach((type, index) => { - registry.registerOperation( - `op${index}`, - type, - 'profile1', - 'Profile 1', - mockRestart - ); - }); - - expect(registry.getOperationCount()).toBe(types.length); - - types.forEach((type, index) => { - const op = registry.getOperation(`op${index}`); - expect(op?.type).toBe(type); - }); - }); - }); - - describe('unregisterOperation', () => { - it('should unregister an existing operation', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - expect(registry.getOperation('op1')).toBeDefined(); - - registry.unregisterOperation('op1'); - expect(registry.getOperation('op1')).toBeUndefined(); - expect(registry.getOperationCount()).toBe(0); - }); - - it('should emit operation-unregistered event', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - const eventListener = vi.fn(); - - registry.on('operation-unregistered', eventListener); - - registry.registerOperation('op1', 'task-execution', 'profile1', 'Profile 1', mockRestart); - registry.unregisterOperation('op1'); - - expect(eventListener).toHaveBeenCalledTimes(1); - expect(eventListener).toHaveBeenCalledWith('op1', 'task-execution'); - }); - - it('should handle unregistering non-existent operation gracefully', () => { - const registry = getOperationRegistry(); - const eventListener = vi.fn(); - - registry.on('operation-unregistered', eventListener); - - // Should not throw - expect(() => registry.unregisterOperation('non-existent')).not.toThrow(); - - // Should not emit event for non-existent operation - expect(eventListener).not.toHaveBeenCalled(); - }); - - it('should decrement operation count', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'triage', 'profile1', 'Profile 1', mockRestart); - expect(registry.getOperationCount()).toBe(2); - - registry.unregisterOperation('op1'); - expect(registry.getOperationCount()).toBe(1); - - registry.unregisterOperation('op2'); - expect(registry.getOperationCount()).toBe(0); - }); - }); - - describe('getOperation', () => { - it('should retrieve operation by id', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'mr-review', 'profile1', 'Profile 1', mockRestart); - - const operation = registry.getOperation('op1'); - expect(operation).toBeDefined(); - expect(operation?.id).toBe('op1'); - }); - - it('should return undefined for non-existent operation', () => { - const registry = getOperationRegistry(); - - const operation = registry.getOperation('non-existent'); - expect(operation).toBeUndefined(); - }); - }); - - describe('getOperationsByProfile', () => { - it('should return operations for a specific profile', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op3', 'mr-review', 'profile2', 'Profile 2', mockRestart); - - const profile1Ops = registry.getOperationsByProfile('profile1'); - expect(profile1Ops).toHaveLength(2); - expect(profile1Ops.map(op => op.id)).toEqual(['op1', 'op2']); - - const profile2Ops = registry.getOperationsByProfile('profile2'); - expect(profile2Ops).toHaveLength(1); - expect(profile2Ops[0].id).toBe('op3'); - }); - - it('should return empty array for profile with no operations', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - - const profile2Ops = registry.getOperationsByProfile('profile2'); - expect(profile2Ops).toEqual([]); - }); - }); - - describe('getAllOperationsByProfile', () => { - it('should return all operations grouped by profile', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op3', 'mr-review', 'profile2', 'Profile 2', mockRestart); - registry.registerOperation('op4', 'triage', 'profile3', 'Profile 3', mockRestart); - - const allOps = registry.getAllOperationsByProfile(); - - expect(Object.keys(allOps)).toEqual(['profile1', 'profile2', 'profile3']); - expect(allOps['profile1']).toHaveLength(2); - expect(allOps['profile2']).toHaveLength(1); - expect(allOps['profile3']).toHaveLength(1); - }); - - it('should return empty object when no operations', () => { - const registry = getOperationRegistry(); - - const allOps = registry.getAllOperationsByProfile(); - expect(allOps).toEqual({}); - }); - }); - - describe('getSummary', () => { - it('should return correct summary with no operations', () => { - const registry = getOperationRegistry(); - - const summary = registry.getSummary(); - expect(summary.totalRunning).toBe(0); - expect(summary.byProfile).toEqual({}); - expect(summary.byType).toEqual({}); - }); - - it('should count operations by profile', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op3', 'mr-review', 'profile2', 'Profile 2', mockRestart); - - const summary = registry.getSummary(); - - expect(summary.totalRunning).toBe(3); - expect(summary.byProfile['profile1']).toEqual(['op1', 'op2']); - expect(summary.byProfile['profile2']).toEqual(['op3']); - }); - - it('should count operations by type', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op3', 'mr-review', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op4', 'insights', 'profile2', 'Profile 2', mockRestart); - - const summary = registry.getSummary(); - - expect(summary.byType['spec-creation']).toBe(2); - expect(summary.byType['mr-review']).toBe(1); - expect(summary.byType['insights']).toBe(1); - }); - - it('should return complete summary with multiple profiles and types', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op3', 'mr-review', 'profile2', 'Profile 2', mockRestart); - registry.registerOperation('op4', 'insights', 'profile2', 'Profile 2', mockRestart); - registry.registerOperation('op5', 'triage', 'profile3', 'Profile 3', mockRestart); - - const summary = registry.getSummary(); - - expect(summary.totalRunning).toBe(5); - expect(Object.keys(summary.byProfile)).toHaveLength(3); - expect(Object.keys(summary.byType)).toHaveLength(5); - }); - }); - - describe('restartOperationsOnProfile', () => { - it('should restart all operations on a profile', async () => { - const registry = getOperationRegistry(); - const mockRestart1 = vi.fn().mockResolvedValue(true); - const mockRestart2 = vi.fn().mockResolvedValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart1); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart2); - - const count = await registry.restartOperationsOnProfile( - 'profile1', - 'profile2', - 'Profile 2' - ); - - expect(count).toBe(2); - expect(mockRestart1).toHaveBeenCalledWith('profile2'); - expect(mockRestart2).toHaveBeenCalledWith('profile2'); - - // Verify profile was updated - const op1 = registry.getOperation('op1'); - const op2 = registry.getOperation('op2'); - expect(op1?.profileId).toBe('profile2'); - expect(op1?.profileName).toBe('Profile 2'); - expect(op2?.profileId).toBe('profile2'); - expect(op2?.profileName).toBe('Profile 2'); - }); - - it('should call stopFn before restart if provided', async () => { - const registry = getOperationRegistry(); - const mockStop = vi.fn().mockResolvedValue(undefined); - const mockRestart = vi.fn().mockResolvedValue(true); - - registry.registerOperation( - 'op1', - 'mr-review', - 'profile1', - 'Profile 1', - mockRestart, - { stopFn: mockStop } - ); - - await registry.restartOperationsOnProfile('profile1', 'profile2', 'Profile 2'); - - expect(mockStop).toHaveBeenCalledTimes(1); - expect(mockRestart).toHaveBeenCalledWith('profile2'); - // Ensure stopFn was called before restartFn - expect(mockStop.mock.invocationCallOrder[0]).toBeLessThan( - mockRestart.mock.invocationCallOrder[0] - ); - }); - - it('should return 0 when no operations on profile', async () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockResolvedValue(true); - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - - const count = await registry.restartOperationsOnProfile( - 'profile2', - 'profile3', - 'Profile 3' - ); - - expect(count).toBe(0); - expect(mockRestart).not.toHaveBeenCalled(); - }); - - it('should handle restart failure gracefully', async () => { - const registry = getOperationRegistry(); - const mockRestart1 = vi.fn().mockResolvedValue(true); - const mockRestart2 = vi.fn().mockResolvedValue(false); // Fails - const mockRestart3 = vi.fn().mockRejectedValue(new Error('Restart error')); // Throws - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart1); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart2); - registry.registerOperation('op3', 'mr-review', 'profile1', 'Profile 1', mockRestart3); - - const count = await registry.restartOperationsOnProfile( - 'profile1', - 'profile2', - 'Profile 2' - ); - - // Only op1 succeeded - expect(count).toBe(1); - - // op1 should have updated profile - const op1 = registry.getOperation('op1'); - expect(op1?.profileId).toBe('profile2'); - - // op2 and op3 should still have old profile - const op2 = registry.getOperation('op2'); - const op3 = registry.getOperation('op3'); - expect(op2?.profileId).toBe('profile1'); - expect(op3?.profileId).toBe('profile1'); - }); - - it('should emit operation-restarted event for each successful restart', async () => { - const registry = getOperationRegistry(); - const mockRestart1 = vi.fn().mockResolvedValue(true); - const mockRestart2 = vi.fn().mockResolvedValue(true); - const eventListener = vi.fn(); - - registry.on('operation-restarted', eventListener); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart1); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart2); - - await registry.restartOperationsOnProfile('profile1', 'profile2', 'Profile 2'); - - expect(eventListener).toHaveBeenCalledTimes(2); - expect(eventListener).toHaveBeenCalledWith('op1', 'profile1', 'profile2'); - expect(eventListener).toHaveBeenCalledWith('op2', 'profile1', 'profile2'); - }); - - it('should emit operations-restarted event after restart', async () => { - const registry = getOperationRegistry(); - const mockRestart1 = vi.fn().mockResolvedValue(true); - const mockRestart2 = vi.fn().mockResolvedValue(true); - const eventListener = vi.fn(); - - registry.on('operations-restarted', eventListener); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart1); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart2); - - await registry.restartOperationsOnProfile('profile1', 'profile2', 'Profile 2'); - - expect(eventListener).toHaveBeenCalledTimes(1); - expect(eventListener).toHaveBeenCalledWith(2, 'profile1', 'profile2'); - }); - - it('should not emit operations-restarted event if no restarts succeeded', async () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockResolvedValue(false); - const eventListener = vi.fn(); - - registry.on('operations-restarted', eventListener); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - - await registry.restartOperationsOnProfile('profile1', 'profile2', 'Profile 2'); - - expect(eventListener).not.toHaveBeenCalled(); - }); - - it('should handle synchronous restart functions', async () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); // Synchronous return - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - - const count = await registry.restartOperationsOnProfile( - 'profile1', - 'profile2', - 'Profile 2' - ); - - expect(count).toBe(1); - expect(mockRestart).toHaveBeenCalledWith('profile2'); - - const op1 = registry.getOperation('op1'); - expect(op1?.profileId).toBe('profile2'); - }); - }); - - describe('updateOperationProfile', () => { - it('should update profile for existing operation', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - - registry.updateOperationProfile('op1', 'profile2', 'Profile 2'); - - const operation = registry.getOperation('op1'); - expect(operation?.profileId).toBe('profile2'); - expect(operation?.profileName).toBe('Profile 2'); - }); - - it('should handle updating non-existent operation gracefully', () => { - const registry = getOperationRegistry(); - - // Should not throw - expect(() => - registry.updateOperationProfile('non-existent', 'profile2', 'Profile 2') - ).not.toThrow(); - }); - }); - - describe('clear', () => { - it('should clear all operations', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op2', 'task-execution', 'profile1', 'Profile 1', mockRestart); - registry.registerOperation('op3', 'mr-review', 'profile2', 'Profile 2', mockRestart); - - expect(registry.getOperationCount()).toBe(3); - - registry.clear(); - - expect(registry.getOperationCount()).toBe(0); - expect(registry.getSummary().totalRunning).toBe(0); - }); - }); - - describe('Edge Cases', () => { - it('should handle registering operation with same id (overwrites)', () => { - const registry = getOperationRegistry(); - const mockRestart1 = vi.fn().mockReturnValue(true); - const mockRestart2 = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'spec-creation', 'profile1', 'Profile 1', mockRestart1); - registry.registerOperation('op1', 'task-execution', 'profile2', 'Profile 2', mockRestart2); - - const operation = registry.getOperation('op1'); - expect(operation?.type).toBe('task-execution'); - expect(operation?.profileId).toBe('profile2'); - expect(registry.getOperationCount()).toBe(1); - }); - - it('should handle multiple unregisters of same operation', () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockReturnValue(true); - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - - registry.unregisterOperation('op1'); - expect(registry.getOperationCount()).toBe(0); - - // Second unregister should not throw or cause issues - registry.unregisterOperation('op1'); - expect(registry.getOperationCount()).toBe(0); - }); - - it('should handle restart with no operations gracefully', async () => { - const registry = getOperationRegistry(); - - const count = await registry.restartOperationsOnProfile( - 'profile1', - 'profile2', - 'Profile 2' - ); - - expect(count).toBe(0); - }); - - it('should preserve operation metadata through restart', async () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockResolvedValue(true); - const metadata = { projectId: 'proj1', prNumber: 123 }; - - registry.registerOperation( - 'op1', - 'mr-review', - 'profile1', - 'Profile 1', - mockRestart, - { metadata } - ); - - await registry.restartOperationsOnProfile('profile1', 'profile2', 'Profile 2'); - - const operation = registry.getOperation('op1'); - expect(operation?.metadata).toEqual(metadata); - }); - - it('should preserve startedAt timestamp through restart', async () => { - const registry = getOperationRegistry(); - const mockRestart = vi.fn().mockResolvedValue(true); - - registry.registerOperation('op1', 'insights', 'profile1', 'Profile 1', mockRestart); - - const originalOp = registry.getOperation('op1'); - const originalStartTime = originalOp?.startedAt; - - await registry.restartOperationsOnProfile('profile1', 'profile2', 'Profile 2'); - - const updatedOp = registry.getOperation('op1'); - expect(updatedOp?.startedAt).toBe(originalStartTime); - }); - }); -}); diff --git a/src/main/claude-profile/__tests__/usage-monitor-account-switch.test.ts b/src/main/claude-profile/__tests__/usage-monitor-account-switch.test.ts index a750e33e6e..2bb0c0c027 100644 --- a/src/main/claude-profile/__tests__/usage-monitor-account-switch.test.ts +++ b/src/main/claude-profile/__tests__/usage-monitor-account-switch.test.ts @@ -22,7 +22,6 @@ const state = vi.hoisted(() => ({ vi.mock('../../claude-profile-manager', () => { const manager = { - getAutoSwitchSettings: () => ({ enabled: false, proactiveSwapEnabled: false, usageCheckInterval: 60_000 }), getSettings: () => ({ profiles: state.profiles, activeProfileId: state.activeProfileId }), getActiveProfile: () => state.profiles.find((p) => p.id === state.activeProfileId), getProfile: (id: string) => state.profiles.find((p) => p.id === id), @@ -56,9 +55,6 @@ vi.mock('../../services/profile/profile-manager', () => ({ loadProfilesFile: async () => ({ profiles: [], activeProfileId: null, version: 1 }), })); vi.mock('../rate-limit-manager', () => ({ isProfileRateLimited: () => ({ limited: false }) })); -vi.mock('../operation-registry', () => ({ - getOperationRegistry: () => ({ getSummary: () => ({ totalRunning: 0, byProfile: {}, byType: {} }) }), -})); vi.mock('../../settings-utils', () => ({ readSettingsFileAsync: vi.fn(async () => undefined), readSettingsFile: vi.fn(() => undefined), @@ -77,7 +73,7 @@ function newMonitor(): UsageMonitor { } function checkNowAndWait(monitor: UsageMonitor): Promise { - return (monitor as unknown as { checkUsageAndSwap: () => Promise }).checkUsageAndSwap(); + return (monitor as unknown as { checkUsage: () => Promise }).checkUsage(); } describe('UsageMonitor account switch', () => { @@ -150,7 +146,7 @@ describe('UsageMonitor account switch', () => { updates.length = 0; lists.length = 0; - // Like Settings > Accounts or an automatic swap + // Like Settings > Accounts or an agent window's account menu const { getClaudeProfileManager } = await import('../../claude-profile-manager'); getClaudeProfileManager().setActiveProfile('claude-code-2'); diff --git a/src/main/claude-profile/operation-registry.ts b/src/main/claude-profile/operation-registry.ts deleted file mode 100644 index 3ae052dccb..0000000000 --- a/src/main/claude-profile/operation-registry.ts +++ /dev/null @@ -1,473 +0,0 @@ -/** - * Unified registry for ALL Claude Agent SDK operations. - * - * This is the single source of truth for tracking running operations that use - * Claude profiles. It enables: - * 1. Proactive account swapping - restart operations on a different profile - * 2. Rate limit recovery - know which operations to restart after auth refresh - * 3. Usage attribution - track which profile is being used by which operation - * - * Operations include: - * - Autonomous tasks (spec creation, task execution) - * - Insights analysis - * - Any other Claude SDK subprocess - */ - -import { EventEmitter } from 'events'; - -/** - * Types of operations that use Claude SDK - */ -export type OperationType = - | 'spec-creation' - | 'task-execution' - | 'mr-review' - | 'insights' - | 'triage' - | 'other'; - -/** - * Registered operation entry - * - * IMPORTANT: Object reference stability during restarts - * ===================================================== - * When an operation is restarted via restartFn, the restartFn implementation may - * choose to re-register the operation (creating a new RegisteredOperation object) - * OR update the existing one. Either approach is valid: - * - * 1. RE-REGISTRATION (AgentManager pattern): - * - restartFn calls registerOperation() which replaces the Map entry - * - Creates a new RegisteredOperation object with fresh closures - * - Previous object references become stale and should not be used - * - Callers MUST call getOperation(id) again to get the fresh reference - * - * 2. IN-PLACE UPDATE (alternative pattern): - * - restartFn updates internal state but doesn't re-register - * - Object reference remains valid - * - Registry calls updateOperationProfile() to sync profileId - * - * BEST PRACTICE for consumers: - * - Don't hold long-lived references to RegisteredOperation objects - * - Always use getOperation(id) to get current state - * - Subscribe to 'operation-restarted' events to know when to refresh - * - If you must hold a reference, listen for 'operation-restarted' and refresh it - */ -interface RegisteredOperation { - /** Unique operation ID */ - id: string; - /** Type of operation */ - type: OperationType; - /** Profile ID currently being used */ - profileId: string; - /** Profile name for logging */ - profileName: string; - /** When the operation started */ - startedAt: Date; - /** Optional metadata (project ID, PR number, etc.) */ - metadata?: Record; - /** - * Function to restart this operation with a new profile. - * Returns true if restart was initiated successfully. - * The registry will update the profileId after successful restart. - * - * IMPORTANT: This function may re-register the operation (creating a new object) - * or update in-place. Callers should use getOperation(id) after restart to get - * the current reference. - */ - restartFn: (newProfileId: string) => boolean | Promise; - /** - * Optional function to stop the operation. - * Called before restart if provided. - */ - stopFn?: () => void | Promise; -} - -/** - * Singleton registry for Claude SDK operations - * - * CONSUMER GUIDELINES: Object Reference Stability - * ================================================ - * Operations may be restarted during profile swaps. When this happens: - * - * 1. The operation's restartFn is called with a new profileId - * 2. The restartFn may choose to: - * a) Re-register the operation (creates new RegisteredOperation object), OR - * b) Update internal state without re-registering (keeps same object) - * - * 3. Either pattern is valid, but has implications for consumers: - * - Pattern (a): Previous object references become stale - * - Pattern (b): Object references remain valid - * - * BEST PRACTICES for consumers: - * - Don't hold long-lived references to RegisteredOperation objects - * - Always use getOperation(id) to get current state when needed - * - Subscribe to 'operation-restarted' events to know when state may have changed - * - Use hasOperation(id) to verify an operation is still registered - * - * EXAMPLE: Safely working with operation references - * ```typescript - * const registry = getOperationRegistry(); - * - * // Initial fetch - * let operation = registry.getOperation('task-123'); - * - * // Listen for restarts - * registry.onOperationRestarted((operationId, oldProfileId, newProfileId) => { - * if (operationId === 'task-123') { - * // Refresh reference after restart - * operation = registry.getOperation('task-123'); - * console.log('Operation restarted with new profile:', newProfileId); - * } - * }); - * - * // When accessing operation state later, prefer fresh fetch: - * const currentOp = registry.getOperation('task-123'); - * if (currentOp) { - * console.log('Current profile:', currentOp.profileId); - * } - * ``` - */ -class ClaudeOperationRegistry extends EventEmitter { - private operations: Map = new Map(); - private debugMode: boolean; - - constructor() { - super(); - this.debugMode = process.env.DEBUG === 'true'; - } - - private debugLog(...args: unknown[]): void { - if (this.debugMode) { - console.log('[OperationRegistry]', ...args); - } - } - - /** - * Register a new operation - */ - registerOperation( - id: string, - type: OperationType, - profileId: string, - profileName: string, - restartFn: RegisteredOperation['restartFn'], - options?: { - stopFn?: RegisteredOperation['stopFn']; - metadata?: Record; - } - ): void { - const operation: RegisteredOperation = { - id, - type, - profileId, - profileName, - startedAt: new Date(), - restartFn, - stopFn: options?.stopFn, - metadata: options?.metadata, - }; - - this.operations.set(id, operation); - this.debugLog('Operation registered:', { - id, - type, - profileId, - profileName, - metadata: options?.metadata, - }); - - this.emit('operation-registered', operation); - } - - /** - * Unregister an operation (when it completes or is cancelled) - */ - unregisterOperation(id: string): void { - const operation = this.operations.get(id); - if (operation) { - this.operations.delete(id); - this.debugLog('Operation unregistered:', { id, type: operation.type }); - this.emit('operation-unregistered', id, operation.type); - } - } - - /** - * Get all operations running on a specific profile - */ - getOperationsByProfile(profileId: string): RegisteredOperation[] { - const result: RegisteredOperation[] = []; - for (const op of this.operations.values()) { - if (op.profileId === profileId) { - result.push(op); - } - } - return result; - } - - /** - * Get all running operations grouped by profile - */ - getAllOperationsByProfile(): Record { - const result: Record = {}; - for (const op of this.operations.values()) { - if (!result[op.profileId]) { - result[op.profileId] = []; - } - result[op.profileId].push(op); - } - return result; - } - - /** - * Get operation by ID - * - * IMPORTANT: Always call this method to get the current operation state. - * Don't hold long-lived references to RegisteredOperation objects, as they - * may become stale after a restart. Instead, call getOperation(id) whenever - * you need current state, or subscribe to 'operation-restarted' events. - */ - getOperation(id: string): RegisteredOperation | undefined { - return this.operations.get(id); - } - - /** - * Check if an operation exists and is currently registered. - * Use this to verify an operation reference is still valid. - * - * @param id - Operation ID to check - * @returns true if operation exists in registry, false otherwise - */ - hasOperation(id: string): boolean { - return this.operations.has(id); - } - - /** - * Get count of running operations - */ - getOperationCount(): number { - return this.operations.size; - } - - /** - * Get summary of running operations for logging - */ - getSummary(): { - totalRunning: number; - byProfile: Record; - byType: Record; - } { - const byProfile: Record = {}; - const byType: Record = {}; - - for (const op of this.operations.values()) { - // By profile - if (!byProfile[op.profileId]) { - byProfile[op.profileId] = []; - } - byProfile[op.profileId].push(op.id); - - // By type - byType[op.type] = (byType[op.type] || 0) + 1; - } - - return { - totalRunning: this.operations.size, - byProfile, - byType: byType as Record, - }; - } - - /** - * Restart all operations running on a specific profile with a new profile. - * This is called by UsageMonitor during proactive swaps. - * - * IMPORTANT: Object reference stability after restart - * ==================================================== - * When operations are restarted, their restartFn implementations may: - * 1. Re-register the operation (AgentManager pattern) - creates new object - * 2. Update in-place (alternative pattern) - keeps same object - * - * For consumers holding operation references: - * - Your reference may become stale if the operation re-registers - * - Always call getOperation(id) after this method to get fresh reference - * - Or subscribe to 'operation-restarted' events and refresh on each event - * - * This method emits: - * - 'operation-restarted' for each successful restart (use this to refresh refs) - * - 'operations-restarted' once with total count - * - 'operation-profile-updated' for each profile update - * - * @param oldProfileId - Profile ID to migrate away from - * @param newProfileId - Profile ID to migrate to - * @param newProfileName - Profile name for logging - * @returns Number of operations that were restarted - */ - async restartOperationsOnProfile( - oldProfileId: string, - newProfileId: string, - newProfileName: string - ): Promise { - const operations = this.getOperationsByProfile(oldProfileId); - - if (operations.length === 0) { - this.debugLog('No operations to restart on profile:', oldProfileId); - return 0; - } - - console.log('[OperationRegistry] Restarting', operations.length, 'operations:', { - from: oldProfileId, - to: newProfileId, - operations: operations.map(op => ({ id: op.id, type: op.type })), - }); - - let restartedCount = 0; - - for (const op of operations) { - try { - // Stop the operation first if a stop function is provided - if (op.stopFn) { - this.debugLog('Stopping operation before restart:', op.id); - await op.stopFn(); - } - - // Call the restart function - this.debugLog('Restarting operation:', op.id, 'with profile:', newProfileId); - const success = await op.restartFn(newProfileId); - - if (success) { - restartedCount++; - - // Update the profile for operations that weren't re-registered during restart. - // For AgentManager tasks, restartFn may create a NEW object in the Map, - // in which case this update is harmless (updates the new reference). - // For other operations, this ensures the profile is properly updated. - this.updateOperationProfile(op.id, newProfileId, newProfileName); - - // Re-fetch from Map to get the current object (restartFn may have - // re-registered the operation with a new object) - const currentOp = this.operations.get(op.id); - - console.log('[OperationRegistry] Operation restarted successfully:', { - id: op.id, - type: currentOp?.type ?? op.type, - newProfile: newProfileName, - }); - - this.emit('operation-restarted', op.id, oldProfileId, newProfileId); - } else { - console.warn('[OperationRegistry] Operation restart returned false:', op.id); - } - } catch (error) { - console.error('[OperationRegistry] Failed to restart operation:', op.id, error); - } - } - - if (restartedCount > 0) { - this.emit('operations-restarted', restartedCount, oldProfileId, newProfileId); - } - - console.log('[OperationRegistry] Restart complete:', { - total: operations.length, - succeeded: restartedCount, - failed: operations.length - restartedCount, - }); - - return restartedCount; - } - - /** - * Update the profile assignment for an operation (e.g., after restart) - */ - updateOperationProfile(id: string, newProfileId: string, newProfileName: string): void { - const operation = this.operations.get(id); - if (operation) { - const oldProfileId = operation.profileId; - operation.profileId = newProfileId; - operation.profileName = newProfileName; - this.debugLog('Operation profile updated:', { - id, - from: oldProfileId, - to: newProfileId, - }); - this.emit('operation-profile-updated', id, oldProfileId, newProfileId); - } - } - - /** - * Clear all registered operations (for testing or cleanup) - */ - clear(): void { - this.operations.clear(); - this.debugLog('All operations cleared'); - } - - /** - * Type-safe event subscription: operation-registered - * Subscribe to operation registration events - */ - onOperationRegistered(callback: (operation: RegisteredOperation) => void): () => void { - this.on('operation-registered', callback); - return () => this.off('operation-registered', callback); - } - - /** - * Type-safe event subscription: operation-unregistered - * Subscribe to operation unregistration events - */ - onOperationUnregistered(callback: (operationId: string, type: OperationType) => void): () => void { - this.on('operation-unregistered', callback); - return () => this.off('operation-unregistered', callback); - } - - /** - * Type-safe event subscription: operation-restarted - * Subscribe to individual operation restart events - */ - onOperationRestarted(callback: (operationId: string, oldProfileId: string, newProfileId: string) => void): () => void { - this.on('operation-restarted', callback); - return () => this.off('operation-restarted', callback); - } - - /** - * Type-safe event subscription: operations-restarted - * Subscribe to batch operation restart events - */ - onOperationsRestarted(callback: (count: number, oldProfileId: string, newProfileId: string) => void): () => void { - this.on('operations-restarted', callback); - return () => this.off('operations-restarted', callback); - } - - /** - * Type-safe event subscription: operation-profile-updated - * Subscribe to operation profile update events - */ - onOperationProfileUpdated(callback: (operationId: string, oldProfileId: string, newProfileId: string) => void): () => void { - this.on('operation-profile-updated', callback); - return () => this.off('operation-profile-updated', callback); - } -} - -// Singleton instance -let registryInstance: ClaudeOperationRegistry | null = null; - -/** - * Get the singleton ClaudeOperationRegistry instance - */ -export function getOperationRegistry(): ClaudeOperationRegistry { - if (!registryInstance) { - registryInstance = new ClaudeOperationRegistry(); - } - return registryInstance; -} - -/** - * Reset the registry (for testing) - * @internal Test hook - */ -export function resetOperationRegistry(): void { - if (registryInstance) { - registryInstance.clear(); - registryInstance.removeAllListeners(); - } - registryInstance = null; -} diff --git a/src/main/claude-profile/profile-scorer.ts b/src/main/claude-profile/profile-scorer.ts deleted file mode 100644 index a572e6a27e..0000000000 --- a/src/main/claude-profile/profile-scorer.ts +++ /dev/null @@ -1,493 +0,0 @@ -/** - * Profile Scorer Module - * Handles profile availability scoring and auto-switch logic - * - * Selection: - * 1. Accounts are filtered by availability criteria: - * - Must be authenticated - * - Must not be rate-limited (explicit 429 error) - * - Must be below user's configured thresholds (default: 95% session, 99% weekly) - * 2. Among the available ones, the account with the most headroom (lowest usage) wins - * 3. If no profile passes all filters, falls back to the "least bad" option - * - * Unified Account Support - * - Supports both OAuth profiles (ClaudeProfile) and API profiles (APIProfile) - * - API profiles are always considered available (hasUnlimitedUsage = true) - */ - -import type { ClaudeProfile, ClaudeAutoSwitchSettings, APIProfile } from '../../shared/types'; -import type { UnifiedAccount } from '../../shared/types/unified-account'; -import { claudeProfileToUnified, apiProfileToUnified } from '../../shared/utils/unified-account'; -import { isProfileRateLimited } from './rate-limit-manager'; -import { isProfileAuthenticated } from './profile-utils'; - -const isDebug = process.env.DEBUG === 'true'; - -interface ScoredProfile { - profile: ClaudeProfile; - score: number; - isAvailable: boolean; - unavailableReason?: string; -} - -/** - * Check if a profile is available for use based on all criteria - */ -function checkProfileAvailability( - profile: ClaudeProfile, - settings: ClaudeAutoSwitchSettings -): { available: boolean; reason?: string } { - // Check authentication - if (!isProfileAuthenticated(profile)) { - return { available: false, reason: 'not authenticated' }; - } - - // Check explicit rate limit (from 429 errors) - const rateLimitStatus = isProfileRateLimited(profile); - if (rateLimitStatus.limited) { - return { - available: false, - reason: `rate limited (${rateLimitStatus.type}, resets ${rateLimitStatus.resetAt?.toISOString() || 'unknown'})` - }; - } - - // Check usage thresholds - if (profile.usage) { - // Weekly threshold check (more important - longer reset time) - // Using >= to reject profiles AT or ABOVE threshold (e.g., 95% is rejected when threshold is 95%) - // This is intentional: we want to switch proactively BEFORE hitting hard limits - if (profile.usage.weeklyUsagePercent >= settings.weeklyThreshold) { - return { - available: false, - reason: `weekly usage ${profile.usage.weeklyUsagePercent}% >= threshold ${settings.weeklyThreshold}%` - }; - } - - // Session threshold check - // Using >= to reject profiles AT or ABOVE threshold (same rationale as weekly) - if (profile.usage.sessionUsagePercent >= settings.sessionThreshold) { - return { - available: false, - reason: `session usage ${profile.usage.sessionUsagePercent}% >= threshold ${settings.sessionThreshold}%` - }; - } - } - - return { available: true }; -} - -/** - * Calculate a fallback score for when no profiles meet all criteria - * Used to pick the "least bad" option - */ -function calculateFallbackScore( - profile: ClaudeProfile, - settings: ClaudeAutoSwitchSettings -): number { - let score = 100; - const now = new Date(); - - // Authentication is critical - if (!isProfileAuthenticated(profile)) { - score -= 1000; // Unauthenticated is basically unusable - } - - // Rate limit status - const rateLimitStatus = isProfileRateLimited(profile); - if (rateLimitStatus.limited) { - if (rateLimitStatus.type === 'weekly') { - score -= 500; // Weekly limit is worse (longer reset) - } else { - score -= 200; // Session limit resets sooner - } - - // Bonus for profiles that reset sooner - if (rateLimitStatus.resetAt) { - const hoursUntilReset = (rateLimitStatus.resetAt.getTime() - now.getTime()) / (1000 * 60 * 60); - score += Math.max(0, 50 - hoursUntilReset); - } - } - - // Usage penalties (prefer lower usage) - if (profile.usage) { - // Penalize based on how far over threshold - const weeklyOverage = Math.max(0, profile.usage.weeklyUsagePercent - settings.weeklyThreshold); - const sessionOverage = Math.max(0, profile.usage.sessionUsagePercent - settings.sessionThreshold); - - score -= weeklyOverage * 2; // Weekly overage is worse - score -= sessionOverage; - - // Also factor in absolute usage (lower is better) - score -= profile.usage.weeklyUsagePercent * 0.3; - score -= profile.usage.sessionUsagePercent * 0.1; - } - - return score; -} - -// ============================================ -// Unified Account Scoring (v3) -// ============================================ - -interface ScoredUnifiedAccount { - account: UnifiedAccount; - score: number; - isAvailable: boolean; - unavailableReason?: string; -} - -/** - * Options for unified account selection - */ -export interface UnifiedAccountSelectionOptions { - /** Unified account ID to exclude (usually the current/failing one) */ - excludeAccountId?: string; - /** Currently active OAuth profile ID (if any) */ - activeOAuthId?: string; - /** Currently active API profile ID (if any) */ - activeAPIId?: string; -} - -/** - * Score a single unified account for availability - * - * @param account - The unified account to score - * @param settings - Auto-switch settings containing usage thresholds - */ -function scoreUnifiedAccount( - account: UnifiedAccount, - settings: ClaudeAutoSwitchSettings -): ScoredUnifiedAccount { - let score = 100; - let unavailableReason: string | undefined; - let isOverThreshold = false; - - // For API profiles: simple availability check - if (account.type === 'api') { - if (!account.isAuthenticated) { - score = -1000; - unavailableReason = 'API key not validated'; - } else if (!account.isAvailable) { - score = -500; - unavailableReason = 'not available'; - } - // API profiles with valid auth get high scores (no usage limits) - - return { - account, - score, - isAvailable: score > 0, - unavailableReason - }; - } - - // For OAuth profiles: detailed scoring with threshold enforcement - if (!account.isAuthenticated) { - score = -1000; - unavailableReason = 'not authenticated'; - } else if (account.isRateLimited) { - if (account.rateLimitType === 'weekly') { - score = -500; - } else { - score = -200; - } - unavailableReason = `rate limited (${account.rateLimitType || 'unknown'})`; - } else { - // Check usage thresholds (matching checkProfileAvailability behavior) - if (account.weeklyPercent !== undefined && account.weeklyPercent >= settings.weeklyThreshold) { - isOverThreshold = true; - unavailableReason = `weekly usage ${account.weeklyPercent}% >= threshold ${settings.weeklyThreshold}%`; - } else if (account.sessionPercent !== undefined && account.sessionPercent >= settings.sessionThreshold) { - isOverThreshold = true; - unavailableReason = `session usage ${account.sessionPercent}% >= threshold ${settings.sessionThreshold}%`; - } - - // Apply proportional penalties for high usage (even if not over threshold) - if (account.weeklyPercent !== undefined) { - score -= account.weeklyPercent * 0.3; - } - if (account.sessionPercent !== undefined) { - score -= account.sessionPercent * 0.1; - } - } - - return { - account, - score, - isAvailable: score > 0 && account.isAuthenticated === true && !account.isRateLimited && !isOverThreshold, - unavailableReason - }; -} - -/** - * Get the best unified account from both OAuth and API profiles - * - * Selection Logic: - * 1. Convert all profiles to UnifiedAccount format - * 2. Score each by availability and usage - * 3. Return the available account with the best score - * 4. If none available, return the "least bad" option - * - * @param oauthProfiles - All OAuth (Claude) profiles - * @param apiProfiles - All API profiles - * @param settings - Auto-switch settings (contains thresholds for OAuth) - * @param options - Optional configuration for selection - */ -export function getBestAvailableUnifiedAccount( - oauthProfiles: ClaudeProfile[], - apiProfiles: APIProfile[], - settings: ClaudeAutoSwitchSettings, - options: UnifiedAccountSelectionOptions = {} -): UnifiedAccount | null { - const { excludeAccountId, activeOAuthId, activeAPIId } = options; - // Convert all profiles to unified format - const unifiedAccounts: UnifiedAccount[] = []; - - // Convert OAuth profiles - for (const profile of oauthProfiles) { - const isActive = profile.id === activeOAuthId; - const rateLimitStatus = isProfileRateLimited(profile); - // Compute authentication status - profile.isAuthenticated may not be set on raw profiles - const isAuthenticated = isProfileAuthenticated(profile); - - unifiedAccounts.push(claudeProfileToUnified(profile, isActive, { - isRateLimited: rateLimitStatus.limited, - rateLimitType: rateLimitStatus.type, - isAuthenticated - })); - } - - // Convert API profiles - for (const profile of apiProfiles) { - const isActive = profile.id === activeAPIId; - // TODO: API profiles are considered authenticated if they have an API key. - // Add validation tracking to distinguish "has key" from "key is confirmed valid". - const isAuthenticated = !!profile.apiKey; - unifiedAccounts.push(apiProfileToUnified(profile, isActive, isAuthenticated)); - } - - // Filter out excluded account - const candidates = unifiedAccounts.filter(a => a.id !== excludeAccountId); - - if (candidates.length === 0) { - return null; - } - - if (isDebug) { - console.warn('[ProfileScorer] Evaluating', candidates.length, 'candidate accounts (excluding:', excludeAccountId, ')'); - console.warn('[ProfileScorer] OAuth thresholds: session =', settings.sessionThreshold, '%, weekly =', settings.weeklyThreshold, '%'); - } - - // Score and check availability for each account - const scoredAccounts: ScoredUnifiedAccount[] = candidates.map(account => { - const scored = scoreUnifiedAccount(account, settings); - - if (isDebug) { - console.warn('[ProfileScorer] Scoring account:', account.displayName, '(', account.id, ')'); - console.warn('[ProfileScorer] Type:', account.type); - console.warn('[ProfileScorer] Available:', scored.isAvailable, scored.unavailableReason ? `(${scored.unavailableReason})` : ''); - if (account.type === 'oauth') { - console.warn('[ProfileScorer] Usage:', `session=${account.sessionPercent}%, weekly=${account.weeklyPercent}%`); - } - console.warn('[ProfileScorer] Score:', scored.score); - } - - return scored; - }); - - // Available accounts first, then the higher score (lower usage; for unavailable ones, the - // "least bad") - scoredAccounts.sort((a, b) => { - if (a.isAvailable !== b.isAvailable) { - return a.isAvailable ? -1 : 1; - } - return b.score - a.score; - }); - - const best = scoredAccounts[0]; - - if (best.isAvailable) { - if (isDebug) { - console.warn('[ProfileScorer] Best available account:', best.account.displayName, - '(type:', best.account.type, ', score:', best.score, ')'); - } - return best.account; - } - - // No account meets all criteria - check if we should return the least bad option - if (best.score > 0) { - if (isDebug) { - console.warn('[ProfileScorer] No ideal account available, using least-bad option:', best.account.displayName, - '(type:', best.account.type, ', score:', best.score, ', reason:', best.unavailableReason, ')'); - } - return best.account; - } - - // All accounts are truly unusable - if (isDebug) { - console.warn('[ProfileScorer] No usable account available, all have issues'); - } - return null; -} - -/** - * Get the best profile to switch to based on availability and usage - * - * Selection Logic: - * 1. Filter to candidates (excluding the current profile) - * 2. Check each profile's availability (auth, rate limit, thresholds) - * 3. Return the available profile with the most headroom (lowest usage) - * 4. If none available, return the "least bad" option based on fallback scoring - * - * @param profiles - All Claude profiles - * @param settings - Auto-switch settings (contains thresholds) - * @param excludeProfileId - Profile ID to exclude (usually the current/failing one) - */ -export function getBestAvailableProfile( - profiles: ClaudeProfile[], - settings: ClaudeAutoSwitchSettings, - excludeProfileId?: string -): ClaudeProfile | null { - // Get all profiles except the excluded one - const candidates = profiles.filter(p => p.id !== excludeProfileId); - - if (candidates.length === 0) { - return null; - } - - if (isDebug) { - console.warn('[ProfileScorer] Evaluating', candidates.length, 'candidate profiles (excluding:', excludeProfileId, ')'); - console.warn('[ProfileScorer] Thresholds: session =', settings.sessionThreshold, '%, weekly =', settings.weeklyThreshold, '%'); - } - - // Score and check availability for each profile - const scoredProfiles: ScoredProfile[] = candidates.map(profile => { - const availability = checkProfileAvailability(profile, settings); - const fallbackScore = calculateFallbackScore(profile, settings); - - if (isDebug) { - console.warn('[ProfileScorer] Scoring profile:', profile.name, '(', profile.id, ')'); - console.warn('[ProfileScorer] Available:', availability.available, availability.reason ? `(${availability.reason})` : ''); - console.warn('[ProfileScorer] Usage:', profile.usage ? `session=${profile.usage.sessionUsagePercent}%, weekly=${profile.usage.weeklyUsagePercent}%` : 'unknown'); - console.warn('[ProfileScorer] Fallback score:', fallbackScore); - } - - return { - profile, - score: fallbackScore, - isAvailable: availability.available, - unavailableReason: availability.reason - }; - }); - - // Available profiles first, then the higher fallback score (lower usage; for unavailable - // ones, the "least bad") - scoredProfiles.sort((a, b) => { - if (a.isAvailable !== b.isAvailable) { - return a.isAvailable ? -1 : 1; - } - return b.score - a.score; - }); - - const best = scoredProfiles[0]; - - if (best.isAvailable) { - console.warn('[ProfileScorer] Best available profile:', best.profile.name, '(score:', best.score, ')'); - return best.profile; - } - - // No profile meets all criteria - check if we should return the least bad option - // Only return if it has a positive score (meaning it might still work) - if (best.score > 0) { - console.warn('[ProfileScorer] No ideal profile available, using least-bad option:', best.profile.name, - '(score:', best.score, ', reason:', best.unavailableReason, ')'); - return best.profile; - } - - // All profiles are truly unusable - console.warn('[ProfileScorer] No usable profile available, all have issues'); - return null; -} - -/** - * Determine if we should proactively switch profiles based on current usage - */ -export function shouldProactivelySwitch( - profile: ClaudeProfile, - allProfiles: ClaudeProfile[], - settings: ClaudeAutoSwitchSettings -): { shouldSwitch: boolean; reason?: string; suggestedProfile?: ClaudeProfile } { - if (!settings.enabled) { - return { shouldSwitch: false }; - } - - if (!profile?.usage) { - return { shouldSwitch: false }; - } - - const usage = profile.usage; - - // Check if we're approaching limits - if (usage.weeklyUsagePercent >= settings.weeklyThreshold) { - const bestProfile = getBestAvailableProfile(allProfiles, settings, profile.id); - if (bestProfile) { - return { - shouldSwitch: true, - reason: `Weekly usage at ${usage.weeklyUsagePercent}% (threshold: ${settings.weeklyThreshold}%)`, - suggestedProfile: bestProfile - }; - } - } - - if (usage.sessionUsagePercent >= settings.sessionThreshold) { - const bestProfile = getBestAvailableProfile(allProfiles, settings, profile.id); - if (bestProfile) { - return { - shouldSwitch: true, - reason: `Session usage at ${usage.sessionUsagePercent}% (threshold: ${settings.sessionThreshold}%)`, - suggestedProfile: bestProfile - }; - } - } - - return { shouldSwitch: false }; -} - -/** - * Get profiles sorted by availability (best first) - */ -export function getProfilesSortedByAvailability(profiles: ClaudeProfile[]): ClaudeProfile[] { - return [...profiles].sort((a, b) => { - // Authenticated profiles first - const aAuth = isProfileAuthenticated(a); - const bAuth = isProfileAuthenticated(b); - if (aAuth !== bAuth) { - return aAuth ? -1 : 1; - } - - // Not rate-limited profiles first - const aLimited = isProfileRateLimited(a); - const bLimited = isProfileRateLimited(b); - - if (aLimited.limited !== bLimited.limited) { - return aLimited.limited ? 1 : -1; - } - - // If both limited, sort by reset time - if (aLimited.limited && bLimited.limited && aLimited.resetAt && bLimited.resetAt) { - return aLimited.resetAt.getTime() - bLimited.resetAt.getTime(); - } - - // Sort by lower weekly usage - const aWeekly = a.usage?.weeklyUsagePercent ?? 0; - const bWeekly = b.usage?.weeklyUsagePercent ?? 0; - if (aWeekly !== bWeekly) { - return aWeekly - bWeekly; - } - - // Sort by lower session usage - const aSession = a.usage?.sessionUsagePercent ?? 0; - const bSession = b.usage?.sessionUsagePercent ?? 0; - return aSession - bSession; - }); -} diff --git a/src/main/claude-profile/profile-storage.ts b/src/main/claude-profile/profile-storage.ts index 89bb406184..ca08028e1e 100644 --- a/src/main/claude-profile/profile-storage.ts +++ b/src/main/claude-profile/profile-storage.ts @@ -7,7 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'; import { readFile } from 'fs/promises'; import { join } from 'path'; import { expandClaudeHome, joinClaudeHome } from '../platform/claude-home'; -import type { ClaudeProfile, ClaudeAutoSwitchSettings } from '../../shared/types'; +import type { ClaudeProfile } from '../../shared/types'; /** Claude Code's default ~/.claude (in the Linux home when Claude Code runs in WSL) */ const getDefaultClaudeConfigDir = () => joinClaudeHome('.claude'); @@ -16,19 +16,6 @@ const getClaudeProfilesDir = () => joinClaudeHome('.claude-profiles'); const STORE_VERSION = 3; // Bumped for encrypted token storage -/** - * Default auto-switch settings - */ -export const DEFAULT_AUTO_SWITCH_SETTINGS: ClaudeAutoSwitchSettings = { - enabled: false, - proactiveSwapEnabled: false, // Proactive monitoring disabled by default - sessionThreshold: 95, // Consider switching at 95% session usage - weeklyThreshold: 99, // Consider switching at 99% weekly usage - autoSwitchOnRateLimit: false, // Prompt user by default - autoSwitchOnAuthFailure: false, // Prompt user by default on auth failures - usageCheckInterval: 30000 // Check every 30s when enabled (0 = disabled) -}; - /** * Internal storage format for Claude profiles */ @@ -36,7 +23,6 @@ export interface ProfileStoreData { version: number; profiles: ClaudeProfile[]; activeProfileId: string; - autoSwitch?: ClaudeAutoSwitchSettings; /** * Profile IDs that were migrated from shared ~/.claude to isolated directories. * These profiles need re-authentication since their credentials are in the old location. @@ -135,11 +121,13 @@ function migrateProfileToIsolatedDirectory(profile: ClaudeProfile): string { * Shared helper used by both sync and async loaders. */ function parseAndMigrateProfileData(data: Record): ProfileStoreData | null { + // Automatic account switching was removed: stores saved before keep its settings, dropped here + delete data.autoSwitch; + // Handle version migration if (data.version === 1) { // Migrate v1 to v2: add usage and rateLimitEvents fields data.version = STORE_VERSION; - data.autoSwitch = DEFAULT_AUTO_SWITCH_SETTINGS; } if (data.version === STORE_VERSION) { diff --git a/src/main/claude-profile/profile-utils.ts b/src/main/claude-profile/profile-utils.ts index c81e4fc4c0..5b7c51c7de 100644 --- a/src/main/claude-profile/profile-utils.ts +++ b/src/main/claude-profile/profile-utils.ts @@ -69,7 +69,7 @@ export function isProfileAuthenticated(profile: ClaudeProfile): boolean { } // Check for direct OAuth token first (OAuth-only profiles without configDir) - // This enables auto-switch to work with profiles that only have oauthToken set + // (profiles that only have oauthToken set) if (hasValidToken(profile)) { return true; } diff --git a/src/main/claude-profile/usage-monitor.test.ts b/src/main/claude-profile/usage-monitor.test.ts index 24297e0030..badc2c4196 100644 --- a/src/main/claude-profile/usage-monitor.test.ts +++ b/src/main/claude-profile/usage-monitor.test.ts @@ -12,13 +12,6 @@ import { hasHardcodedText } from '../../shared/utils/format-time'; // Mock getClaudeProfileManager vi.mock('../claude-profile-manager', () => ({ getClaudeProfileManager: vi.fn(() => ({ - getAutoSwitchSettings: vi.fn(() => ({ - enabled: true, - proactiveSwapEnabled: true, - usageCheckInterval: 30000, - sessionThreshold: 80, - weeklyThreshold: 80 - })), getActiveProfile: vi.fn(() => ({ id: 'test-profile-1', name: 'Test Profile', @@ -31,10 +24,6 @@ vi.mock('../claude-profile-manager', () => ({ baseUrl: 'https://api.anthropic.com', oauthToken: 'mock-oauth-token' })), - getProfilesSortedByAvailability: vi.fn(() => [ - { id: 'profile-2', name: 'Profile 2' }, - { id: 'profile-3', name: 'Profile 3' } - ]), setActiveProfile: vi.fn(), hasValidAuth: vi.fn(() => true), getProfileToken: vi.fn(() => 'mock-decrypted-token') @@ -170,7 +159,7 @@ describe('usage-monitor', () => { expect(monitor1).toBe(monitor2); }); - it('should start monitoring when settings allow', () => { + it('should start monitoring', () => { const monitor = getUsageMonitor(); monitor.start(); @@ -257,29 +246,6 @@ describe('usage-monitor', () => { }); }); - describe('UsageMonitor error handling', () => { - it('should emit event when swap fails', () => { - const monitor = getUsageMonitor(); - const swapFailedHandler = vi.fn(); - - monitor.on('proactive-swap-failed', swapFailedHandler); - - // Manually trigger the swap logic by calling the private method through a test scenario - // Since we can't directly call private methods, we'll verify the event system works - monitor.emit('proactive-swap-failed', { - reason: 'no_alternative', - currentProfile: 'test-profile' - }); - - expect(swapFailedHandler).toHaveBeenCalledWith({ - reason: 'no_alternative', - currentProfile: 'test-profile' - }); - - monitor.off('proactive-swap-failed', swapFailedHandler); - }); - }); - describe('Anthropic response normalization', () => { it('should normalize Anthropic response with utilization values', () => { const monitor = getUsageMonitor(); @@ -904,25 +870,17 @@ describe('usage-monitor', () => { // Mock to return null for active profile mockGetManager.mockReturnValueOnce({ - getAutoSwitchSettings: vi.fn(() => ({ - enabled: true, - proactiveSwapEnabled: true, - usageCheckInterval: 30000, - sessionThreshold: 80, - weeklyThreshold: 80 - })), getActiveProfile: vi.fn(() => null), // Return null getProfile: vi.fn(() => null), - getProfilesSortedByAvailability: vi.fn(() => []), setActiveProfile: vi.fn(), getProfileToken: vi.fn(() => null) } as any); const monitor = getUsageMonitor(); - // Call checkUsageAndSwap directly to test null profile handling + // Call checkUsage directly to test null profile handling // Should complete without throwing an error - await expect(monitor['checkUsageAndSwap']()).resolves.toBeUndefined(); + await expect(monitor['checkUsage']()).resolves.toBeUndefined(); }); it('should handle profile with missing required fields', async () => { @@ -1049,10 +1007,10 @@ describe('usage-monitor', () => { const monitor = getUsageMonitor(); // Start first check (it will take some time) - const firstCheck = monitor['checkUsageAndSwap'](); + const firstCheck = monitor['checkUsage'](); // Try to start second check immediately (should be ignored) - const secondCheck = monitor['checkUsageAndSwap'](); + const secondCheck = monitor['checkUsage'](); // Both should resolve await firstCheck; @@ -1065,89 +1023,6 @@ describe('usage-monitor', () => { describe('backward compatibility', () => { - describe('Settings backward compatibility', () => { - it('should handle settings with missing optional fields', async () => { - // Get the mocked getClaudeProfileManager function - const { getClaudeProfileManager } = await import('../claude-profile-manager'); - const mockGetManager = vi.mocked(getClaudeProfileManager); - - // Mock settings with missing optional fields - mockGetManager.mockReturnValueOnce({ - getAutoSwitchSettings: vi.fn(() => ({ - enabled: true, - proactiveSwapEnabled: true - // Missing: usageCheckInterval, sessionThreshold, weeklyThreshold - })), - getActiveProfile: vi.fn(() => ({ - id: 'test-profile-1', - name: 'Test Profile', - baseUrl: 'https://api.anthropic.com', - oauthToken: 'mock-oauth-token' - })), - getProfile: vi.fn(() => ({ - id: 'test-profile-1', - name: 'Test Profile', - baseUrl: 'https://api.anthropic.com', - oauthToken: 'mock-oauth-token' - })), - getProfilesSortedByAvailability: vi.fn(() => []), - setActiveProfile: vi.fn(), - getProfileToken: vi.fn(() => 'mock-decrypted-token') - } as any); - - const monitor = getUsageMonitor(); - - // Should start with default values for missing fields - monitor.start(); - - // Should have started monitoring - expect(monitor['intervalId']).not.toBeNull(); - - monitor.stop(); - }); - - it('should use default thresholds when not specified in settings', async () => { - // Get the mocked getClaudeProfileManager function - const { getClaudeProfileManager } = await import('../claude-profile-manager'); - const mockGetManager = vi.mocked(getClaudeProfileManager); - - // Mock settings without thresholds - mockGetManager.mockReturnValueOnce({ - getAutoSwitchSettings: vi.fn(() => ({ - enabled: true, - proactiveSwapEnabled: true, - usageCheckInterval: 30000 - // Missing: sessionThreshold, weeklyThreshold - })), - getActiveProfile: vi.fn(() => ({ - id: 'test-profile-1', - name: 'Test Profile', - baseUrl: 'https://api.anthropic.com', - oauthToken: 'mock-oauth-token' - })), - getProfile: vi.fn(() => ({ - id: 'test-profile-1', - name: 'Test Profile', - baseUrl: 'https://api.anthropic.com', - oauthToken: 'mock-oauth-token' - })), - getProfilesSortedByAvailability: vi.fn(() => []), - setActiveProfile: vi.fn(), - getProfileToken: vi.fn(() => 'mock-decrypted-token') - } as any); - - const monitor = getUsageMonitor(); - - // Should not crash when checking thresholds - monitor.start(); - - // Should have started successfully - expect(monitor['intervalId']).not.toBeNull(); - - monitor.stop(); - }); - }); - describe('Anthropic response format backward compatibility', () => { it('should handle legacy Anthropic response format', () => { const monitor = getUsageMonitor(); @@ -1617,7 +1492,7 @@ describe('usage-monitor', () => { const monitor = getUsageMonitor(); - // Pre-determined active profile (simulating profile at time of checkUsageAndSwap) + // Pre-determined active profile (simulating profile at time of checkUsage) const predeterminedProfile = { isAPIProfile: true, profileId: 'api-profile-1', diff --git a/src/main/claude-profile/usage-monitor.ts b/src/main/claude-profile/usage-monitor.ts index ffd6240789..85297e9931 100644 --- a/src/main/claude-profile/usage-monitor.ts +++ b/src/main/claude-profile/usage-monitor.ts @@ -1,8 +1,8 @@ /** - * Usage Monitor - Proactive usage monitoring and account switching + * Usage Monitor - Claude account usage monitoring * - * Monitors Claude account usage at configured intervals and automatically - * switches to alternative accounts before hitting rate limits. + * Fetches the usage of the account in use (and the other accounts, less often) for the usage + * badge and the accounts list. It never switches accounts. * * Uses hybrid approach: * 1. Primary: Direct OAuth API (https://api.anthropic.com/api/oauth/usage) @@ -19,7 +19,6 @@ import { detectProvider as sharedDetectProvider, type ApiProvider } from '../../ import { getCredentialsFromKeychain, clearKeychainCache } from './credential-utils'; import { reactiveTokenRefresh, ensureValidToken } from './token-refresh'; import { isProfileRateLimited } from './rate-limit-manager'; -import { getOperationRegistry } from './operation-registry'; import { usesClaudeSubscription } from './profile-utils'; import { appLog } from '../app-logger'; @@ -219,10 +218,6 @@ export class UsageMonitor extends EventEmitter { private apiFailureTimestamps: Map = new Map(); private static API_FAILURE_COOLDOWN_MS = 2 * 60 * 1000; // 2 minutes cooldown before API retry - // Swap loop protection: track profiles that recently failed auth - private authFailedProfiles: Map = new Map(); // profileId -> timestamp - private static AUTH_FAILURE_COOLDOWN_MS = 5 * 60 * 1000; // 5 minutes cooldown - // Track profiles that need re-authentication (invalid refresh token) // These profiles have permanent auth failures that require manual re-auth private needsReauthProfiles: Set = new Set(); @@ -231,6 +226,7 @@ export class UsageMonitor extends EventEmitter { // Map private allProfilesUsageCache: Map = new Map(); private static PROFILE_USAGE_CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes cache for inactive profiles + private static USAGE_CHECK_INTERVAL_MS = 60 * 1000; // 60 seconds for active profile polling // Request coalescing: track in-flight getAllProfilesUsage() promise to avoid parallel duplicate fetches private allProfilesUsageInflight: Promise | null = null; @@ -286,7 +282,6 @@ export class UsageMonitor extends EventEmitter { * Start monitoring usage at configured interval * * Note: Usage monitoring always runs to display the usage badge. - * Proactive account swapping only occurs if enabled in settings. * * Update interval: 60 seconds (60000ms) for active profile; inactive profiles every 5 minutes (adaptive: 60s when usage is high) */ @@ -297,22 +292,21 @@ export class UsageMonitor extends EventEmitter { } const profileManager = getClaudeProfileManager(); - const settings = profileManager.getAutoSwitchSettings(); - const interval = settings.usageCheckInterval || 60000; // 60 seconds for active profile polling + const interval = UsageMonitor.USAGE_CHECK_INTERVAL_MS; this.debugLog('[UsageMonitor] Starting with interval: ' + interval + ' ms (60-second updates for active profile usage stats)'); - // Every way of switching accounts (Settings, swaps, terminals) goes through the profile manager + // Every way of switching accounts (Settings, terminals) goes through the profile manager this.unsubscribeActiveProfile = profileManager.onActiveProfileChanged?.((profileId) => { this.handleActiveProfileChanged(profileId); }) ?? null; // Check immediately - this.checkUsageAndSwap(); + this.checkUsage(); // Then check periodically this.intervalId = setInterval(() => { - this.checkUsageAndSwap(); + this.checkUsage(); }, interval); } @@ -332,8 +326,7 @@ export class UsageMonitor extends EventEmitter { /** * The account in use changed: show the new account's stored usage right away (or nothing, so * the badge waits for it, when it was never fetched) instead of the previous account's, then - * fetch its usage in the background. The swap check is skipped for that refresh, so two - * accounts over their limits don't swap back and forth; the regular interval does that. + * fetch its usage in the background. */ handleActiveProfileChanged(profileId: string): void { this.activeProfileGeneration++; @@ -351,13 +344,13 @@ export class UsageMonitor extends EventEmitter { this.refreshUsage(); } - /** Fetch the active account's usage now without the swap check (queued behind a running check) */ + /** Fetch the active account's usage now (queued behind a running check) */ private refreshUsage(): void { if (this.isChecking) { this.recheckPending = true; return; } - this.checkUsageAndSwap({ allowSwap: false }).catch(error => { + this.checkUsage().catch(error => { appLog.error('[UsageMonitor] Usage refresh failed:', error); }); } @@ -455,34 +448,13 @@ export class UsageMonitor extends EventEmitter { }); } - /** - * Clear a profile from the auth-failed list. - * Called after successful re-authentication to allow the profile to be used again. - * - * @param profileId - Profile identifier to clear from failed list - */ - clearAuthFailedProfile(profileId: string): void { - const wasInFailedList = this.authFailedProfiles.has(profileId); - const wasNeedsReauth = this.needsReauthProfiles.has(profileId); - this.authFailedProfiles.delete(profileId); - this.needsReauthProfiles.delete(profileId); - this.clearProfileUsageCache(profileId); - - if (wasInFailedList || wasNeedsReauth) { - this.debugLog('[UsageMonitor] Cleared auth failure status for profile: ' + profileId, { - wasInFailedList, - wasNeedsReauth - }); - } - } - /** * Trigger an immediate usage check. * Called after re-authentication to give the user immediate feedback. */ checkNow(): void { this.debugLog('[UsageMonitor] Immediate check triggered'); - this.checkUsageAndSwap().catch(error => { + this.checkUsage().catch(error => { console.error('[UsageMonitor] Immediate check failed:', error); }); } @@ -570,14 +542,7 @@ export class UsageMonitor extends EventEmitter { const profilesToFetch: ProfileToFetch[] = []; const profileResults: (ProfileUsageSummary | null)[] = new Array(settings.profiles.length).fill(null); - // Adaptive cache TTL: when active profile usage is high, refresh inactive profiles more - // frequently (every 60s instead of 5min) because we may need to swap soon - const activeUsageHigh = this.currentUsage - ? (this.currentUsage.sessionPercent > 80 || this.currentUsage.weeklyPercent > 90) - : false; - const effectiveCacheTtl = activeUsageHigh - ? 60 * 1000 // 60s when usage is high (swap-ready mode) - : UsageMonitor.PROFILE_USAGE_CACHE_TTL_MS; // 5 min normally + const effectiveCacheTtl = UsageMonitor.PROFILE_USAGE_CACHE_TTL_MS; for (let i = 0; i < settings.profiles.length; i++) { const profile = settings.profiles[i]; @@ -1036,14 +1001,12 @@ export class UsageMonitor extends EventEmitter { } /** - * Check usage and trigger swap if thresholds exceeded + * Fetch the account in use's usage (and the accounts list) and emit it for the UI * - * Refactored to use helper methods for better maintainability: * - determineActiveProfile(): Detects API vs OAuth profile - * - checkThresholdsExceeded(): Evaluates usage against thresholds - * - handleAuthFailure(): Manages auth failure recovery + * - handleAuthFailure(): Manages auth failure recovery (token refresh) */ - private async checkUsageAndSwap({ allowSwap = true }: { allowSwap?: boolean } = {}): Promise { + private async checkUsage(): Promise { if (this.isChecking) { return; // Prevent concurrent checks } @@ -1086,7 +1049,7 @@ export class UsageMonitor extends EventEmitter { const profileManager = getClaudeProfileManager(); profileManager.updateProfileUsageFromAPI(profileId, usage.sessionPercent, usage.weeklyPercent); - // Step 3: Emit usage update for UI (always emit, regardless of proactive swap settings) + // Step 3: Emit usage update for UI this.emit('usage-updated', usage); // Step 3.5: Emit all profiles usage for multi-profile display @@ -1102,51 +1065,8 @@ export class UsageMonitor extends EventEmitter { console.warn(`[UsageMonitor] Usage: ${summary}`); } } - - // Step 4: Check thresholds and perform proactive swap (OAuth profiles only) - if (!allowSwap) return; - if (!isAPIProfile) { - const profileManager = getClaudeProfileManager(); - const settings = profileManager.getAutoSwitchSettings(); - - if (!settings.enabled || !settings.proactiveSwapEnabled) { - this.traceLog('[UsageMonitor:TRACE] Proactive swap disabled, skipping threshold check'); - return; - } - - const thresholds = this.checkThresholdsExceeded(usage, settings); - - if (thresholds.anyExceeded) { - this.traceLog('[UsageMonitor:TRACE] Threshold exceeded', { - sessionPercent: usage.sessionPercent, - weekPercent: usage.weeklyPercent, - activeProfile: profileId, - hasCredential: !!activeProfile.credential - }); - - this.debugLog('[UsageMonitor] Threshold exceeded:', { - sessionPercent: usage.sessionPercent, - sessionThreshold: settings.sessionThreshold ?? 95, - weeklyPercent: usage.weeklyPercent, - weeklyThreshold: settings.weeklyThreshold ?? 99 - }); - - // Attempt proactive swap - await this.performProactiveSwap( - profileId, - thresholds.sessionExceeded ? 'session' : 'weekly' - ); - } else { - this.traceLog('[UsageMonitor:TRACE] Usage OK', { - sessionPercent: usage.sessionPercent, - weekPercent: usage.weeklyPercent - }); - } - } else { - this.traceLog('[UsageMonitor:TRACE] Skipping proactive swap for API profile (only supported for OAuth profiles)'); - } } catch (error) { - // Step 5: Handle auth failures + // Step 4: Handle auth failures if (isHttpError(error) && (error.statusCode === 401 || error.statusCode === 403)) { if (profileId) { await this.handleAuthFailure(profileId, isAPIProfile); @@ -1306,29 +1226,8 @@ export class UsageMonitor extends EventEmitter { } /** - * Check if thresholds are exceeded for proactive swapping - * - * @param usage - Current usage snapshot - * @param settings - Auto-switch settings - * @returns Object indicating which thresholds are exceeded - */ - private checkThresholdsExceeded( - usage: ClaudeUsageSnapshot, - settings: { sessionThreshold?: number; weeklyThreshold?: number } - ): { sessionExceeded: boolean; weeklyExceeded: boolean; anyExceeded: boolean } { - const sessionExceeded = usage.sessionPercent >= (settings.sessionThreshold ?? 95); - const weeklyExceeded = usage.weeklyPercent >= (settings.weeklyThreshold ?? 99); - - return { - sessionExceeded, - weeklyExceeded, - anyExceeded: sessionExceeded || weeklyExceeded - }; - } - - /** - * Handle auth failure by attempting token refresh, then marking profile as failed - * and attempting proactive swap if refresh fails. + * Handle auth failure by attempting token refresh (the account stays in use; one whose + * refresh token is invalid is marked as needing re-authentication). * * @param profileId - Profile that failed auth * @param isAPIProfile - Whether this is an API profile (token refresh only for OAuth) @@ -1384,39 +1283,6 @@ export class UsageMonitor extends EventEmitter { clearKeychainCache(profile.configDir); } } - - // Mark this profile as auth-failed to prevent swap loops - // This MUST happen before the early return to prevent infinite loops - this.authFailedProfiles.set(profileId, Date.now()); - this.debugLog('[UsageMonitor] Auth failure detected, marked profile as failed: ' + profileId); - - // Clean up expired entries from the failed profiles map - const now = Date.now(); - this.authFailedProfiles.forEach((timestamp, failedProfileId) => { - if (now - timestamp > UsageMonitor.AUTH_FAILURE_COOLDOWN_MS) { - this.authFailedProfiles.delete(failedProfileId); - } - }); - - const settings = profileManager.getAutoSwitchSettings(); - - // Proactive swap is only supported for OAuth profiles, not API profiles - if (isAPIProfile || !settings.enabled || !settings.proactiveSwapEnabled) { - this.debugLog('[UsageMonitor] Auth failure detected but proactive swap is disabled or using API profile, skipping swap'); - return; - } - - try { - const excludeProfiles = Array.from(this.authFailedProfiles.keys()); - this.debugLog('[UsageMonitor] Attempting proactive swap (excluding failed profiles):', excludeProfiles); - await this.performProactiveSwap( - profileId, - 'session', // Treat auth failure as session limit for immediate swap - excludeProfiles - ); - } catch (swapError) { - console.error('[UsageMonitor] Failed to perform auth-failure swap:', swapError); - } } /** @@ -1819,7 +1685,7 @@ export class UsageMonitor extends EventEmitter { return normalizedUsage; } catch (error: any) { - // Re-throw auth failures to be handled by checkUsageAndSwap + // Re-throw auth failures to be handled by checkUsage // This includes both status code auth failures (401/403) and body-detected failures if (error?.message?.includes('Auth Failure') || error?.statusCode === 401 || error?.statusCode === 403) { throw error; @@ -2148,178 +2014,6 @@ export class UsageMonitor extends EventEmitter { // The API method handles all cases; this fallback path is expected when API is rate-limited or unavailable. return null; } - - /** - * Perform proactive profile swap - * @param currentProfileId - The profile to switch from - * @param limitType - The type of limit that triggered the swap - * @param additionalExclusions - Additional profile IDs to exclude (e.g., auth-failed profiles) - */ - private async performProactiveSwap( - currentProfileId: string, - limitType: 'session' | 'weekly', - additionalExclusions: string[] = [] - ): Promise { - const profileManager = getClaudeProfileManager(); - const excludeIds = new Set([currentProfileId, ...additionalExclusions]); - - // Build unified list of available accounts - type UnifiedSwapTarget = { - id: string; - name: string; - type: 'oauth' | 'api'; - }; - - const unifiedAccounts: UnifiedSwapTarget[] = []; - - // Add OAuth profiles (sorted by availability) - const oauthProfiles = profileManager.getProfilesSortedByAvailability(); - for (const profile of oauthProfiles) { - // Never swap to an account without credentials (e.g. a sign-in that never finished) - if (!excludeIds.has(profile.id) && profileManager.hasValidAuth(profile.id)) { - unifiedAccounts.push({ - id: profile.id, - name: profile.name, - type: 'oauth' - }); - } - } - - // Add API profiles (always considered available since they have unlimited usage) - try { - const profilesFile = await loadProfilesFile(); - for (const apiProfile of profilesFile.profiles) { - if (!excludeIds.has(apiProfile.id) && apiProfile.apiKey) { - unifiedAccounts.push({ - id: apiProfile.id, - name: apiProfile.name, - type: 'api' - }); - } - } - } catch (error) { - this.debugLog('[UsageMonitor] Failed to load API profiles for swap:', error); - } - - if (unifiedAccounts.length === 0) { - this.debugLog('[UsageMonitor] No alternative profile for proactive swap (excluded:', Array.from(excludeIds)); - this.emit('proactive-swap-failed', { - reason: additionalExclusions.length > 0 ? 'all_alternatives_failed_auth' : 'no_alternative', - currentProfile: currentProfileId, - excludedProfiles: Array.from(excludeIds) - }); - return; - } - - // Claude accounts (already sorted by availability) come before API profiles - const bestAccount = unifiedAccounts.find((account) => account.type === 'oauth') ?? unifiedAccounts[0]; - - this.debugLog('[UsageMonitor] Proactive swap:', { - from: currentProfileId, - to: bestAccount.id, - toType: bestAccount.type, - reason: limitType - }); - - // Clear cache for the profile that's becoming inactive - // This ensures the next fetch gets fresh data instead of stale cached values - this.clearProfileUsageCache(currentProfileId); - - // Switch to the new profile - // Note: bestAccount.id is already the raw profile ID (not unified format) - const rawProfileId = bestAccount.id; - - if (bestAccount.type === 'oauth') { - // Switch OAuth profile via profile manager - profileManager.setActiveProfile(rawProfileId); - } else { - // Switch API profile via profile-manager service - try { - const { setActiveAPIProfile } = await import('../services/profile/profile-manager'); - await setActiveAPIProfile(rawProfileId); - } catch (error) { - console.error('[UsageMonitor] Failed to set active API profile:', error); - return; - } - } - - // Get the "from" profile name - let fromProfileName: string | undefined; - const fromOAuthProfile = profileManager.getProfile(currentProfileId); - if (fromOAuthProfile) { - fromProfileName = fromOAuthProfile.name; - } else { - // It might be an API profile - try { - const profilesFile = await loadProfilesFile(); - const fromAPIProfile = profilesFile.profiles.find(p => p.id === currentProfileId); - if (fromAPIProfile) { - fromProfileName = fromAPIProfile.name; - } - } catch { - // Ignore - } - } - - // Emit swap event - this.emit('proactive-swap-completed', { - fromProfile: { id: currentProfileId, name: fromProfileName }, - toProfile: { id: bestAccount.id, name: bestAccount.name }, - limitType, - timestamp: new Date() - }); - - // Notify UI - this.emit('show-swap-notification', { - fromProfile: fromProfileName, - toProfile: bestAccount.name, - reason: 'proactive', - limitType - }); - - // PROACTIVE OPERATION RESTART: Stop and restart all running Claude SDK operations with new profile credentials - // This includes autonomous tasks, MR reviews, insights, etc. - // Claude Agent SDK sessions maintain state independently of auth tokens, so no progress is lost - const operationRegistry = getOperationRegistry(); - const operationSummary = operationRegistry.getSummary(); - const operationIdsOnOldProfile = operationSummary.byProfile[currentProfileId] || []; - - // Always log running operations info for debugging - console.log('[UsageMonitor] PROACTIVE-SWAP: Checking running operations:', { - oldProfileId: currentProfileId, - newProfileId: bestAccount.id, - totalRunning: operationSummary.totalRunning, - byProfile: operationSummary.byProfile, - byType: operationSummary.byType, - operationIdsOnOldProfile: operationIdsOnOldProfile - }); - - if (operationIdsOnOldProfile.length > 0) { - console.log('[UsageMonitor] PROACTIVE-SWAP: Found', operationIdsOnOldProfile.length, 'operations to restart:', operationIdsOnOldProfile); - - // Restart all operations on the old profile with the new profile - const restartedCount = await operationRegistry.restartOperationsOnProfile( - currentProfileId, - bestAccount.id, - bestAccount.name - ); - - // Emit event for tracking/logging - this.emit('proactive-operations-restarted', { - fromProfile: { id: currentProfileId, name: fromProfileName }, - toProfile: { id: bestAccount.id, name: bestAccount.name }, - operationIds: operationIdsOnOldProfile, - restartedCount, - limitType, - timestamp: new Date() - }); - } else { - console.log('[UsageMonitor] PROACTIVE-SWAP: No operations running on old profile', currentProfileId, '- swap complete without restart'); - } - - // Note: Don't immediately check new profile - let normal interval handle it - // This prevents cascading swaps if multiple profiles are near limits - } } /** diff --git a/src/main/index.ts b/src/main/index.ts index e428adafbf..7c231b2f07 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -813,8 +813,8 @@ app.whenReady().then(async () => { }); // Initialize Claude profile manager, then start usage monitor - // We do this sequentially to ensure profile data (including auto-switch settings) - // is loaded BEFORE the usage monitor attempts to read settings. + // We do this sequentially to ensure profile data + // is loaded BEFORE the usage monitor attempts to read it. // This prevents the "UsageMonitor disabled" error due to race condition. // Forwarding is registered once, here: the monitor's events go to every window either way initializeUsageMonitorForwarding(() => getFocusedWindow()); diff --git a/src/main/ipc-handlers/agent-events-handlers.ts b/src/main/ipc-handlers/agent-events-handlers.ts index 72af8bef5e..0eedf0e0f2 100644 --- a/src/main/ipc-handlers/agent-events-handlers.ts +++ b/src/main/ipc-handlers/agent-events-handlers.ts @@ -11,7 +11,6 @@ import type { ClaudeRunInfo } from "../../shared/types/claude-code"; import { XSTATE_SETTLED_STATES, XSTATE_ACTIVE_STATES, XSTATE_TO_PHASE, mapStateToLegacy } from "../../shared/state-machines"; import { AgentManager } from "../agent"; import type { ProcessType, ExecutionProgressData, AgentAuthFailure } from "../agent"; -import type { TaskEventPayload } from "../agent/task-event-schema"; import type { TaskRunSubtask } from "../claude-code/task-runner"; import { titleGenerator } from "../title-generator"; import { fileWatcher } from "../file-watcher"; @@ -70,57 +69,6 @@ function findFallbackTimerKey(taskId: string, projectId?: string): string | unde return undefined; } -/** - * Before holding a rate-limited task until its reset time, try switching to another - * Claude profile. The restarted run continues from its saved state (claude_run.json). - * - * Only applies when the run used a Claude profile (`event.profileId`, set by AgentManager); - * runs on an API profile have no other account to switch to. - * - * @returns true if the task was restarted on another profile (no hold needed) - */ -function tryAutoSwapBeforeHold( - agentManager: AgentManager, - taskId: string, - event: TaskEventPayload, - getMainWindow: () => BrowserWindow | null -): boolean { - const limitedProfileId = typeof event.profileId === "string" ? event.profileId : undefined; - if (!limitedProfileId) { - return false; - } - const profileManager = getClaudeProfileManager(); - const autoSwitch = profileManager.getAutoSwitchSettings(); - if (!autoSwitch.enabled || !autoSwitch.autoSwitchOnRateLimit) { - return false; - } - const bestProfile = profileManager.getBestAvailableProfile(limitedProfileId); - if (!bestProfile) { - return false; - } - console.warn(`[agent-events-handlers] Rate limit for ${taskId}: switching profile ${limitedProfileId} -> ${bestProfile.id} instead of holding`); - // A task id is only unique inside its project, so the restart names the project the event came - // from: without it a task of the same name in another project could be the one restarted - if (!agentManager.restartTask(taskId, bestProfile.id, event.projectId)) { - return false; - } - const rateLimitInfo: SDKRateLimitInfo = { - source: "task", - projectId: event.projectId, - taskId, - resetTime: typeof event.resetAt === "string" ? event.resetAt : undefined, - profileId: limitedProfileId, - profileName: profileManager.getProfile(limitedProfileId)?.name, - detectedAt: new Date(), - originalError: typeof event.message === "string" ? event.message : undefined, - wasAutoSwapped: true, - swappedToProfile: { id: bestProfile.id, name: bestProfile.name }, - swapReason: "reactive", - }; - safeSendToRenderer(getMainWindow, IPC_CHANNELS.CLAUDE_SDK_RATE_LIMIT, rateLimitInfo); - return true; -} - /** * Register all agent-events-related IPC handlers */ @@ -300,13 +248,10 @@ export function registerAgenteventsHandlers( phase: task.executionProgress?.phase }); - // Provider limit hit with a known reset time: prefer switching accounts; otherwise - // persist the hold (and notify the renderer) BEFORE XState moves the task to the - // queue, so queue auto-promotion sees the hold and skips this task. + // Provider limit hit with a known reset time: persist the hold (and notify the renderer) + // BEFORE XState moves the task to the queue, so queue auto-promotion sees the hold and skips + // this task. The task stays on its account and resumes there after the reset. if (event.type === "RATE_LIMIT_HOLD") { - if (tryAutoSwapBeforeHold(agentManager, taskId, event, getMainWindow)) { - return; - } const hold = parseRateLimitHold({ ...event, pausedAt: event.timestamp }); if (hold) { applyRateLimitHold(project, task, hold, getMainWindow); diff --git a/src/main/ipc-handlers/terminal-handlers.ts b/src/main/ipc-handlers/terminal-handlers.ts index 658dc08248..9a01280b23 100644 --- a/src/main/ipc-handlers/terminal-handlers.ts +++ b/src/main/ipc-handlers/terminal-handlers.ts @@ -445,46 +445,6 @@ export function registerTerminalHandlers( // The new authentication flow (CLAUDE_PROFILE_AUTHENTICATE) doesn't require // manual code submission - the user completes OAuth directly in the browser. - // Get auto-switch settings - ipcMain.handle( - IPC_CHANNELS.CLAUDE_PROFILE_AUTO_SWITCH_SETTINGS, - async (): Promise> => { - try { - const profileManager = getClaudeProfileManager(); - const settings = profileManager.getAutoSwitchSettings(); - return { success: true, data: settings }; - } catch (error) { - return { - success: false, - error: error instanceof Error ? error.message : 'Failed to get auto-switch settings' - }; - } - } - ); - - // Update auto-switch settings - ipcMain.handle( - IPC_CHANNELS.CLAUDE_PROFILE_UPDATE_AUTO_SWITCH, - async (_, settings: Partial): Promise => { - try { - const profileManager = getClaudeProfileManager(); - profileManager.updateAutoSwitchSettings(settings); - - // Restart usage monitor with new settings - const monitor = getUsageMonitor(); - monitor.stop(); - monitor.start(); - - return { success: true }; - } catch (error) { - return { - success: false, - error: error instanceof Error ? error.message : 'Failed to update auto-switch settings' - }; - } - } - ); - // Fetch usage by sending /usage command to terminal ipcMain.handle( IPC_CHANNELS.CLAUDE_PROFILE_FETCH_USAGE, @@ -502,23 +462,6 @@ export function registerTerminalHandlers( } ); - // Get best available profile - ipcMain.handle( - IPC_CHANNELS.CLAUDE_PROFILE_GET_BEST_PROFILE, - async (_, excludeProfileId?: string): Promise> => { - try { - const profileManager = getClaudeProfileManager(); - const bestProfile = profileManager.getBestAvailableProfile(excludeProfileId); - return { success: true, data: bestProfile }; - } catch (error) { - return { - success: false, - error: error instanceof Error ? error.message : 'Failed to get best profile' - }; - } - } - ); - // Retry rate-limited operation with a different profile ipcMain.handle( IPC_CHANNELS.CLAUDE_RETRY_WITH_PROFILE, @@ -723,9 +666,4 @@ export function initializeUsageMonitorForwarding(getWindow: () => BrowserWindow monitor.on('all-profiles-usage-updated', (allProfilesUsage: AllProfilesUsage) => { safeSendToRenderer(getWindow, IPC_CHANNELS.ALL_PROFILES_USAGE_UPDATED, allProfilesUsage); }); - - // Forward proactive swap notifications to renderer - monitor.on('show-swap-notification', (notification: unknown) => { - safeSendToRenderer(getWindow, IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, notification); - }); } diff --git a/src/main/rate-limit-detector.ts b/src/main/rate-limit-detector.ts index 011bc9d4c4..399677ddf4 100644 --- a/src/main/rate-limit-detector.ts +++ b/src/main/rate-limit-detector.ts @@ -6,8 +6,7 @@ import { getClaudeProfileManager } from './claude-profile-manager'; import { debugLog } from '../shared/utils/debug-logger'; import { findStandaloneLimitReset } from './claude-profile/rate-limit-manager'; - -; +import { appLog } from './app-logger'; /** * Regex pattern to detect Claude Code rate limit messages @@ -57,11 +56,6 @@ export interface RateLimitDetectionResult { limitType?: 'session' | 'weekly'; /** The profile ID that hit the limit (if known) */ profileId?: string; - /** Best alternative profile to switch to */ - suggestedProfile?: { - id: string; - name: string; - }; /** Original error message (truncated to 500 chars for security) */ originalError?: string; } @@ -102,18 +96,11 @@ export function detectRateLimit( console.error('[RateLimitDetector] Failed to record rate limit event:', err); } - // Find best alternative profile - const bestProfile = profileManager.getBestAvailableProfile(effectiveProfileId); - return { isRateLimited: true, resetTime, limitType, profileId: effectiveProfileId, - suggestedProfile: bestProfile ? { - id: bestProfile.id, - name: bestProfile.name - } : undefined, originalError: sanitizeErrorOutput(output) }; } @@ -123,15 +110,10 @@ export function detectRateLimit( if (pattern.test(output)) { const profileManager = getClaudeProfileManager(); const effectiveProfileId = profileId || profileManager.getActiveProfile().id; - const bestProfile = profileManager.getBestAvailableProfile(effectiveProfileId); return { isRateLimited: true, profileId: effectiveProfileId, - suggestedProfile: bestProfile ? { - id: bestProfile.id, - name: bestProfile.name - } : undefined, originalError: sanitizeErrorOutput(output) }; } @@ -140,15 +122,15 @@ export function detectRateLimit( return { isRateLimited: false }; } -/** - * Environment for a specific profile, or null when that profile no longer exists or has no - * credentials (callers then fall back to the best available profile). - */ /** Whether an account is a Claude Code setup found in its own configuration */ export function isDetectedClaudeCodeProfile(profileId: string): boolean { return !!getClaudeProfileManager().getProfile(profileId)?.detected; } +/** + * Environment for a specific profile, or null when that profile no longer exists or has no + * credentials (callers then fall back to the account in use, see getRunnableProfileEnv). + */ export function getUsableProfileEnv(profileId: string): Record | null { const profileManager = getClaudeProfileManager(); if (!profileManager.getProfile(profileId) || !profileManager.hasValidAuth(profileId)) { @@ -158,154 +140,56 @@ export function getUsableProfileEnv(profileId: string): Record | } /** - * Result of getting the best available profile environment + * Result of getting the environment of the account a run uses */ -export interface BestProfileEnvResult { +interface RunnableProfileEnvResult { /** Environment variables for the selected profile */ env: Record; /** The profile ID that was selected */ profileId: string; /** The profile name for logging/display */ profileName: string; - /** Whether a swap was performed (true if different from active profile) */ - wasSwapped: boolean; - /** Reason for the swap if one occurred */ - swapReason?: 'rate_limited' | 'at_capacity' | 'proactive' | 'not_authenticated'; - /** The original active profile if a swap occurred */ - originalProfile?: { - id: string; - name: string; - }; + /** The account in use can't run at all (no credentials), so a signed-in one was used instead */ + wasSignedOut: boolean; } /** - * Get environment variables for the BEST available Claude profile and persist the profile swap. - * - * IMPORTANT: This function has the side effect of calling profileManager.setActiveProfile() - * when a better profile is found. This modifies global state and persists the profile swap. - * - * This is the preferred function for SDK operations that need profile environment. - * It automatically handles: - * 1. Checking if the active profile is explicitly rate-limited (received 429/rate limit error) - * 2. Checking if the active profile is at capacity (100% weekly usage) - * 3. Finding a better alternative profile if available - * 4. PERSISTING the swap by updating the active profile - * - * Use this instead of getProfileEnv() for any operation that will make Claude API calls. + * Environment for the account in use, for runs that name no account (or whose account was + * removed or signed out). * - * @returns Object containing env vars and metadata about which profile was selected + * Runs stay on the account in use, also while it is rate limited or at its usage limit (they + * wait for the reset). The only exception: an account that can't run at all (e.g. an "Add + * account" sign-in that never finished) is replaced by a signed-in one, which also becomes the + * account in use, since every run on it could only fail. */ -export function getBestAvailableProfileEnv(): BestProfileEnvResult { +export function getRunnableProfileEnv(): RunnableProfileEnvResult { const profileManager = getClaudeProfileManager(); const activeProfile = profileManager.getActiveProfile(); - debugLog('[RateLimitDetector] getBestAvailableProfileEnv() called:', { - activeProfileId: activeProfile.id, - activeProfileName: activeProfile.name, - hasConfigDir: !!activeProfile.configDir, - configDir: activeProfile.configDir, - weeklyUsagePercent: activeProfile.usage?.weeklyUsagePercent, - }); - - // Check for explicit rate limit (from previous API errors) - const rateLimitStatus = profileManager.isProfileRateLimited(activeProfile.id); - - // Check for capacity limit (100% weekly usage - will be rate limited on next request) - const isAtCapacity = activeProfile.usage?.weeklyUsagePercent !== undefined && - activeProfile.usage.weeklyUsagePercent >= 100; - - // An account without credentials can't run anything (e.g. an "Add account" sign-in that - // never finished): move to one that is signed in - // (A profile without a config dir uses the default credentials and is left alone.) + // A profile without a config dir uses the default credentials and is left alone const isSignedOut = !!activeProfile.configDir && !profileManager.hasValidAuth(activeProfile.id); - - // Determine if we need to find an alternative - const needsSwap = rateLimitStatus.limited || isAtCapacity || isSignedOut; - const swapReason: BestProfileEnvResult['swapReason'] = isSignedOut - ? 'not_authenticated' - : rateLimitStatus.limited - ? 'rate_limited' - : isAtCapacity - ? 'at_capacity' - : undefined; - - if (needsSwap) { - debugLog('[RateLimitDetector] Active profile needs swap:', { - activeProfile: activeProfile.name, - isRateLimited: rateLimitStatus.limited, - isAtCapacity, - weeklyUsage: activeProfile.usage?.weeklyUsagePercent, - limitType: rateLimitStatus.type, - resetAt: rateLimitStatus.resetAt - }); - - // Try to find a better profile. Never switch to one without credentials: it would fail - // every run and become the active account. - const candidate = profileManager.getBestAvailableProfile(activeProfile.id); - const bestProfile = candidate && profileManager.hasValidAuth(candidate.id) ? candidate : null; - - if (bestProfile) { - debugLog('[RateLimitDetector] Using alternative profile:', { - originalProfile: activeProfile.name, - alternativeProfile: bestProfile.name, - reason: swapReason - }); - - // Persist the swap by updating the active profile - // This ensures the UI reflects which account is actually being used - profileManager.setActiveProfile(bestProfile.id); - console.warn('[RateLimitDetector] Switched active profile:', { - from: activeProfile.name, - to: bestProfile.name, - reason: swapReason - }); - - // The usage monitor follows the switch (setActiveProfile notifies it): it shows the new - // account's stored usage at once and fetches fresh usage. Emitting a list fetched here could - // land after that fresh usage and show stale numbers again. - - const profileEnv = profileManager.getProfileEnv(bestProfile.id); - - debugLog('[RateLimitDetector] Profile env for swapped profile:', { - profileId: bestProfile.id, - hasClaudeConfigDir: !!profileEnv.CLAUDE_CONFIG_DIR, - claudeConfigDir: profileEnv.CLAUDE_CONFIG_DIR, - hasOAuthToken: !!profileEnv.CLAUDE_CODE_OAUTH_TOKEN, - envKeys: Object.keys(profileEnv), - }); - + if (isSignedOut) { + const signedIn = profileManager.getSettings().profiles.find( + (profile) => profile.id !== activeProfile.id && profileManager.hasValidAuth(profile.id) + ); + if (signedIn) { + profileManager.setActiveProfile(signedIn.id); + appLog.warn(`[RateLimitDetector] Account "${activeProfile.name}" has no credentials, using "${signedIn.name}"`); return { - env: ensureCleanProfileEnv(profileEnv), - profileId: bestProfile.id, - profileName: bestProfile.name, - wasSwapped: true, - swapReason, - originalProfile: { - id: activeProfile.id, - name: activeProfile.name - } + env: ensureCleanProfileEnv(profileManager.getProfileEnv(signedIn.id)), + profileId: signedIn.id, + profileName: signedIn.name, + wasSignedOut: true }; - } else { - debugLog('[RateLimitDetector] No alternative profile available, using rate-limited/at-capacity profile'); } + debugLog('[RateLimitDetector] Active account has no credentials and no other account is signed in'); } - // Use active profile (either it's fine, or no better alternative exists) - const activeEnv = profileManager.getActiveProfileEnv(); - - debugLog('[RateLimitDetector] Using active profile env (no swap):', { - profileId: activeProfile.id, - hasClaudeConfigDir: !!activeEnv.CLAUDE_CONFIG_DIR, - claudeConfigDir: activeEnv.CLAUDE_CONFIG_DIR, - hasOAuthToken: !!activeEnv.CLAUDE_CODE_OAUTH_TOKEN, - envKeys: Object.keys(activeEnv), - }); - return { - env: ensureCleanProfileEnv(activeEnv), + env: ensureCleanProfileEnv(profileManager.getActiveProfileEnv()), profileId: activeProfile.id, profileName: activeProfile.name, - wasSwapped: false + wasSignedOut: false }; } @@ -321,8 +205,8 @@ export function getBestAvailableProfileEnv(): BestProfileEnvResult { * in the shell environment, which would cause it to show "Claude API" instead of * "Claude Max" and bypass the intended config dir credentials. * - * This is critical for multi-account switching: when switching from a rate-limited - * account to an available one, the subprocess must use the new account's credentials. + * This is critical with several accounts: the subprocess must use the chosen account's + * credentials. * * Also warns if the profile env is empty, which indicates a misconfigured profile. * @@ -383,26 +267,10 @@ export interface SDKRateLimitInfo { profileId: string; /** Profile name for display */ profileName?: string; - /** Suggested alternative profile */ - suggestedProfile?: { - id: string; - name: string; - }; /** When detected */ detectedAt: Date; /** Original error message (truncated to 500 chars for security) */ originalError?: string; - - // Auto-swap information - /** Whether this rate limit was automatically handled via account swap */ - wasAutoSwapped?: boolean; - /** Profile that was swapped to (if auto-swapped) */ - swappedToProfile?: { - id: string; - name: string; - }; - /** Why the swap occurred: 'proactive' (before limit) or 'reactive' (after limit hit) */ - swapReason?: 'proactive' | 'reactive'; } /** @@ -429,7 +297,6 @@ export function createSDKRateLimitInfo( limitType: detection.limitType, profileId: detection.profileId || profileManager.getActiveProfile().id, profileName: profile?.name, - suggestedProfile: detection.suggestedProfile, detectedAt: new Date(), originalError: detection.originalError }; diff --git a/src/main/services/profile/profile-manager.ts b/src/main/services/profile/profile-manager.ts index 09b5e32567..f5f38814e4 100644 --- a/src/main/services/profile/profile-manager.ts +++ b/src/main/services/profile/profile-manager.ts @@ -192,29 +192,6 @@ async function withProfilesLock(fn: () => Promise): Promise { } } -/** - * Set the active API profile by ID - * This atomically updates the activeProfileId in profiles.json - * - * @param profileId - The profile ID to set as active, or null to clear - * @returns The updated ProfilesFile - */ -export async function setActiveAPIProfile(profileId: string | null): Promise { - return await atomicModifyProfiles((file) => { - // Validate that the profile exists if setting an ID - if (profileId !== null) { - const profile = file.profiles.find(p => p.id === profileId); - if (!profile) { - throw new Error(`API profile not found: ${profileId}`); - } - } - return { - ...file, - activeProfileId: profileId - }; - }); -} - /** * Atomically modify the profiles file * Loads, modifies, and saves the file within an exclusive lock diff --git a/src/main/terminal/__tests__/rate-limit-terminal-output.test.ts b/src/main/terminal/__tests__/rate-limit-terminal-output.test.ts index fe34b64623..27f811fb4f 100644 --- a/src/main/terminal/__tests__/rate-limit-terminal-output.test.ts +++ b/src/main/terminal/__tests__/rate-limit-terminal-output.test.ts @@ -8,8 +8,6 @@ import type { TerminalProcess } from '../types'; const profileManager = vi.hoisted(() => ({ recordRateLimitEvent: vi.fn(() => ({ type: 'session' })), - getAutoSwitchSettings: vi.fn(() => ({ enabled: false, autoSwitchOnRateLimit: false })), - getBestAvailableProfile: vi.fn(() => null), })); vi.mock('electron', () => ({ app: { getPath: () => '/tmp' }, BrowserWindow: vi.fn() })); @@ -29,7 +27,7 @@ function terminal(): TerminalProcess { } function feed(data: string): void { - handleRateLimit(terminal(), data, new Map(), () => null, vi.fn(async () => {})); + handleRateLimit(terminal(), data, new Map(), () => null); } describe('handleRateLimit (terminal output)', () => { diff --git a/src/main/terminal/cli-integration-handler.ts b/src/main/terminal/cli-integration-handler.ts index 2a2430b9f9..1c639f3b4b 100644 --- a/src/main/terminal/cli-integration-handler.ts +++ b/src/main/terminal/cli-integration-handler.ts @@ -1057,14 +1057,14 @@ export function finalizeClaudeInvoke( } /** - * Handle rate limit detection and profile switching + * Handle rate limit detection: the window's account is marked rate limited until its reset + * (the window stays on that account) */ export function handleRateLimit( terminal: TerminalProcess, data: string, lastNotifiedRateLimitReset: Map, - getWindow: WindowGetter, - switchProfileCallback: (terminalId: string, profileId: string) => Promise + getWindow: WindowGetter ): void { if (!OutputParser.extractRateLimitReset(data)) { return; @@ -1099,27 +1099,12 @@ export function handleRateLimit( console.error('[ClaudeIntegration] Failed to record rate limit event:', err); } - const autoSwitchSettings = profileManager.getAutoSwitchSettings(); - const bestProfile = profileManager.getBestAvailableProfile(currentProfileId); - safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_RATE_LIMIT, { terminalId: terminal.id, resetTime, detectedAt: new Date().toISOString(), - profileId: currentProfileId, - suggestedProfileId: bestProfile?.id, - suggestedProfileName: bestProfile?.name, - autoSwitchEnabled: autoSwitchSettings.autoSwitchOnRateLimit + profileId: currentProfileId } as RateLimitEvent); - - if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit && bestProfile) { - console.warn('[ClaudeIntegration] Auto-switching to profile:', bestProfile.name); - switchProfileCallback(terminal.id, bestProfile.id).then(_result => { - console.warn('[ClaudeIntegration] Auto-switch completed'); - }).catch(err => { - console.error('[ClaudeIntegration] Auto-switch failed:', err); - }); - } } /** diff --git a/src/main/terminal/terminal-event-handler.ts b/src/main/terminal/terminal-event-handler.ts index fde70e3a6e..2b350dd84e 100644 --- a/src/main/terminal/terminal-event-handler.ts +++ b/src/main/terminal/terminal-event-handler.ts @@ -71,8 +71,7 @@ export function handleTerminalData( */ export function createEventCallbacks( getWindow: WindowGetter, - lastNotifiedRateLimitReset: Map, - switchProfileCallback: (terminalId: string, profileId: string) => Promise + lastNotifiedRateLimitReset: Map ): EventHandlerCallbacks { return { onRateLimit: (terminal, data) => { @@ -80,8 +79,7 @@ export function createEventCallbacks( terminal, data, lastNotifiedRateLimitReset, - getWindow, - switchProfileCallback + getWindow ); }, onOAuthToken: (terminal, data) => { diff --git a/src/main/terminal/terminal-manager.ts b/src/main/terminal/terminal-manager.ts index 74684453e0..1b19added2 100644 --- a/src/main/terminal/terminal-manager.ts +++ b/src/main/terminal/terminal-manager.ts @@ -37,10 +37,7 @@ export class TerminalManager { // Create event callbacks with bound context this.eventCallbacks = TerminalEventHandler.createEventCallbacks( this.getWindow, - this.lastNotifiedRateLimitReset, - async (terminalId, profileId) => { - await this.switchClaudeProfile(terminalId, profileId); - } + this.lastNotifiedRateLimitReset ); // Periodically save session data. The period is shared with the store, which reads the trail diff --git a/src/main/terminal/types.ts b/src/main/terminal/types.ts index 28f27507f6..820f0e9772 100644 --- a/src/main/terminal/types.ts +++ b/src/main/terminal/types.ts @@ -51,9 +51,6 @@ export interface RateLimitEvent { resetTime: string; detectedAt: string; profileId: string; - suggestedProfileId?: string; - suggestedProfileName?: string; - autoSwitchEnabled: boolean; } /** diff --git a/src/preload/api/index.ts b/src/preload/api/index.ts index 843579d221..955ffbae30 100644 --- a/src/preload/api/index.ts +++ b/src/preload/api/index.ts @@ -13,7 +13,6 @@ import { LiveAgentAPI, createLiveAgentAPI } from './modules/live-agent-api'; import { McpAPI, createMcpAPI } from './modules/mcp-api'; import { BrowserDrawerAPI, createBrowserDrawerAPI } from './modules/browser-drawer-api'; import { ProfileAPI, createProfileAPI } from './profile-api'; -import { QueueAPI, createQueueAPI } from './queue-api'; import { WindowAPI, createWindowAPI } from './modules/window-api'; import { ShellRuntimeAPI, createShellRuntimeAPI } from './modules/shell-runtime-api'; @@ -34,10 +33,7 @@ export interface ElectronAPI extends BrowserDrawerAPI, ProfileAPI, WindowAPI, - ShellRuntimeAPI { - /** Queue routing API for rate limit recovery */ - queue: QueueAPI; -} + ShellRuntimeAPI {} export const createElectronAPI = (): ElectronAPI => ({ ...createProjectAPI(), @@ -55,8 +51,7 @@ export const createElectronAPI = (): ElectronAPI => ({ ...createBrowserDrawerAPI(), ...createProfileAPI(), ...createWindowAPI(), - ...createShellRuntimeAPI(), - queue: createQueueAPI() // Queue routing for rate limit recovery + ...createShellRuntimeAPI() }); // Export individual API creators for potential use in tests or specialized contexts diff --git a/src/preload/api/queue-api.ts b/src/preload/api/queue-api.ts deleted file mode 100644 index ac9e28e3f0..0000000000 --- a/src/preload/api/queue-api.ts +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Queue Routing API - * - * Preload API for rate limit recovery queue routing. - * Exposes IPC methods to the renderer for profile-aware task distribution. - */ - -import { ipcRenderer } from 'electron'; -import { IPC_CHANNELS } from '../../shared/constants'; -import type { - IPCResult, - RunningTasksByProfile, - ProfileAssignmentReason, - ProfileSwapRecord, -} from '../../shared/types'; -import type { UnifiedAccount } from '../../shared/types/unified-account'; - -/** - * Result of best profile selection for a task - */ -export interface BestProfileResult { - profileId: string; - profileName: string; - availabilityScore: number; - reason: ProfileAssignmentReason; - runningTaskCount: number; -} - -/** - * Options for getting the best profile for a task - */ -export interface GetBestProfileOptions { - /** Profile ID to exclude (e.g., one that just hit rate limit) */ - excludeProfileId?: string; - /** Maximum tasks per profile before load balancing (default: 2) */ - perProfileMaxTasks?: number; - /** Usage threshold (0-1) before considering profile "busy" (default: 0.85) */ - profileThreshold?: number; -} - -/** - * Options for getting the best unified account for a task - */ -export interface GetBestUnifiedAccountOptions { - /** Unified account ID to exclude (e.g., 'oauth-profile1' or 'api-profile2') */ - excludeAccountId?: string; -} - -/** - * Profile swap notification event payload - */ -export interface QueueProfileSwapEvent { - taskId: string; - swap: ProfileSwapRecord; -} - -/** - * Session captured event payload - */ -export interface QueueSessionCapturedEvent { - taskId: string; - sessionId: string; - capturedAt: string; -} - -export interface QueueAPI { - // Queue Routing Operations - /** - * Get running tasks grouped by profile - * Used for queue routing decisions - */ - getRunningTasksByProfile: () => Promise>; - - /** - * Get the best available profile for a new task - * Considers availability scores, running task counts, and rate limit status - */ - getBestProfileForTask: (options?: GetBestProfileOptions) => Promise>; - - /** - * Get the best available unified account for a new task - * Considers both OAuth profiles and API profiles in unified selection - * Used for cross-type account switching when OAuth profiles are exhausted - */ - getBestUnifiedAccount: (options?: GetBestUnifiedAccountOptions) => Promise>; - - /** - * Assign a profile to a task - * Called when a task is started or when profile is swapped - */ - assignProfileToTask: ( - taskId: string, - profileId: string, - profileName: string, - reason: ProfileAssignmentReason - ) => Promise; - - /** - * Update session ID for a task - * Called when session ID is captured from agent stdout - */ - updateTaskSession: (taskId: string, sessionId: string) => Promise; - - /** - * Get session ID for a task - */ - getTaskSession: (taskId: string) => Promise>; - - // Queue Routing Event Listeners - /** - * Listen for profile swap events - * Fired when a task's profile is swapped due to rate limit or capacity - */ - onQueueProfileSwapped: (callback: (event: QueueProfileSwapEvent) => void) => () => void; - - /** - * Listen for session captured events - * Fired when a session ID is captured from a running task - */ - onQueueSessionCaptured: (callback: (event: QueueSessionCapturedEvent) => void) => () => void; - - /** - * Listen for queue blocked events - * Fired when no profiles are available to run queued tasks - */ - onQueueBlockedNoProfiles: (callback: (info: { reason: string; timestamp: string }) => void) => () => void; -} - -export const createQueueAPI = (): QueueAPI => ({ - // Queue Routing Operations - getRunningTasksByProfile: (): Promise> => - ipcRenderer.invoke(IPC_CHANNELS.QUEUE_GET_RUNNING_TASKS_BY_PROFILE), - - getBestProfileForTask: (options?: GetBestProfileOptions): Promise> => - ipcRenderer.invoke(IPC_CHANNELS.QUEUE_GET_BEST_PROFILE_FOR_TASK, options), - - getBestUnifiedAccount: (options?: GetBestUnifiedAccountOptions): Promise> => - ipcRenderer.invoke(IPC_CHANNELS.QUEUE_GET_BEST_UNIFIED_ACCOUNT, options), - - assignProfileToTask: ( - taskId: string, - profileId: string, - profileName: string, - reason: ProfileAssignmentReason - ): Promise => - ipcRenderer.invoke(IPC_CHANNELS.QUEUE_ASSIGN_PROFILE_TO_TASK, taskId, profileId, profileName, reason), - - updateTaskSession: (taskId: string, sessionId: string): Promise => - ipcRenderer.invoke(IPC_CHANNELS.QUEUE_UPDATE_TASK_SESSION, taskId, sessionId), - - getTaskSession: (taskId: string): Promise> => - ipcRenderer.invoke(IPC_CHANNELS.QUEUE_GET_TASK_SESSION, taskId), - - // Queue Routing Event Listeners - onQueueProfileSwapped: (callback: (event: QueueProfileSwapEvent) => void): (() => void) => { - const handler = (_event: Electron.IpcRendererEvent, data: QueueProfileSwapEvent) => callback(data); - ipcRenderer.on(IPC_CHANNELS.QUEUE_PROFILE_SWAPPED, handler); - return () => ipcRenderer.removeListener(IPC_CHANNELS.QUEUE_PROFILE_SWAPPED, handler); - }, - - onQueueSessionCaptured: (callback: (event: QueueSessionCapturedEvent) => void): (() => void) => { - const handler = (_event: Electron.IpcRendererEvent, data: QueueSessionCapturedEvent) => callback(data); - ipcRenderer.on(IPC_CHANNELS.QUEUE_SESSION_CAPTURED, handler); - return () => ipcRenderer.removeListener(IPC_CHANNELS.QUEUE_SESSION_CAPTURED, handler); - }, - - onQueueBlockedNoProfiles: (callback: (info: { reason: string; timestamp: string }) => void): (() => void) => { - const handler = (_event: Electron.IpcRendererEvent, info: { reason: string; timestamp: string }) => callback(info); - ipcRenderer.on(IPC_CHANNELS.QUEUE_BLOCKED_NO_PROFILES, handler); - return () => ipcRenderer.removeListener(IPC_CHANNELS.QUEUE_BLOCKED_NO_PROFILES, handler); - }, -}); diff --git a/src/preload/api/terminal-api.ts b/src/preload/api/terminal-api.ts index dba32c326a..0f50d175db 100644 --- a/src/preload/api/terminal-api.ts +++ b/src/preload/api/terminal-api.ts @@ -11,21 +11,12 @@ import type { TerminalCreateOptions, ClaudeProfile, ClaudeProfileSettings, - ClaudeUsageSnapshot, CreateTerminalWorktreeRequest, TerminalWorktreeConfig, TerminalWorktreeResult, OtherWorktreeInfo, } from '../../shared/types'; -/** Type for proactive swap notification events */ -interface ProactiveSwapNotification { - fromProfile: { id: string; name: string }; - toProfile: { id: string; name: string }; - reason: string; - usageSnapshot: ClaudeUsageSnapshot; -} - export interface TerminalAPI { // Terminal Operations createTerminal: (options: TerminalCreateOptions) => Promise; @@ -103,19 +94,15 @@ export interface TerminalAPI { claudeAuthLoginSubprocess: (profileId: string) => Promise>; cancelClaudeAuthLogin: (profileId: string) => Promise; onClaudeAuthLoginProgress: (callback: (data: { status: string; message?: string }) => void) => () => void; - getAutoSwitchSettings: () => Promise>; - updateAutoSwitchSettings: (settings: Partial) => Promise; fetchClaudeUsage: (terminalId: string) => Promise; - getBestAvailableProfile: (excludeProfileId?: string) => Promise>; onAuthFailure: (callback: (info: import('../../shared/types').AuthFailureInfo) => void) => () => void; retryWithProfile: (request: import('../../shared/types').RetryWithProfileRequest) => Promise; - // Usage Monitoring (Proactive Account Switching) + // Usage Monitoring requestUsageUpdate: () => Promise>; requestAllProfilesUsage: (forceRefresh?: boolean) => Promise>; onUsageUpdated: (callback: (usage: import('../../shared/types').ClaudeUsageSnapshot | null) => void) => () => void; onAllProfilesUsageUpdated: (callback: (allProfilesUsage: import('../../shared/types').AllProfilesUsage) => void) => () => void; - onProactiveSwapNotification: (callback: (notification: ProactiveSwapNotification) => void) => () => void; } export const createTerminalAPI = (): TerminalAPI => ({ @@ -417,18 +404,9 @@ export const createTerminalAPI = (): TerminalAPI => ({ }; }, - getAutoSwitchSettings: (): Promise> => - ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_PROFILE_AUTO_SWITCH_SETTINGS), - - updateAutoSwitchSettings: (settings: Partial): Promise => - ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_PROFILE_UPDATE_AUTO_SWITCH, settings), - fetchClaudeUsage: (terminalId: string): Promise => ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_PROFILE_FETCH_USAGE, terminalId), - getBestAvailableProfile: (excludeProfileId?: string): Promise> => - ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_PROFILE_GET_BEST_PROFILE, excludeProfileId), - onAuthFailure: ( callback: (info: import('../../shared/types').AuthFailureInfo) => void ): (() => void) => { @@ -447,7 +425,7 @@ export const createTerminalAPI = (): TerminalAPI => ({ retryWithProfile: (request: import('../../shared/types').RetryWithProfileRequest): Promise => ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_RETRY_WITH_PROFILE, request), - // Usage Monitoring (Proactive Account Switching) + // Usage Monitoring requestUsageUpdate: (): Promise> => ipcRenderer.invoke(IPC_CHANNELS.USAGE_REQUEST), @@ -482,17 +460,5 @@ export const createTerminalAPI = (): TerminalAPI => ({ return () => { ipcRenderer.removeListener(IPC_CHANNELS.ALL_PROFILES_USAGE_UPDATED, handler); }; - }, - - onProactiveSwapNotification: ( - callback: (notification: ProactiveSwapNotification) => void - ): (() => void) => { - const handler = (_event: Electron.IpcRendererEvent, notification: ProactiveSwapNotification): void => { - callback(notification); - }; - ipcRenderer.on(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, handler); - return () => { - ipcRenderer.removeListener(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, handler); - }; } }); diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index 2d9d3bc33a..782c8b8ad6 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -25,7 +25,6 @@ import { Insights } from './components/Insights'; import { WelcomeScreen } from './components/WelcomeScreen'; import { ProjectsPage } from './components/ProjectsPage'; import { AuthFailureModal } from './components/AuthFailureModal'; -import { ProactiveSwapListener } from './components/ProactiveSwapListener'; import { useProjectStore, loadProjects, initializeProject, removeProject } from './stores/project-store'; import { useTaskStore, loadTasks } from './stores/task-store'; import { useInsightsStore, chatBrowserId } from './stores/insights-store'; @@ -680,7 +679,6 @@ export function App() { return ( -
{/* Sidebar */} (null); - const [isVisible, setIsVisible] = useState(false); - - useEffect(() => { - const unsubscribe = window.electronAPI.onProactiveSwapNotification((data) => { - const notif: SwapNotification = { - fromProfile: data.fromProfile.name, - toProfile: data.toProfile.name, - reason: data.reason, - timestamp: new Date() - }; - - setNotification(notif); - setIsVisible(true); - - // Auto-hide after 5 seconds - setTimeout(() => { - setIsVisible(false); - }, 5000); - }); - - return () => { - unsubscribe(); - }; - }, []); - - const handleDismiss = () => { - setIsVisible(false); - }; - - if (!notification || !isVisible) { - return null; - } - - return ( -
-
-
-
-

{t('notification.accountSwitched')}

-

- {t('notification.swapFrom')} {notification.fromProfile} {t('notification.swapTo')}{' '} - {notification.toProfile} -
- - {t('notification.swapReason', { reason: notification.reason })} - -

-
- -
-
-
- ); -} diff --git a/src/renderer/components/settings/AccountSettings.tsx b/src/renderer/components/settings/AccountSettings.tsx index 1c291f3616..82df021757 100644 --- a/src/renderer/components/settings/AccountSettings.tsx +++ b/src/renderer/components/settings/AccountSettings.tsx @@ -1,21 +1,16 @@ /** * AccountSettings - how Claude Code signs in * - * claude.ai settings layout: Claude accounts (subscriptions, with usage), API profiles - * (Anthropic-compatible endpoints) and automatic account switching, then spending per project - * (Metrics). + * claude.ai settings layout: Claude accounts (subscriptions, with usage) and API profiles + * (Anthropic-compatible endpoints), then spending per project (Metrics). */ -import { useState, useEffect, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; -import { Switch } from '../ui/switch'; -import { cn } from '../../lib/utils'; import { SettingsSection } from './SettingsSection'; -import { SettingsRow, SettingsRows } from './SettingsRow'; +import { SettingsRows } from './SettingsRow'; import { ClaudeAccountsSection } from './ClaudeAccountsSection'; import { ProfileList } from './ProfileList'; import { ProjectMetricsSection } from './ProjectMetricsSection'; -import { useClaudeAccounts } from './hooks/useClaudeAccounts'; -import type { AppSettings, ClaudeAutoSwitchSettings } from '../../../shared/types'; +import type { AppSettings } from '../../../shared/types'; interface AccountSettingsProps { /** Kept for the page signature; accounts are stored by the main process, not in app settings */ @@ -24,83 +19,8 @@ interface AccountSettingsProps { isOpen: boolean; } -export function AccountSettings({ isOpen }: AccountSettingsProps) { +export function AccountSettings(_props: AccountSettingsProps) { const { t } = useTranslation('settings'); - const { profiles } = useClaudeAccounts(isOpen); - - const [autoSwitchSettings, setAutoSwitchSettings] = useState(null); - const [isLoadingAutoSwitch, setIsLoadingAutoSwitch] = useState(false); - // A failed settings change, shown in place of the switching setting's description - const [settingsError, setSettingsError] = useState(null); - const showUpdateFailed = useCallback((description?: string) => { - setSettingsError(`${t('accounts.toast.settingsUpdateFailed')}: ${description || t('accounts.toast.tryAgain')}`); - }, [t]); - - const loadAutoSwitchSettings = useCallback(async () => { - setIsLoadingAutoSwitch(true); - try { - const result = await window.electronAPI.getAutoSwitchSettings(); - if (result.success && result.data) setAutoSwitchSettings(result.data); - } catch { - // Non-fatal - } finally { - setIsLoadingAutoSwitch(false); - } - }, []); - - useEffect(() => { - if (!isOpen) return; - void loadAutoSwitchSettings(); - }, [isOpen, loadAutoSwitchSettings]); - - const handleUpdateAutoSwitch = async (updates: Partial) => { - setIsLoadingAutoSwitch(true); - setSettingsError(null); - try { - const result = await window.electronAPI.updateAutoSwitchSettings(updates); - if (result.success) { - await loadAutoSwitchSettings(); - } else { - showUpdateFailed(result.error); - } - } catch { - showUpdateFailed(); - } finally { - setIsLoadingAutoSwitch(false); - } - }; - - const totalAccounts = profiles.length; - - const thresholdSlider = ( - id: string, - value: number, - onChange: (value: number) => void, - describedBy: string - ) => ( -
- onChange(parseInt(e.target.value, 10))} - disabled={isLoadingAutoSwitch} - aria-describedby={describedBy} - className={cn( - 'h-1.5 w-40 cursor-pointer appearance-none rounded-full bg-segment-track disabled:cursor-default', - 'focus-visible:outline-none focus-visible:shadow-(--shadow-focus)', - '[&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:appearance-none', - '[&::-webkit-slider-thumb]:cursor-pointer [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-foreground', - '[&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:cursor-pointer', - '[&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-foreground' - )} - /> - {value}% -
- ); return ( <> @@ -109,107 +29,6 @@ export function AccountSettings({ isOpen }: AccountSettingsProps) { - - {/* Automatic account switching: once there's another account to switch to */} - {totalAccounts > 1 && ( - {settingsError} - ) : ( - t('accounts.autoSwitching.description') - ) - } - > - handleUpdateAutoSwitch({ enabled })} - disabled={isLoadingAutoSwitch} - aria-label={t('accounts.autoSwitching.enableAutoSwitching')} - /> - - )} - - {totalAccounts > 1 && autoSwitchSettings?.enabled && ( - - handleUpdateAutoSwitch({ proactiveSwapEnabled: value })} - disabled={isLoadingAutoSwitch} - aria-label={t('accounts.autoSwitching.proactiveMonitoring')} - /> - - )} - - {totalAccounts > 1 && autoSwitchSettings?.enabled && autoSwitchSettings?.proactiveSwapEnabled && ( - - {t('accounts.autoSwitching.sessionThresholdDescription')} - - } - > - {thresholdSlider( - 'session-threshold', - autoSwitchSettings?.sessionThreshold ?? 95, - (value) => handleUpdateAutoSwitch({ sessionThreshold: value }), - 'session-threshold-description' - )} - - )} - - {totalAccounts > 1 && autoSwitchSettings?.enabled && autoSwitchSettings?.proactiveSwapEnabled && ( - - {t('accounts.autoSwitching.weeklyThresholdDescription')} - - } - > - {thresholdSlider( - 'weekly-threshold', - autoSwitchSettings?.weeklyThreshold ?? 99, - (value) => handleUpdateAutoSwitch({ weeklyThreshold: value }), - 'weekly-threshold-description' - )} - - )} - - {totalAccounts > 1 && autoSwitchSettings?.enabled && ( - - handleUpdateAutoSwitch({ autoSwitchOnRateLimit: value })} - disabled={isLoadingAutoSwitch} - aria-label={t('accounts.autoSwitching.reactiveRecovery')} - /> - - )} - - {totalAccounts > 1 && autoSwitchSettings?.enabled && ( - - handleUpdateAutoSwitch({ autoSwitchOnAuthFailure: value })} - disabled={isLoadingAutoSwitch} - aria-label={t('accounts.autoSwitching.autoSwitchOnAuthFailure')} - /> - - )} diff --git a/src/renderer/lib/browser-mock.ts b/src/renderer/lib/browser-mock.ts index eb567a7e5d..0fc43c2049 100644 --- a/src/renderer/lib/browser-mock.ts +++ b/src/renderer/lib/browser-mock.ts @@ -101,18 +101,7 @@ const browserMockAPI: ElectronAPI = { } }), - // Queue Routing API (rate limit recovery) - queue: { - getRunningTasksByProfile: async () => ({ success: true, data: { byProfile: {}, totalRunning: 0 } }), - getBestProfileForTask: async () => ({ success: true, data: null }), - getBestUnifiedAccount: async () => ({ success: true, data: null }), - assignProfileToTask: async () => ({ success: true }), - updateTaskSession: async () => ({ success: true }), - getTaskSession: async () => ({ success: true, data: null }), - onQueueProfileSwapped: () => () => {}, - onQueueSessionCaptured: () => () => {}, - onQueueBlockedNoProfiles: () => () => {} - }, + // Claude Code Operations // Graphify CLI (memory graph) diff --git a/src/renderer/lib/mocks/claude-profile-mock.ts b/src/renderer/lib/mocks/claude-profile-mock.ts index a3c8338f19..63e00ca60d 100644 --- a/src/renderer/lib/mocks/claude-profile-mock.ts +++ b/src/renderer/lib/mocks/claude-profile-mock.ts @@ -37,34 +37,14 @@ export const claudeProfileMock = { setClaudeProfileToken: async () => ({ success: true }), - getAutoSwitchSettings: async () => ({ - success: true, - data: { - enabled: false, - proactiveSwapEnabled: false, - sessionThreshold: 95, - weeklyThreshold: 99, - autoSwitchOnRateLimit: false, - autoSwitchOnAuthFailure: false, - usageCheckInterval: 30000 - } - }), - - updateAutoSwitchSettings: async () => ({ success: true }), - fetchClaudeUsage: async () => ({ success: true }), - getBestAvailableProfile: async () => ({ - success: true, - data: null - }), - onAuthFailure: () => () => {}, retryWithProfile: async () => ({ success: true }), - // Usage Monitoring (Proactive Account Switching) + // Usage Monitoring requestUsageUpdate: async () => ({ success: true, data: null @@ -79,8 +59,6 @@ export const claudeProfileMock = { onAllProfilesUsageUpdated: () => () => {}, - onProactiveSwapNotification: () => () => {}, - // Returns terminal config for embedded authentication authenticateClaudeProfile: async (profileId: string) => ({ success: true, diff --git a/src/shared/constants/ipc.ts b/src/shared/constants/ipc.ts index 25b45a8c3b..f23c6372a4 100644 --- a/src/shared/constants/ipc.ts +++ b/src/shared/constants/ipc.ts @@ -141,10 +141,7 @@ export const IPC_CHANNELS = { CLAUDE_AUTH_LOGIN_SUBPROCESS: 'claude:authLoginSubprocess', // Run `claude auth login` as subprocess CLAUDE_AUTH_LOGIN_PROGRESS: 'claude:authLoginProgress', // Main → Renderer progress events CLAUDE_AUTH_LOGIN_CANCEL: 'claude:authLoginCancel', // Stop a running `claude auth login` - CLAUDE_PROFILE_AUTO_SWITCH_SETTINGS: 'claude:autoSwitchSettings', - CLAUDE_PROFILE_UPDATE_AUTO_SWITCH: 'claude:updateAutoSwitch', CLAUDE_PROFILE_FETCH_USAGE: 'claude:fetchUsage', - CLAUDE_PROFILE_GET_BEST_PROFILE: 'claude:getBestProfile', // SDK/CLI rate limit event (for non-terminal Claude invocations) CLAUDE_SDK_RATE_LIMIT: 'claude:sdkRateLimit', @@ -153,12 +150,11 @@ export const IPC_CHANNELS = { // Retry a rate-limited operation with a different profile CLAUDE_RETRY_WITH_PROFILE: 'claude:retryWithProfile', - // Usage monitoring (proactive account switching) + // Usage monitoring USAGE_UPDATED: 'claude:usageUpdated', // Event: usage data updated (main -> renderer) USAGE_REQUEST: 'claude:usageRequest', // Request current usage snapshot ALL_PROFILES_USAGE_REQUEST: 'claude:allProfilesUsageRequest', // Request all profiles usage immediately ALL_PROFILES_USAGE_UPDATED: 'claude:allProfilesUsageUpdated', // Event: all profiles usage data (main -> renderer) - PROACTIVE_SWAP_NOTIFICATION: 'claude:proactiveSwapNotification', // Event: proactive swap occurred // Settings SETTINGS_GET: 'settings:get', @@ -321,18 +317,5 @@ export const IPC_CHANNELS = { // Spell check - SPELLCHECK_SET_LANGUAGES: 'spellcheck:setLanguages', // Set spell check language (syncs with i18n) - - // Queue routing (rate limit recovery) - QUEUE_GET_RUNNING_TASKS_BY_PROFILE: 'queue:getRunningTasksByProfile', - QUEUE_GET_BEST_PROFILE_FOR_TASK: 'queue:getBestProfileForTask', - QUEUE_GET_BEST_UNIFIED_ACCOUNT: 'queue:getBestUnifiedAccount', // Unified OAuth + API account selection - QUEUE_ASSIGN_PROFILE_TO_TASK: 'queue:assignProfileToTask', - QUEUE_UPDATE_TASK_SESSION: 'queue:updateTaskSession', - QUEUE_GET_TASK_SESSION: 'queue:getTaskSession', - - // Queue routing events (main -> renderer) - QUEUE_PROFILE_SWAPPED: 'queue:profileSwapped', // Task switched to different profile - QUEUE_SESSION_CAPTURED: 'queue:sessionCaptured', // Session ID captured from running task - QUEUE_BLOCKED_NO_PROFILES: 'queue:blockedNoProfiles' // All profiles unavailable + SPELLCHECK_SET_LANGUAGES: 'spellcheck:setLanguages' // Set spell check language (syncs with i18n) } as const; diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index b454558f9f..cdd69bdf16 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -109,12 +109,6 @@ "notFound": "Not found", "unauthorized": "Unauthorized" }, - "notification": { - "accountSwitched": "Account Switched", - "swapFrom": "Switched from", - "swapTo": "to", - "swapReason": "({{reason}} swap)" - }, "insights": { "suggestedTask": "Suggested Task", "creating": "Creating...", diff --git a/src/shared/i18n/locales/en/settings.json b/src/shared/i18n/locales/en/settings.json index eae9b6c583..a4ca9d03be 100644 --- a/src/shared/i18n/locales/en/settings.json +++ b/src/shared/i18n/locales/en/settings.json @@ -352,21 +352,6 @@ "accounts": { "title": "Accounts", "description": "Manage Claude accounts and API endpoints", - "autoSwitching": { - "description": "Switch to another Claude account before or when the one in use hits a limit", - "enableAutoSwitching": "Enable automatic switching", - "masterSwitch": "Master switch for all auto-swap features", - "proactiveMonitoring": "Proactive monitoring", - "proactiveDescription": "Check usage regularly and swap before hitting limits", - "sessionThreshold": "Session usage threshold", - "sessionThresholdDescription": "Switch when session usage reaches this level (recommended: 95%)", - "weeklyThreshold": "Weekly usage threshold", - "weeklyThresholdDescription": "Switch when weekly usage reaches this level (recommended: 99%)", - "reactiveRecovery": "Reactive recovery", - "reactiveDescription": "Auto-swap when unexpected rate limit is hit", - "autoSwitchOnAuthFailure": "Auto-switch on auth failure", - "autoSwitchOnAuthFailureDescription": "Automatically switch to another authenticated account when authentication fails" - }, "metrics": { "title": "Metrics", "tasks_one": "{{count}} task", diff --git a/src/shared/types/agent.ts b/src/shared/types/agent.ts index 2221bba1b2..a5c020b9fe 100644 --- a/src/shared/types/agent.ts +++ b/src/shared/types/agent.ts @@ -264,66 +264,4 @@ export interface ClaudeProfileSettings { profiles: ClaudeProfile[]; /** ID of the currently active profile */ activeProfileId: string; - /** Auto-switch settings */ - autoSwitch?: ClaudeAutoSwitchSettings; -} - -/** - * Settings for automatic profile switching - */ -export interface ClaudeAutoSwitchSettings { - /** Master toggle - enables all auto-switch features */ - enabled: boolean; - - // Proactive monitoring settings - /** Enable proactive monitoring and swapping before hitting limits */ - proactiveSwapEnabled: boolean; - /** Interval (ms) to check usage (default: 30000 = 30s, 0 = disabled) */ - usageCheckInterval: number; - - // Threshold settings - /** Session usage threshold (0-100) to trigger proactive switch (default: 95) */ - sessionThreshold: number; - /** Weekly usage threshold (0-100) to trigger proactive switch (default: 99) */ - weeklyThreshold: number; - - // Reactive recovery - /** Whether to automatically switch on unexpected rate limit (vs. prompting user) */ - autoSwitchOnRateLimit: boolean; - - /** Whether to automatically switch on authentication failure (vs. prompting user) */ - autoSwitchOnAuthFailure: boolean; -} - -// ============================================ -// Queue Routing Types (Rate Limit Recovery) -// ============================================ - -/** - * Reason for profile assignment to a task - */ -export type ProfileAssignmentReason = 'proactive' | 'reactive' | 'manual'; - -/** - * Tracking of running tasks grouped by profile - */ -export interface RunningTasksByProfile { - /** Map of profileId → array of task IDs running on that profile */ - byProfile: Record; - /** Total number of running tasks across all profiles */ - totalRunning: number; -} - -/** - * Profile swap record for tracking history - */ -export interface ProfileSwapRecord { - fromProfileId: string; - fromProfileName: string; - toProfileId: string; - toProfileName: string; - swappedAt: string; - reason: 'capacity' | 'rate_limit' | 'manual' | 'recovery'; - sessionId?: string; - sessionResumed: boolean; } diff --git a/src/shared/types/index.ts b/src/shared/types/index.ts index c386408ce7..aa5f55582f 100644 --- a/src/shared/types/index.ts +++ b/src/shared/types/index.ts @@ -12,7 +12,6 @@ export * from './kanban'; export * from './terminal'; export * from './agent'; export * from './profile'; -export * from './unified-account'; export * from './settings'; export * from './insights'; export * from './app-update'; diff --git a/src/shared/types/ipc.ts b/src/shared/types/ipc.ts index 15d1892703..849c7d28a1 100644 --- a/src/shared/types/ipc.ts +++ b/src/shared/types/ipc.ts @@ -81,7 +81,6 @@ import type { import type { ClaudeProfileSettings, ClaudeProfile, - ClaudeAutoSwitchSettings, ClaudeUsageSnapshot, AllProfilesUsage } from './agent'; @@ -310,21 +309,15 @@ export interface ElectronAPI { cancelClaudeAuthLogin: (profileId: string) => Promise; /** Listen for OAuth subprocess progress events */ onClaudeAuthLoginProgress: (callback: (data: { status: string; message?: string }) => void) => () => void; - /** Get auto-switch settings */ - getAutoSwitchSettings: () => Promise>; - /** Update auto-switch settings */ - updateAutoSwitchSettings: (settings: Partial) => Promise; /** Request usage fetch from a terminal (sends /usage command) */ fetchClaudeUsage: (terminalId: string) => Promise; - /** Get the best available profile (for manual switching) */ - getBestAvailableProfile: (excludeProfileId?: string) => Promise>; /** Listen for SDK/CLI rate limit events (non-terminal) */ /** Listen for auth failure events (401 errors requiring re-authentication) */ onAuthFailure: (callback: (info: AuthFailureInfo) => void) => () => void; /** Retry a rate-limited operation with a different profile */ retryWithProfile: (request: RetryWithProfileRequest) => Promise; - // Usage Monitoring (Proactive Account Switching) + // Usage Monitoring /** Request current usage snapshot */ requestUsageUpdate: () => Promise>; /** Request all profiles usage immediately (for startup/refresh) @@ -334,13 +327,6 @@ export interface ElectronAPI { /** Listen for usage data updates */ /** Usage of the account in use; null right after switching to an account whose usage isn't known yet */ onUsageUpdated: (callback: (usage: ClaudeUsageSnapshot | null) => void) => () => void; - /** Listen for proactive swap notifications */ - onProactiveSwapNotification: (callback: (notification: { - fromProfile: { id: string; name: string }; - toProfile: { id: string; name: string }; - reason: string; - usageSnapshot: ClaudeUsageSnapshot; - }) => void) => () => void; /** Listen for all profiles usage updates (for multi-profile display) */ onAllProfilesUsageUpdated?: (callback: (allProfilesUsage: AllProfilesUsage) => void) => () => void; @@ -572,9 +558,6 @@ export interface ElectronAPI { refreshWslAvailability: () => Promise>; /** Restart the app (applies a changed shell setting) */ relaunchApp: () => Promise; - - // Queue Routing API (rate limit recovery) - queue: import('../../preload/api/queue-api').QueueAPI; } /** Platform information exposed via contextBridge for platform-specific behavior */ diff --git a/src/shared/types/terminal.ts b/src/shared/types/terminal.ts index 3a51c5a993..12cf58b8d8 100644 --- a/src/shared/types/terminal.ts +++ b/src/shared/types/terminal.ts @@ -70,26 +70,10 @@ export interface SDKRateLimitInfo { profileId: string; /** Profile name for display */ profileName?: string; - /** Suggested alternative profile */ - suggestedProfile?: { - id: string; - name: string; - }; /** When detected */ detectedAt: Date; /** Original error message */ originalError?: string; - - // Auto-swap information (NEW) - /** Whether this rate limit was automatically handled via account swap */ - wasAutoSwapped?: boolean; - /** Profile that was swapped to (if auto-swapped) */ - swappedToProfile?: { - id: string; - name: string; - }; - /** Why the swap occurred: 'proactive' (before limit) or 'reactive' (after limit hit) */ - swapReason?: 'proactive' | 'reactive'; } /** diff --git a/src/shared/types/unified-account.ts b/src/shared/types/unified-account.ts deleted file mode 100644 index 58c74ab2f3..0000000000 --- a/src/shared/types/unified-account.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Unified Account Types - * - * Types for representing both OAuth accounts and API profiles in a unified format. - * Used by the priority list to display and manage all accounts in a single interface. - * - * For conversion utilities and helper functions, see shared/utils/unified-account.ts - */ - -/** - * Type discriminator for unified accounts - */ -type UnifiedAccountType = 'oauth' | 'api'; - -/** - * Type of rate limit that was hit - */ -export type RateLimitType = 'session' | 'weekly'; - -/** - * Unified account representation for the priority list. - * - * This interface provides a common format for both OAuth accounts (Claude subscriptions) - * and API profiles (custom endpoints), enabling unified display and management. - * - * Key concepts: - * - Only ONE account should have `isActive: true` at any time (the currently in-use account) - * - `isNext` indicates the fallback account that will be used next - * - Priority is determined by position in the list (index 0 = highest priority) - */ -export interface UnifiedAccount { - /** Unique identifier for this account */ - id: string; - - /** Internal name/key for the account */ - name: string; - - /** Account type discriminator */ - type: UnifiedAccountType; - - /** Human-friendly display name */ - displayName: string; - - /** email for OAuth accounts, baseUrl for API profiles */ - identifier: string; - - /** TRUE only for the ONE account currently in use */ - isActive: boolean; - - /** TRUE for the account that will be used next (first available after active) */ - isNext: boolean; - - /** Whether this account is available for use (authenticated, not rate limited) */ - isAvailable: boolean; - - /** TRUE for API profiles (pay-per-use without rate limits) */ - hasUnlimitedUsage: boolean; - - /** Session usage percentage (0-100), only for OAuth accounts */ - sessionPercent?: number; - - /** Weekly usage percentage (0-100), only for OAuth accounts */ - weeklyPercent?: number; - - /** Whether this account is currently rate limited */ - isRateLimited?: boolean; - - /** Which type of limit was hit, if rate limited */ - rateLimitType?: RateLimitType; - - /** Whether this OAuth account has valid authentication */ - isAuthenticated?: boolean; - - /** - * Set when this account has identical usage to another OAuth account. - * This may indicate the same underlying Anthropic account registered twice. - */ - isDuplicateUsage?: boolean; - - /** - * Set when this OAuth account has an invalid refresh token and needs re-authentication. - * The user should be prompted to log in again. - */ - needsReauthentication?: boolean; -} diff --git a/src/shared/utils/unified-account.ts b/src/shared/utils/unified-account.ts deleted file mode 100644 index 49bd2eec03..0000000000 --- a/src/shared/utils/unified-account.ts +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Unified Account Utilities - * - * Conversion utilities and helpers for unified account management. - * These functions convert between OAuth/API profiles and the unified account format. - */ - -import type { ClaudeProfile } from '../types/agent'; -import type { APIProfile } from '../types/profile'; -import type { UnifiedAccount, RateLimitType } from '../types/unified-account'; - -// ============================================ -// Constants -// ============================================ - -/** - * ID prefix for OAuth accounts in unified format - */ -export const OAUTH_ID_PREFIX = 'oauth-'; - -/** - * ID prefix for API accounts in unified format - */ -const API_ID_PREFIX = 'api-'; - -// ============================================ -// Conversion Functions -// ============================================ - -/** - * Convert a ClaudeProfile (OAuth) to UnifiedAccount format - * - * @param profile - The OAuth profile to convert - * @param isActive - Whether this is the currently active account - * @param options - Additional options for conversion - * @param options.isRateLimited - Whether the profile is currently rate limited - * @param options.rateLimitType - The type of rate limit (session or weekly) - * @param options.isAuthenticated - Whether the profile is authenticated (REQUIRED - must be computed by caller) - */ -export function claudeProfileToUnified( - profile: ClaudeProfile, - isActive: boolean, - options?: { - isRateLimited?: boolean; - rateLimitType?: RateLimitType; - isAuthenticated?: boolean; - } -): UnifiedAccount { - // Check for rate limit from profile's rate limit events - const now = new Date(); - const activeRateLimit = profile.rateLimitEvents?.find(e => e.resetAt > now); - const isRateLimited = options?.isRateLimited ?? !!activeRateLimit; - // Use explicit isAuthenticated from options, falling back to profile property (which may be undefined for raw profiles) - const isAuthenticated = options?.isAuthenticated ?? profile.isAuthenticated ?? false; - - // Derive isAvailable from the computed values - const isAvailable = !!(isAuthenticated && !isRateLimited); - - return { - id: `${OAUTH_ID_PREFIX}${profile.id}`, - name: profile.name, - type: 'oauth', - displayName: profile.name, - identifier: profile.email || profile.id, - isActive, - isNext: false, // Computed later based on priority order - isAvailable, - hasUnlimitedUsage: false, // OAuth accounts have usage limits - sessionPercent: profile.usage?.sessionUsagePercent, - weeklyPercent: profile.usage?.weeklyUsagePercent, - isRateLimited, - rateLimitType: options?.rateLimitType ?? activeRateLimit?.type, - isAuthenticated, - needsReauthentication: false // Set separately if needed - }; -} - -/** - * Convert an APIProfile to UnifiedAccount format - * - * @param profile - The API profile to convert - * @param isActive - Whether this is the currently active account - * @param isAuthenticated - Whether the API key is valid (has been tested). Defaults to false for safety. - */ -export function apiProfileToUnified( - profile: APIProfile, - isActive: boolean, - isAuthenticated: boolean = false -): UnifiedAccount { - // API profiles are available if they have a valid API key - // They have unlimited usage (pay-per-use) - const isAvailable = isAuthenticated && !!profile.apiKey; - - return { - id: `${API_ID_PREFIX}${profile.id}`, - name: profile.name, - type: 'api', - displayName: profile.name, - identifier: profile.baseUrl, - isActive, - isNext: false, // Computed later based on priority order - isAvailable, - hasUnlimitedUsage: true, // API profiles are pay-per-use with no rate limits - sessionPercent: undefined, // Not applicable to API profiles - weeklyPercent: undefined, // Not applicable to API profiles - isRateLimited: false, // API profiles don't have rate limits - rateLimitType: undefined, - isAuthenticated, - needsReauthentication: false - }; -} \ No newline at end of file From 1e0f421446f416262b58a93f31323ab03d2ba0c3 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sat, 7 Nov 2026 22:12:31 +0400 Subject: [PATCH 02/74] feat(api-profiles): optional key for localhost, required default model - A base URL starting with http://localhost (any port) can be saved without an API key; such a profile sends a placeholder credential to Claude Code and the connection test, which need one. - The default model is required. Haiku, Sonnet and Opus follow it while empty or still set to it, until another model is picked for them. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 +- package.json | 2 +- src/main/ipc-handlers/profile-handlers.ts | 5 +- src/main/services/profile/profile-service.ts | 32 ++++-- .../settings/ModelSearchableSelect.tsx | 6 +- .../settings/ProfileEditDialog.test.tsx | 70 ++++++++++++ .../components/settings/ProfileEditDialog.tsx | 107 ++++++++++++------ .../components/settings/ProfileList.tsx | 2 +- src/shared/i18n/locales/en/settings.json | 10 +- src/shared/utils/api-profile-key.ts | 23 ++++ 10 files changed, 204 insertions(+), 57 deletions(-) create mode 100644 src/shared/utils/api-profile-key.ts diff --git a/package-lock.json b/package-lock.json index 617807417b..33b2304686 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.1", + "version": "1.6.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.1", + "version": "1.6.2", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index 88e4ac3af6..7691e116c9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.1", + "version": "1.6.2", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/main/ipc-handlers/profile-handlers.ts b/src/main/ipc-handlers/profile-handlers.ts index 9b522a6553..16cf358205 100644 --- a/src/main/ipc-handlers/profile-handlers.ts +++ b/src/main/ipc-handlers/profile-handlers.ts @@ -12,6 +12,7 @@ import { ipcMain } from 'electron'; import { IPC_CHANNELS } from '../../shared/constants'; +import { isApiKeyOptional } from '../../shared/utils/api-profile-key'; import type { IPCResult } from '../../shared/types'; import type { APIProfile, ProfileFormData, ProfilesFile, TestConnectionResult, DiscoverModelsResult } from '@shared/types/profile'; import { @@ -204,7 +205,7 @@ export function registerProfileHandlers(): void { }; } - if (!apiKey || apiKey.trim() === '') { + if ((!apiKey || apiKey.trim() === '') && !isApiKeyOptional(baseUrl)) { clearTimeout(timeoutId); activeTestConnections.delete(requestId); return { @@ -290,7 +291,7 @@ export function registerProfileHandlers(): void { }; } - if (!apiKey || apiKey.trim() === '') { + if ((!apiKey || apiKey.trim() === '') && !isApiKeyOptional(baseUrl)) { clearTimeout(timeoutId); activeDiscoverModelsRequests.delete(requestId); return { diff --git a/src/main/services/profile/profile-service.ts b/src/main/services/profile/profile-service.ts index fb267ea30b..afcb2311fc 100644 --- a/src/main/services/profile/profile-service.ts +++ b/src/main/services/profile/profile-service.ts @@ -15,6 +15,7 @@ import Anthropic, { import { loadProfilesFile, generateProfileId, atomicModifyProfiles } from './profile-manager'; import type { APIProfile, TestConnectionResult, ModelInfo, DiscoverModelsResult } from '@shared/types/profile'; +import { apiKeyToSend, isApiKeyOptional } from '@shared/utils/api-profile-key'; /** * Input type for creating a profile (without id, createdAt, updatedAt) @@ -69,6 +70,15 @@ export function validateApiKey(apiKey: string): boolean { return hasValidChars; } +/** + * Validate a profile's API key for its base URL: a local endpoint (`http://localhost`) takes any + * key or none, others need a key in a valid format + */ +export function validateProfileApiKey(baseUrl: string, apiKey: string | undefined): boolean { + if (isApiKeyOptional(baseUrl)) return !/\s/.test(apiKey?.trim() ?? ''); + return validateApiKey(apiKey ?? ''); +} + /** * Delete a profile with validation * Throws errors for validation failures @@ -110,8 +120,8 @@ export async function createProfile(input: CreateProfileInput): Promise> { // Map profile fields to SDK env vars const envVars: Record = { ANTHROPIC_BASE_URL: profile.baseUrl || '', - ANTHROPIC_AUTH_TOKEN: profile.apiKey || '', + ANTHROPIC_AUTH_TOKEN: apiKeyToSend(profile.baseUrl || '', profile.apiKey), ANTHROPIC_MODEL: profile.models?.default || '', ANTHROPIC_DEFAULT_HAIKU_MODEL: profile.models?.haiku || '', ANTHROPIC_DEFAULT_SONNET_MODEL: profile.models?.sonnet || '', @@ -292,7 +302,7 @@ export async function testConnection( signal?: AbortSignal ): Promise { // Validate API key first (key format doesn't depend on URL normalization) - if (!validateApiKey(apiKey)) { + if (!validateProfileApiKey(baseUrl, apiKey)) { return { success: false, errorType: 'auth', @@ -373,7 +383,7 @@ export async function testConnection( try { // Create Anthropic client with SDK const client = new Anthropic({ - apiKey, + apiKey: apiKeyToSend(baseUrl, apiKey), baseURL: normalizedUrl, timeout: 10000, // 10 seconds maxRetries: 0, // Disable retries for immediate feedback @@ -497,7 +507,7 @@ export async function discoverModels( signal?: AbortSignal ): Promise { // Validate API key first - if (!validateApiKey(apiKey)) { + if (!validateProfileApiKey(baseUrl, apiKey)) { const error: Error & { errorType?: string } = new Error('Authentication failed. Please check your API key.'); error.errorType = 'auth'; throw error; @@ -538,7 +548,7 @@ export async function discoverModels( try { // Create Anthropic client with SDK const client = new Anthropic({ - apiKey, + apiKey: apiKeyToSend(baseUrl, apiKey), baseURL: normalizedUrl, timeout: 10000, // 10 seconds maxRetries: 0, // Disable retries for immediate feedback diff --git a/src/renderer/components/settings/ModelSearchableSelect.tsx b/src/renderer/components/settings/ModelSearchableSelect.tsx index c76084f820..4805b738e1 100644 --- a/src/renderer/components/settings/ModelSearchableSelect.tsx +++ b/src/renderer/components/settings/ModelSearchableSelect.tsx @@ -39,6 +39,8 @@ interface ModelSearchableSelectProps { disabled?: boolean; /** Additional CSS classes */ className?: string; + /** Id of the input, for its label */ + id?: string; } /** @@ -62,7 +64,8 @@ export function ModelSearchableSelect({ baseUrl, apiKey, disabled = false, - className + className, + id }: ModelSearchableSelectProps) { const { t } = useTranslation(); const resolvedPlaceholder = placeholder ?? t('settings:modelSelect.placeholder'); @@ -222,6 +225,7 @@ export function ModelSearchableSelect({ {/* Main input with loading/dropdown indicator */}
{ handleManualInputChange(e.target.value); diff --git a/src/renderer/components/settings/ProfileEditDialog.test.tsx b/src/renderer/components/settings/ProfileEditDialog.test.tsx index 8ba251903a..ef98376cf9 100644 --- a/src/renderer/components/settings/ProfileEditDialog.test.tsx +++ b/src/renderer/components/settings/ProfileEditDialog.test.tsx @@ -337,6 +337,7 @@ describe('ProfileEditDialog - Validation', () => { name: 'Test', baseUrl: 'https://api.example.com', apiKey: 'sk-ant-test123', + models: { default: 'claude-sonnet-4-6' }, createdAt: Date.now(), updatedAt: Date.now() }; @@ -698,3 +699,72 @@ describe('ProfileEditDialog - Test Connection Feature', () => { }); }); }); + +describe('ProfileEditDialog - Local endpoints and default model', () => { + const mockSaveProfile = vi.fn(); + + beforeEach(() => { + vi.clearAllMocks(); + mockSaveProfile.mockResolvedValue(true); + (useSettingsStore as unknown as ReturnType).mockReturnValue({ + saveProfile: mockSaveProfile, + discoverModels: vi.fn().mockResolvedValue(null), + profilesLoading: false, + profilesError: null + }); + }); + + const fill = (baseUrl: string, apiKey = '') => { + fireEvent.change(screen.getByLabelText(/name/i), { target: { value: 'Local' } }); + fireEvent.change(screen.getByLabelText(/base url/i), { target: { value: baseUrl } }); + if (apiKey) fireEvent.change(screen.getByLabelText(/api key/i), { target: { value: apiKey } }); + }; + + it('saves a localhost profile (any port) without an API key', async () => { + render(); + fill('http://localhost:11434'); + fireEvent.change(screen.getByLabelText(/default model/i), { target: { value: 'qwen3' } }); + fireEvent.click(screen.getByText(/save profile/i)); + + await waitFor(() => { + expect(mockSaveProfile).toHaveBeenCalledWith(expect.objectContaining({ + baseUrl: 'http://localhost:11434', + apiKey: '' + })); + }); + }); + + it('still requires an API key for other endpoints', async () => { + render(); + fill('https://api.example.com'); + fireEvent.change(screen.getByLabelText(/default model/i), { target: { value: 'claude-sonnet-4-6' } }); + fireEvent.click(screen.getByText(/save profile/i)); + + expect(await screen.findByText('API Key is required')).toBeInTheDocument(); + expect(mockSaveProfile).not.toHaveBeenCalled(); + }); + + it('requires the default model', async () => { + render(); + fill('http://localhost:8080'); + fireEvent.click(screen.getByText(/save profile/i)); + + expect(await screen.findByText('Default model is required')).toBeInTheDocument(); + expect(mockSaveProfile).not.toHaveBeenCalled(); + }); + + it('fills Haiku, Sonnet and Opus with the default model until they are changed', () => { + render(); + const defaultInput = screen.getByLabelText(/default model/i); + fireEvent.change(defaultInput, { target: { value: 'glm-4.6' } }); + expect(screen.getByLabelText(/haiku model/i)).toHaveValue('glm-4.6'); + expect(screen.getByLabelText(/sonnet model/i)).toHaveValue('glm-4.6'); + expect(screen.getByLabelText(/opus model/i)).toHaveValue('glm-4.6'); + + fireEvent.change(screen.getByLabelText(/haiku model/i), { target: { value: 'glm-4.5-air' } }); + fireEvent.change(defaultInput, { target: { value: 'glm-5' } }); + expect(screen.getByLabelText(/haiku model/i)).toHaveValue('glm-4.5-air'); + expect(screen.getByLabelText(/sonnet model/i)).toHaveValue('glm-5'); + expect(screen.getByLabelText(/opus model/i)).toHaveValue('glm-5'); + }); +}); diff --git a/src/renderer/components/settings/ProfileEditDialog.tsx b/src/renderer/components/settings/ProfileEditDialog.tsx index 9ab4d10254..79746e7db3 100644 --- a/src/renderer/components/settings/ProfileEditDialog.tsx +++ b/src/renderer/components/settings/ProfileEditDialog.tsx @@ -5,8 +5,8 @@ * Supports all profile fields including optional model name mappings. * * Features: - * - Required fields: Name, Base URL, API Key - * - Optional model fields: Default, Haiku, Sonnet, Opus + * - Required fields: Name, Base URL, API Key (optional for http://localhost, any port), Default model + * - Haiku, Sonnet and Opus models follow the default model until set to another one * - Form validation with error display * - Save button triggers store action (create or update) * - Close button cancels without saving @@ -33,6 +33,7 @@ import { ModelSearchableSelect } from './ModelSearchableSelect'; import { isValidUrl, isValidApiKey } from '../../lib/profile-utils'; import type { APIProfile, ProfileFormData, } from '@shared/types/profile'; import { maskApiKey } from '../../lib/profile-utils'; +import { isApiKeyOptional } from '../../../shared/utils/api-profile-key'; import { API_PROVIDER_PRESETS } from '../../../shared/constants'; interface ProfileEditDialogProps { @@ -78,6 +79,10 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof const [nameError, setNameError] = useState(null); const [urlError, setUrlError] = useState(null); const [keyError, setKeyError] = useState(null); + const [modelError, setModelError] = useState(null); + + // A local endpoint (http://localhost, any port) may run without an API key + const keyOptional = isApiKeyOptional(baseUrl); // AbortController ref for test connection cleanup const abortControllerRef = useRef(null); @@ -137,6 +142,7 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof setNameError(null); setUrlError(null); setKeyError(null); + setModelError(null); } else { // Clear test result display when dialog closes setShowTestResult(false); @@ -176,21 +182,34 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof setUrlError(null); } - // API Key validation (only in create mode or when changing key in edit mode) + // API Key validation (only in create mode or when changing key in edit mode); a local + // endpoint takes any key or none if (!isEditMode || isChangingApiKey) { if (!apiKey.trim()) { - setKeyError(t('settings:apiProfiles.validation.apiKeyRequired')); - isValid = false; - } else if (!isValidApiKey(apiKey)) { + setKeyError(keyOptional ? null : t('settings:apiProfiles.validation.apiKeyRequired')); + if (!keyOptional) isValid = false; + } else if (!keyOptional && !isValidApiKey(apiKey)) { setKeyError(t('settings:apiProfiles.validation.apiKeyInvalid')); isValid = false; } else { setKeyError(null); } + } else if (!profile?.apiKey && !keyOptional) { + // A profile saved without a key that no longer points at a local endpoint + setKeyError(t('settings:apiProfiles.validation.apiKeyRequired')); + isValid = false; } else { setKeyError(null); } + // Default model validation + if (!defaultModel.trim()) { + setModelError(t('settings:apiProfiles.validation.defaultModelRequired')); + isValid = false; + } else { + setModelError(null); + } + return isValid; }; @@ -206,7 +225,7 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof setUrlError(t('settings:apiProfiles.validation.baseUrlRequired')); return; } - if (!apiKeyForTest.trim()) { + if (!apiKeyForTest.trim() && !keyOptional) { setKeyError(t('settings:apiProfiles.validation.apiKeyRequired')); return; } @@ -222,12 +241,25 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof if (!name.trim() || !baseUrl.trim()) { return false; } + // A local endpoint may run without a key + if (keyOptional) return true; // In create mode or when changing key, need apiKey if (!isEditMode || isChangingApiKey) { return apiKey.trim().length > 0; } - // In edit mode without changing key, existing profile has apiKey - return true; + // In edit mode without changing key, the existing profile's key + return !!profile?.apiKey; + }; + + // Haiku, Sonnet and Opus follow the default model while empty or still set to it + const changeDefaultModel = (value: string) => { + const previous = defaultModel; + const follow = (current: string) => (!current.trim() || current === previous ? value : current); + setHaikuModel(follow); + setSonnetModel(follow); + setOpusModel(follow); + setDefaultModel(value); + if (value.trim()) setModelError(null); }; // Handle save @@ -244,15 +276,12 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof baseUrl: baseUrl.trim(), // Only update API key if user is changing it ...(isChangingApiKey && { apiKey: apiKey.trim() }), - // Update models if provided - ...(defaultModel || haikuModel || sonnetModel || opusModel ? { - models: { - ...(defaultModel && { default: defaultModel.trim() }), - ...(haikuModel && { haiku: haikuModel.trim() }), - ...(sonnetModel && { sonnet: sonnetModel.trim() }), - ...(opusModel && { opus: opusModel.trim() }) - } - } : { models: undefined }) + models: { + default: defaultModel.trim(), + ...(haikuModel.trim() && { haiku: haikuModel.trim() }), + ...(sonnetModel.trim() && { sonnet: sonnetModel.trim() }), + ...(opusModel.trim() && { opus: opusModel.trim() }) + } }; const success = await updateProfile(updatedProfile); if (success) { @@ -264,18 +293,15 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof const profileData: ProfileFormData = { name: name.trim(), baseUrl: baseUrl.trim(), - apiKey: apiKey.trim() + apiKey: apiKey.trim(), + models: { + default: defaultModel.trim(), + ...(haikuModel.trim() && { haiku: haikuModel.trim() }), + ...(sonnetModel.trim() && { sonnet: sonnetModel.trim() }), + ...(opusModel.trim() && { opus: opusModel.trim() }) + } }; - // Add optional models if provided - if (defaultModel || haikuModel || sonnetModel || opusModel) { - profileData.models = {}; - if (defaultModel) profileData.models.default = defaultModel.trim(); - if (haikuModel) profileData.models.haiku = haikuModel.trim(); - if (sonnetModel) profileData.models.sonnet = sonnetModel.trim(); - if (opusModel) profileData.models.opus = opusModel.trim(); - } - const success = await saveProfile(profileData); if (success) { onOpenChange(false); @@ -365,17 +391,19 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof

- {/* API Key field (required for create, masked in edit mode) */} + {/* API Key field (required for create unless the endpoint is local, masked in edit mode) */}
{isEditMode && !isChangingApiKey && profile ? ( // Edit mode: show masked API key
@@ -394,7 +422,11 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof setApiKey(e.target.value)} className={keyError ? 'border-destructive' : ''} @@ -453,7 +485,7 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof
)} - {/* Optional model mappings */} + {/* Model mappings: the default model is required, the others follow it */}

{t('settings:apiProfiles.models.title')}

@@ -465,15 +497,17 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof
+ {modelError &&

{modelError}

}
@@ -482,6 +516,7 @@ export function ProfileEditDialog({ open, onOpenChange, onSaved, profile }: Prof {[ getHostFromUrl(profile.baseUrl), - maskApiKey(profile.apiKey), + profile.apiKey ? maskApiKey(profile.apiKey) : null, customModels.length > 0 ? t('settings:apiProfiles.customModels', { models: customModels.join(', ') }) : null diff --git a/src/shared/i18n/locales/en/settings.json b/src/shared/i18n/locales/en/settings.json index a4ca9d03be..904d24c97f 100644 --- a/src/shared/i18n/locales/en/settings.json +++ b/src/shared/i18n/locales/en/settings.json @@ -78,7 +78,8 @@ "name": "My Custom API", "preset": "Choose a provider preset", "baseUrl": "https://api.anthropic.com", - "apiKey": "sk-ant-..." + "apiKey": "sk-ant-...", + "apiKeyOptional": "Optional for localhost" }, "hints": { "preset": "Presets fill the base URL; you still need to paste your API key.", @@ -89,7 +90,8 @@ "baseUrlRequired": "Base URL is required", "baseUrlInvalid": "Invalid URL format (must be http:// or https://)", "apiKeyRequired": "API Key is required", - "apiKeyInvalid": "Invalid API Key format" + "apiKeyInvalid": "Invalid API Key format", + "defaultModelRequired": "Default model is required" }, "actions": { "save": "Save profile", @@ -105,8 +107,8 @@ "failure": "Connection failed" }, "models": { - "title": "Model name mappings (optional)", - "description": "Select models from your API provider. Leave blank to use defaults.", + "title": "Model name mappings", + "description": "Select models from your API provider. Haiku, Sonnet and Opus use the default model unless you pick another one.", "defaultLabel": "Default model", "haikuLabel": "Haiku model", "sonnetLabel": "Sonnet model", diff --git a/src/shared/utils/api-profile-key.ts b/src/shared/utils/api-profile-key.ts new file mode 100644 index 0000000000..d74083f63f --- /dev/null +++ b/src/shared/utils/api-profile-key.ts @@ -0,0 +1,23 @@ +/** + * API profiles on a local endpoint (`http://localhost`, any port) may have no API key. Claude Code + * and the Anthropic SDK still need a credential to send, so such a profile sends a placeholder. + */ + +/** Sent as the credential of a local API profile without a key */ +export const LOCAL_API_KEY_PLACEHOLDER = 'no-key'; + +/** Whether the base URL is a local endpoint (`http://localhost`, with or without a port or path) */ +export function isLocalhostBaseUrl(baseUrl: string): boolean { + return /^http:\/\/localhost(?=[:/?#]|$)/i.test(baseUrl.trim()); +} + +/** Whether a profile with this base URL can be saved without an API key */ +export function isApiKeyOptional(baseUrl: string): boolean { + return isLocalhostBaseUrl(baseUrl); +} + +/** The credential to send for a profile: its key, or the placeholder for a local one without */ +export function apiKeyToSend(baseUrl: string, apiKey: string | undefined): string { + const key = apiKey?.trim() ?? ''; + return key || (isApiKeyOptional(baseUrl) ? LOCAL_API_KEY_PLACEHOLDER : ''); +} From f7e1973f2062edf6271fedb2cc4861245bb5bcfa Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sat, 7 Nov 2026 22:12:34 +0400 Subject: [PATCH 03/74] feat(accounts): delete Claude accounts, one "In use" label - An account's Details dialog can delete it after a confirmation: it is signed out with `claude auth logout` and its config dir removed (for the default ~/.claude only the settings that set up how it reaches Claude); projects that chose it lose the reference. The account in use, the only account, one with running tasks and a default-dir setup defined by the environment or managed settings can't be deleted. - While an API profile is in use, no Claude account is marked in use; using a Claude account switches the API profile off. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 11 +- package-lock.json | 4 +- package.json | 2 +- .../__tests__/claude-profile-detected.test.ts | 28 ++++- src/main/claude-profile-manager.ts | 33 +++++ .../__tests__/account-deletion.test.ts | 110 +++++++++++++++++ src/main/claude-profile/account-deletion.ts | 116 ++++++++++++++++++ .../claude-profile/claude-code-detection.ts | 12 ++ .../terminal-handlers-task-session.test.ts | 7 +- src/main/ipc-handlers/terminal-handlers.ts | 22 +++- .../settings/ClaudeAccountsSection.tsx | 30 ++++- .../settings/DetectedAccountDialog.tsx | 94 +++++++++++++- .../__tests__/ClaudeAccountsSection.test.tsx | 46 ++++++- src/shared/i18n/locales/en/settings.json | 12 +- src/shared/types/agent.ts | 5 + 15 files changed, 504 insertions(+), 28 deletions(-) create mode 100644 src/main/claude-profile/__tests__/account-deletion.test.ts create mode 100644 src/main/claude-profile/account-deletion.ts diff --git a/CLAUDE.md b/CLAUDE.md index 131278530d..fa51c0cecc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -533,14 +533,17 @@ overlays use `AgentLoader` (`ui/agent-loader.tsx`, the live agent node bouncing) **IPC** — Handlers in `src/main/ipc-handlers/` (by domain), safe APIs exposed in `src/preload/`, renderer calls `window.electronAPI.*`. -**Agent management** (`src/main/agent/`) — `agent-manager.ts` (starts, stops and restarts Claude Code task runs and -relays their events), `agent-state.ts` (profile/session assignment for account swapping). +**Agent management** (`src/main/agent/`) — `agent-manager.ts` (starts and stops Claude Code task runs and +relays their events), `agent-state.ts` (the profile and session of each running task). **Claude profiles** (`src/main/claude-profile/`) — `credential-utils.ts` (OS keychain), `token-refresh.ts` (OAuth -refresh), `usage-monitor.ts` (usage and rate limits), `profile-scorer.ts` (profile selection). On every start, +refresh), `usage-monitor.ts` (usage and rate limits). On every start, `claude-code-detection.ts` finds Claude Code's own setups (`~/.claude`, `CLAUDE_CONFIG_DIR`, `~/.claude-*`: subscription sign-in, cloud provider, API key or gateway, from managed settings, the dir's `settings.json` and the environment) and -lists them as accounts (`ClaudeProfile.detected`): usable and renamable, never removed. Claude Code's default `~/.claude` +lists them as accounts (`ClaudeProfile.detected`): usable and renamable. Deleting one (its Details dialog; never the account in use, the only one, or one with running +tasks) signs it out with `claude auth logout` and removes its config dir, or for the default `~/.claude` only the +settings that set up how it reaches Claude (`claude-profile/account-deletion.ts`); projects that chose it lose the +reference. Claude Code's default `~/.claude` runs without `CLAUDE_CONFIG_DIR`, keeps its sign-in in `~/.claude.json` and its plain keychain entry (`config-dir-paths.ts`). diff --git a/package-lock.json b/package-lock.json index 33b2304686..d2e17fc98c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.2", + "version": "1.6.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.2", + "version": "1.6.3", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index 7691e116c9..ad0f135a43 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.2", + "version": "1.6.3", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/main/__tests__/claude-profile-detected.test.ts b/src/main/__tests__/claude-profile-detected.test.ts index bdd061a18b..13821952e2 100644 --- a/src/main/__tests__/claude-profile-detected.test.ts +++ b/src/main/__tests__/claude-profile-detected.test.ts @@ -1,6 +1,6 @@ /** * Accounts found in Claude Code's configuration, synced on every start: - * - each setup becomes an account (usable, not removable, renamable) + * - each setup becomes an account (usable, renamable; deleted on purpose unless it's in use) * - accounts added the old way leave the list once a setup is detected * - a later start updates its values and keeps its name; a setup that's gone drops its account * - a cloud provider setup counts as signed in (Claude Code authenticates it) @@ -98,4 +98,30 @@ describe('accounts found in Claude Code configuration', () => { expect(profiles.some((profile) => profile.detected)).toBe(false); expect(profiles.map((profile) => profile.name)).toEqual(['Primary']); }); + + it('deletes an account only when it is not the one in use nor the only one, and moves references off it', async () => { + const workDir = join(root, 'home', '.claude-work'); + const awsDir = join(root, 'home', '.claude-aws'); + mkdirSync(workDir, { recursive: true }); + mkdirSync(awsDir, { recursive: true }); + setupsRef.setups = [bedrock(workDir, 'us-east-1'), bedrock(awsDir, 'eu-west-1')]; + + const manager = await start(); + const [work, aws] = manager.getSettings().profiles; + expect(manager.setActiveProfile(aws.id)).toBe(true); + + // The account in use can't be deleted + expect(manager.detectedAccountDeletionBlocker(aws.id)).toMatch(/in use/); + expect(manager.detectedAccountDeletionBlocker(work.id)).toBeNull(); + + // Its files gone (account-deletion.ts), it leaves the accounts + setupsRef.setups = [bedrock(awsDir, 'eu-west-1')]; + manager.removeDetectedAccount(work.id); + expect(manager.getSettings().profiles.map((profile) => profile.id)).toEqual([aws.id]); + expect(manager.getSettings().activeProfileId).toBe(aws.id); + expect(manager.redetectAccounts().profiles.map((profile) => profile.id)).toEqual([aws.id]); + + // The only account left can't be deleted + expect(manager.detectedAccountDeletionBlocker(aws.id)).not.toBeNull(); + }); }); diff --git a/src/main/claude-profile-manager.ts b/src/main/claude-profile-manager.ts index e32720cd29..64949a9a63 100644 --- a/src/main/claude-profile-manager.ts +++ b/src/main/claude-profile-manager.ts @@ -775,6 +775,39 @@ export class ClaudeProfileManager { return true; } + /** + * Why an account found in Claude Code's configuration can't be deleted, or null when it can: + * not the account in use, not the only account, and not set up from outside its config dir + * (environment variables or managed settings, which would list it again) + */ + detectedAccountDeletionBlocker(profileId: string): string | null { + const profile = this.getProfile(profileId); + if (!profile) return 'Account not found'; + if (!profile.detected || !profile.configDir) return "Not an account from Claude Code's configuration"; + if (profile.id === this.data.activeProfileId) return "The account in use can't be deleted"; + if (this.data.profiles.length <= 1) return "The only Claude account can't be deleted"; + if (profile.detected.isDefaultDir && profile.detected.definedOutside) { + return 'This account is set up by environment variables or managed settings outside Claude Code\'s config dir; remove them there'; + } + return null; + } + + /** + * Drop a deleted account (see account-deletion.ts, which removed its files) from the accounts. + * References to it move to the account in use. + */ + removeDetectedAccount(profileId: string): void { + const others = this.data.profiles.filter((p) => p.id !== profileId); + if (others.length === this.data.profiles.length || others.length === 0) return; + const removed = this.data.profiles.find((p) => p.id === profileId)!; + this.data.profiles = others; + const fallback = others.find((p) => p.id === this.data.activeProfileId) + ?? others.find((p) => p.detected?.isDefaultDir) ?? others[0]; + if (removed.isDefault && !others.some((p) => p.isDefault)) fallback.isDefault = true; + this.remapRemovedProfiles(new Map([[profileId, fallback.id]])); + this.save(); + } + /** * Rename a profile */ diff --git a/src/main/claude-profile/__tests__/account-deletion.test.ts b/src/main/claude-profile/__tests__/account-deletion.test.ts new file mode 100644 index 0000000000..bbba5b1575 --- /dev/null +++ b/src/main/claude-profile/__tests__/account-deletion.test.ts @@ -0,0 +1,110 @@ +/** + * Deleting a detected Claude account: signed out with Claude Code's own logout, then its config + * dir removed (or, for the default ~/.claude, only its sign-in settings); nothing removed when the + * sign-out fails. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ClaudeProfile } from '../../../shared/types'; + +const homeRef = vi.hoisted(() => ({ dir: '' })); +const runTool = vi.hoisted(() => vi.fn()); + +vi.mock('../../platform/claude-home', () => ({ + getClaudeHome: () => homeRef.dir, + isClaudeHomeInWsl: () => false, +})); +vi.mock('../../platform/runtime-exec', () => ({ runTool })); +vi.mock('../../cli-tool-manager', () => ({ + getToolInfoAsync: vi.fn(async () => ({ found: true, path: '/usr/bin/claude' })), +})); +vi.mock('../credential-utils', () => ({ clearKeychainCache: vi.fn() })); + +import { deleteClaudeCodeAccountFiles } from '../account-deletion'; + +function account(configDir: string, detected: Partial>): ClaudeProfile { + return { + id: 'acc', + name: 'Account', + configDir, + isDefault: false, + createdAt: new Date(), + detected: { provider: 'subscription', isDefaultDir: false, values: [], ...detected }, + } as ClaudeProfile; +} + +beforeEach(() => { + homeRef.dir = mkdtempSync(join(tmpdir(), 'account-deletion-')); + runTool.mockReset(); + runTool.mockResolvedValue({ stdout: '', stderr: '' }); +}); + +afterEach(() => { + rmSync(homeRef.dir, { recursive: true, force: true }); +}); + +describe('deleteClaudeCodeAccountFiles', () => { + it('signs a sign-in out on its own config dir, then removes the dir', async () => { + const dir = join(homeRef.dir, '.claude-2'); + mkdirSync(dir); + writeFileSync(join(dir, '.credentials.json'), '{}'); + + await deleteClaudeCodeAccountFiles(account(dir, { email: 'me@example.com' })); + + expect(runTool).toHaveBeenCalledWith('claude', ['auth', 'logout'], expect.objectContaining({ + env: expect.objectContaining({ CLAUDE_CONFIG_DIR: dir }), + })); + expect(existsSync(dir)).toBe(false); + }); + + it('keeps everything when the sign-out fails', async () => { + const dir = join(homeRef.dir, '.claude-2'); + mkdirSync(dir); + runTool.mockRejectedValue(new Error('logout failed')); + + await expect(deleteClaudeCodeAccountFiles(account(dir, { email: 'me@example.com' }))).rejects.toThrow('logout failed'); + expect(existsSync(dir)).toBe(true); + }); + + it('keeps the default ~/.claude, removing only how it reaches Claude from its settings', async () => { + const dir = join(homeRef.dir, '.claude'); + mkdirSync(dir); + const settings = { + model: 'opus', + apiKeyHelper: '/bin/key', + permissions: { allow: ['Read'] }, + env: { ANTHROPIC_BASE_URL: 'https://gw.example', ANTHROPIC_AUTH_TOKEN: 'secret', ANTHROPIC_MODEL: 'opus', FOO: '1' }, + }; + writeFileSync(join(dir, 'settings.json'), JSON.stringify(settings)); + + await deleteClaudeCodeAccountFiles(account(dir, { provider: 'auth-token', isDefaultDir: true })); + + // No sign-in to sign out + expect(runTool).not.toHaveBeenCalled(); + expect(existsSync(dir)).toBe(true); + expect(JSON.parse(readFileSync(join(dir, 'settings.json'), 'utf-8'))).toEqual({ + model: 'opus', + permissions: { allow: ['Read'] }, + env: { ANTHROPIC_MODEL: 'opus', FOO: '1' }, + }); + }); + + it('signs the default dir out without CLAUDE_CONFIG_DIR', async () => { + const dir = join(homeRef.dir, '.claude'); + mkdirSync(dir); + + await deleteClaudeCodeAccountFiles(account(dir, { isDefaultDir: true, email: 'me@example.com' })); + + const env = runTool.mock.calls[0][2].env as NodeJS.ProcessEnv; + expect(env.CLAUDE_CONFIG_DIR).toBeUndefined(); + expect(existsSync(dir)).toBe(true); + }); + + it('never removes the home dir or one above it', async () => { + await expect(deleteClaudeCodeAccountFiles(account(homeRef.dir, {}))).rejects.toThrow(/Refusing/); + expect(runTool).not.toHaveBeenCalled(); + expect(existsSync(homeRef.dir)).toBe(true); + }); +}); diff --git a/src/main/claude-profile/account-deletion.ts b/src/main/claude-profile/account-deletion.ts new file mode 100644 index 0000000000..1be09ed529 --- /dev/null +++ b/src/main/claude-profile/account-deletion.ts @@ -0,0 +1,116 @@ +/** + * Deleting a Claude account found in Claude Code's configuration (Settings > Accounts, the + * account's Details), so nothing of it is left for detection to list again: + * + * - a subscription sign-in is signed out with Claude Code's own `claude auth logout` on its config + * dir, which removes its credentials (macOS Keychain entry or `.credentials.json`) and the + * account in its `.claude.json` + * - any other config dir (`~/.claude-*`, CLAUDE_CONFIG_DIR) is then removed with everything in it + * - Claude Code's default `~/.claude` stays (it holds the user's settings, skills, plugins and + * history for every account): its settings.json loses the variables and keys that set up how it + * reaches Claude (provider switches, keys, tokens, base URLs); model choices stay + * + * Nothing is removed when the sign-out fails. + */ +import { readFile, rm, writeFile } from 'fs/promises'; +import path from 'path'; +import type { ClaudeProfile } from '../../shared/types'; +import { getToolInfoAsync } from '../cli-tool-manager'; +import { runTool } from '../platform/runtime-exec'; +import { getClaudeHome, isClaudeHomeInWsl } from '../platform/claude-home'; +import { isWindows } from '../platform'; +import { clearKeychainCache } from './credential-utils'; +import { SETUP_CREDENTIAL_SETTINGS } from './claude-code-detection'; + +const LOGOUT_TIMEOUT_MS = 30_000; + +function pathApi(): typeof path { + return isClaudeHomeInWsl() ? path.win32 : path; +} + +/** Sign the config dir's subscription account out with Claude Code's own logout */ +async function signOut(configDir: string, isDefaultDir: boolean): Promise { + const claude = await getToolInfoAsync('claude', { refreshIfMissing: true }); + if (!claude.found || !claude.path) throw new Error('Claude Code CLI not found, so the account could not be signed out'); + const env: NodeJS.ProcessEnv = { ...process.env, CLAUDE_CONFIG_DIR: configDir }; + // Claude Code's default ~/.claude runs without CLAUDE_CONFIG_DIR + if (isDefaultDir) delete env.CLAUDE_CONFIG_DIR; + await runTool('claude', ['auth', 'logout'], { command: claude.path, env, timeout: LOGOUT_TIMEOUT_MS }); + clearKeychainCache(configDir); +} + +/** + * A dir that is safe to remove as a whole: not a filesystem root, and neither the home dir nor + * one of its ancestors + */ +function isRemovableConfigDir(dir: string): boolean { + const paths = pathApi(); + const resolved = paths.resolve(dir); + const home = paths.resolve(getClaudeHome()); + const same = (a: string, b: string) => (isWindows() || isClaudeHomeInWsl() ? a.toLowerCase() === b.toLowerCase() : a === b); + if (same(resolved, paths.parse(resolved).root)) return false; + const relative = paths.relative(resolved, home); + // The home dir itself or a dir above it + return !(same(resolved, home) || (relative && !relative.startsWith('..') && !paths.isAbsolute(relative))); +} + +/** Remove the variables and keys that set up how the dir reaches Claude from its settings.json */ +async function stripSetupSettings(configDir: string): Promise { + const file = pathApi().join(configDir, 'settings.json'); + let text: string; + try { + text = await readFile(file, 'utf-8'); + } catch { + return; + } + let data: Record; + try { + data = JSON.parse(text) as Record; + } catch { + // Claude Code can't read it either; leave the user's file as it is + return; + } + if (!data || typeof data !== 'object') return; + + let changed = false; + for (const key of SETUP_CREDENTIAL_SETTINGS.settings) { + if (key in data) { + delete data[key]; + changed = true; + } + } + const env = data.env; + if (env && typeof env === 'object') { + const vars = env as Record; + for (const name of SETUP_CREDENTIAL_SETTINGS.env) { + if (name in vars) { + delete vars[name]; + changed = true; + } + } + if (Object.keys(vars).length === 0) delete data.env; + } + if (changed) await writeFile(file, `${JSON.stringify(data, null, 2)}\n`, 'utf-8'); +} + +/** Delete a detected account's sign-in and configuration (see the file comment) */ +export async function deleteClaudeCodeAccountFiles(profile: ClaudeProfile): Promise { + const detected = profile.detected; + const configDir = profile.configDir; + if (!detected || !configDir) throw new Error("Not an account from Claude Code's configuration"); + + if (!detected.isDefaultDir && !isRemovableConfigDir(configDir)) { + throw new Error(`Refusing to remove ${configDir}`); + } + + // A subscription sign-in (also one behind another provider) is signed out first + if (detected.provider === 'subscription' || detected.email) { + await signOut(configDir, detected.isDefaultDir); + } + + if (detected.isDefaultDir) { + await stripSetupSettings(configDir); + } else { + await rm(configDir, { recursive: true, force: true }); + } +} diff --git a/src/main/claude-profile/claude-code-detection.ts b/src/main/claude-profile/claude-code-detection.ts index abdee282fb..a93d45944b 100644 --- a/src/main/claude-profile/claude-code-detection.ts +++ b/src/main/claude-profile/claude-code-detection.ts @@ -79,6 +79,15 @@ const SETUP_SETTINGS = ['apiKeyHelper', 'awsAuthRefresh', 'awsCredentialExport', const SECRET = /(KEY|TOKEN|SECRET|HEADERS)/; +/** + * The settings (`env` variables and top-level keys) of a config dir's settings.json that set up + * how it reaches Claude: everything above except model choices, which are the user's preferences + */ +export const SETUP_CREDENTIAL_SETTINGS = { + env: SETUP_VARIABLES.filter((name) => !/MODEL$/.test(name)) as string[], + settings: SETUP_SETTINGS.filter((key) => key !== 'model') as string[], +}; + export interface DetectedSetup extends DetectedClaudeCodeAccount { /** Absolute config dir */ configDir: string; @@ -230,6 +239,8 @@ export function readClaudeCodeSetup(configDir: string, options: DetectionOptions // Where the credentials are defined: the sign-in's credentials file (or its macOS Keychain // entry), or the file (or environment) that configures the provider let credentials: string; + const decidingSource = decidingKey ? effective.get(decidingKey)?.source : undefined; + const definedOutside = provider !== 'subscription' && decidingSource !== user; if (provider === 'subscription') { const file = pathApi().join(configDir, '.credentials.json'); credentials = existsSync(file) || !isMacOS() @@ -247,6 +258,7 @@ export function readClaudeCodeSetup(configDir: string, options: DetectionOptions credentials, ...(provider === 'subscription' || signedIn ? { email, organization: str(account?.organizationName), plan } : {}), values, + ...(definedOutside ? { definedOutside } : {}), }; } diff --git a/src/main/ipc-handlers/__tests__/terminal-handlers-task-session.test.ts b/src/main/ipc-handlers/__tests__/terminal-handlers-task-session.test.ts index 183ad98f80..07fca00b7c 100644 --- a/src/main/ipc-handlers/__tests__/terminal-handlers-task-session.test.ts +++ b/src/main/ipc-handlers/__tests__/terminal-handlers-task-session.test.ts @@ -47,7 +47,7 @@ interface Run { * A stand-in for AgentManager's run lookup that answers the way `keyOf` does: a named project * selects that project's run, and a bare task id is answered only while it means one run. */ -function fakeAgentManager(runs: Run[]): Pick { +function fakeAgentManager(runs: Run[]): Pick { const find = (taskId: string, projectId?: string): Run | undefined => { const matches = runs.filter((run) => run.taskId === taskId && (!projectId || run.projectId === projectId)); return matches.length === 1 ? matches[0] : undefined; @@ -57,8 +57,9 @@ function fakeAgentManager(runs: Run[]): Pick { const run = find(taskId, projectId); return run ? { sessionId: run.sessionId } : undefined; - } - } as Pick; + }, + getRunningTasksByProfile: () => ({ byProfile: {}, totalRunning: runs.length }) + } as Pick; } const followTaskSession = vi.fn(); diff --git a/src/main/ipc-handlers/terminal-handlers.ts b/src/main/ipc-handlers/terminal-handlers.ts index 9a01280b23..efd1e55468 100644 --- a/src/main/ipc-handlers/terminal-handlers.ts +++ b/src/main/ipc-handlers/terminal-handlers.ts @@ -12,6 +12,7 @@ import { keepOpenProjectsOnAccount, projectAccount } from '../project-account'; import { readSettingsFileAsync } from '../settings-utils'; import { appLog } from '../app-logger'; import { createProfileDirectory } from '../claude-profile/profile-utils'; +import { deleteClaudeCodeAccountFiles } from '../claude-profile/account-deletion'; import { isValidConfigDir } from '../utils/config-path-validator'; import { getToolInfoAsync } from '../cli-tool-manager'; import { isDefaultClaudeConfigDir } from '../claude-profile/config-dir-paths'; @@ -28,7 +29,7 @@ import { readClipboardFilePaths } from '../terminal/clipboard-files'; export function registerTerminalHandlers( terminalManager: TerminalManager, getMainWindow: () => BrowserWindow | null, - agentManager?: Pick + agentManager?: Pick ): void { // ============================================ @@ -281,8 +282,23 @@ export function registerTerminalHandlers( async (_, profileId: string): Promise => { try { const profileManager = getClaudeProfileManager(); - if (profileManager.getProfile(profileId)?.detected) { - return { success: false, error: "This account comes from Claude Code's configuration and can't be removed" }; + // An account from Claude Code's configuration: signed out and its configuration removed + // (account-deletion.ts), then dropped from the accounts and from projects that chose it + const profile = profileManager.getProfile(profileId); + if (profile?.detected) { + const blocker = profileManager.detectedAccountDeletionBlocker(profileId); + if (blocker) return { success: false, error: blocker }; + if (agentManager?.getRunningTasksByProfile().byProfile[profileId]?.length) { + return { success: false, error: "Tasks are running on this account; it can't be deleted until they stop" }; + } + await deleteClaudeCodeAccountFiles(profile); + profileManager.removeDetectedAccount(profileId); + for (const project of projectStore.getProjects()) { + if (project.settings?.claudeProfileId === profileId) { + projectStore.updateProjectSettings(project.id, { claudeProfileId: undefined }); + } + } + return { success: true }; } const success = profileManager.deleteProfile(profileId); if (!success) { diff --git a/src/renderer/components/settings/ClaudeAccountsSection.tsx b/src/renderer/components/settings/ClaudeAccountsSection.tsx index 77ad95bf33..64deed8de2 100644 --- a/src/renderer/components/settings/ClaudeAccountsSection.tsx +++ b/src/renderer/components/settings/ClaudeAccountsSection.tsx @@ -1,8 +1,9 @@ /** * Claude accounts (Accounts page): the Claude Code setups found in its own configuration (see * claude-code-detection). Each project window has its own account in use (saved for its project); - * with automatic switching on, tasks move to the next account when it hits a limit. Each row shows the account's email and usage (or its - * provider); its menu switches to it, signs it in again and shows its details. Adding an account + * while an API profile is in use, that profile is the one in use and no account is marked. Each row + * shows the account's email and usage (or its provider); its menu switches to it (leaving an API + * profile in use), signs it in again and shows its details (where it can be removed). Adding an account * (or signing one in again) runs Claude Code's own sign-in (`claude auth login`) in the user's * terminal; the accounts are then detected again until the sign-in shows up. */ @@ -16,6 +17,7 @@ import { SettingsRow } from './SettingsRow'; import { DetectedAccountDialog } from './DetectedAccountDialog'; import { useClaudeAccounts } from './hooks/useClaudeAccounts'; import { switchClaudeAccount, useWindowClaudeAccountId } from '../../hooks/useWindowClaudeAccount'; +import { useSettingsStore } from '../../stores/settings-store'; import type { ClaudeProfile } from '../../../shared/types'; /** How often (and how long) the accounts are detected again while a sign-in runs in a terminal */ @@ -24,9 +26,12 @@ const LOGIN_WATCH_MAX_TRIES = 200; export function ClaudeAccountsSection() { const { t } = useTranslation('settings'); - const { profiles: allProfiles, usage, reload } = useClaudeAccounts(); + const { profiles: allProfiles, activeProfileId, usage, reload } = useClaudeAccounts(); // The account this window's project runs on const accountId = useWindowClaudeAccountId(); + // An API profile in use takes over from the Claude accounts: it alone is marked in use + const apiProfileInUse = useSettingsStore((state) => state.activeProfileId); + const setActiveApiProfile = useSettingsStore((state) => state.setActiveProfile); // Only Claude Code's own setups are accounts const profiles = allProfiles.filter((profile) => profile.detected); @@ -45,10 +50,13 @@ export function ClaudeAccountsSection() { setRowError(null); try { // Saved for this window's project; other windows keep their own account - const result = await switchClaudeAccount(profile.id); + const result = profile.id === accountId ? { success: true } as const : await switchClaudeAccount(profile.id); if (!result.success) { const title = t('claudeAccounts.toast.switchFailed'); setRowError({ id: profile.id, message: result.error ? `${title}: ${result.error}` : title }); + } else if (apiProfileInUse && !(await setActiveApiProfile(null))) { + // Back from the API profile to Claude accounts + setRowError({ id: profile.id, message: t('claudeAccounts.toast.switchFailed') }); } await reload(); } finally { @@ -106,6 +114,15 @@ export function ClaudeAccountsSection() { }; }, [login, reload, t]); + // Why an account can't be deleted: the account in use (this window's or the app's), the only + // one, or one set up from outside its config dir (it would be listed again) + const deleteBlockedReason = (profile: ClaudeProfile): string | undefined => { + if (profile.id === accountId || profile.id === activeProfileId) return t('claudeAccounts.dialog.deleteInUse'); + if (profiles.length <= 1) return t('claudeAccounts.dialog.deleteOnly'); + if (profile.detected?.isDefaultDir && profile.detected.definedOutside) return t('claudeAccounts.dialog.deleteOutside'); + return undefined; + }; + const describe = (profile: ClaudeProfile): string => { // A setup on a cloud provider, an API key or a gateway: what it reaches Claude through const detected = profile.detected; @@ -139,7 +156,7 @@ export function ClaudeAccountsSection() { return ( <> {profiles.map((profile) => { - const isActive = profile.id === accountId; + const isActive = !apiProfileInUse && profile.id === accountId; const isBusy = busyId === profile.id; return ( {addStatus.message} - ) : profiles.length > 1 ? t('claudeAccounts.addDescriptionMore') : t('claudeAccounts.addDescription') + ) : t('claudeAccounts.addDescription') } > @@ -112,5 +161,42 @@ export function DetectedAccountDialog({ open, profile, onOpenChange, onSaved }: + + {/* Confirm before the account leaves the list */} + { + if (isDeleting) return; + setConfirmDelete(next); + if (!next) setDeleteError(null); + }} + > + + + {t('claudeAccounts.dialog.deleteTitle')} + + {detected.isDefaultDir + ? t('claudeAccounts.dialog.deleteDescriptionDefault', { name: profile.name }) + : t('claudeAccounts.dialog.deleteDescription', { name: profile.name, dir: profile.configDir })} + + {deleteError &&

{deleteError}

} +
+ + {t('claudeAccounts.dialog.cancel')} + { + // Stay open until the delete finishes, so a failure can be shown here + e.preventDefault(); + void handleDelete(); + }} + disabled={isDeleting} + className={buttonVariants({ variant: 'destructive', size: 'sm' })} + > + {isDeleting ? t('claudeAccounts.dialog.deleting') : t('claudeAccounts.dialog.delete')} + + +
+
+ ); } diff --git a/src/renderer/components/settings/__tests__/ClaudeAccountsSection.test.tsx b/src/renderer/components/settings/__tests__/ClaudeAccountsSection.test.tsx index b040b37f4d..de44a93fbb 100644 --- a/src/renderer/components/settings/__tests__/ClaudeAccountsSection.test.tsx +++ b/src/renderer/components/settings/__tests__/ClaudeAccountsSection.test.tsx @@ -7,13 +7,21 @@ */ import { describe, it, expect, vi } from 'vitest'; import '@testing-library/jest-dom/vitest'; -import { render, screen } from '@testing-library/react'; +import { fireEvent, render, screen } from '@testing-library/react'; import type { ClaudeProfile, ProfileUsageSummary } from '../../../../shared/types'; import { ClaudeAccountsSection } from '../ClaudeAccountsSection'; import { useClaudeAccounts } from '../hooks/useClaudeAccounts'; +import { useClaudeProfileStore } from '../../../stores/claude-profile-store'; +import { useSettingsStore } from '../../../stores/settings-store'; vi.mock('../hooks/useClaudeAccounts', () => ({ useClaudeAccounts: vi.fn() })); -vi.mock('../DetectedAccountDialog', () => ({ DetectedAccountDialog: () => null })); +const dialogProps = vi.hoisted(() => ({ current: null as null | { deleteBlockedReason?: string } })); +vi.mock('../DetectedAccountDialog', () => ({ + DetectedAccountDialog: (props: { deleteBlockedReason?: string }) => { + dialogProps.current = props; + return null; + }, +})); vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string, params?: Record) => @@ -80,4 +88,38 @@ describe('ClaudeAccountsSection', () => { // No summary at all: just the email expect(screen.getByText('me@work.example')).toBeInTheDocument(); }); + + it('marks the window\'s account in use while no API profile is in use', () => { + useClaudeProfileStore.setState({ profiles: [profile('personal', 'Personal', 'me@example.com')], activeProfileId: 'personal' }); + useSettingsStore.setState({ activeProfileId: null }); + renderWith([]); + + expect(screen.getAllByText('claudeAccounts.inUse')).toHaveLength(1); + }); + + it('marks no Claude account in use while an API profile is in use', () => { + useClaudeProfileStore.setState({ profiles: [profile('personal', 'Personal', 'me@example.com')], activeProfileId: 'personal' }); + useSettingsStore.setState({ activeProfileId: 'api-profile' }); + renderWith([]); + + expect(screen.queryByText('claudeAccounts.inUse')).not.toBeInTheDocument(); + useSettingsStore.setState({ activeProfileId: null }); + }); + + it('blocks deleting the account in use, not another one', async () => { + useClaudeProfileStore.setState({ profiles: [profile('personal', 'Personal', 'me@example.com')], activeProfileId: 'personal' }); + useSettingsStore.setState({ activeProfileId: null }); + renderWith([]); + + // Details of an account, from its row's menu (rows in order: personal, work, new) + const openDetails = async (row: number) => { + fireEvent.pointerDown(screen.getAllByLabelText('claudeAccounts.menu')[row], { button: 0, ctrlKey: false }); + fireEvent.click(await screen.findByText('claudeAccounts.details')); + }; + + await openDetails(0); + expect(dialogProps.current?.deleteBlockedReason).toBe('claudeAccounts.dialog.deleteInUse'); + await openDetails(1); + expect(dialogProps.current?.deleteBlockedReason).toBeUndefined(); + }); }); diff --git a/src/shared/i18n/locales/en/settings.json b/src/shared/i18n/locales/en/settings.json index 904d24c97f..1cb85b0a5a 100644 --- a/src/shared/i18n/locales/en/settings.json +++ b/src/shared/i18n/locales/en/settings.json @@ -664,14 +664,22 @@ "add": "Add Claude account", "addButton": "Add", "addDescription": "Opens a terminal with claude auth login", - "addDescriptionMore": "Tasks switch to the next account when the one in use hits a limit", "dialog": { "name": "Account name", "save": "Save", - "cancel": "Cancel" + "cancel": "Cancel", + "delete": "Delete", + "deleting": "Deleting...", + "deleteOnly": "The only Claude account can't be deleted", + "deleteInUse": "The account in use can't be deleted", + "deleteOutside": "Set up by environment variables or managed settings; remove them there", + "deleteTitle": "Delete account?", + "deleteDescription": "Are you sure you want to delete \"{{name}}\"? It is signed out and its Claude Code configuration ({{dir}}) is removed. This action cannot be undone.", + "deleteDescriptionDefault": "Are you sure you want to delete \"{{name}}\"? It is signed out and its sign-in settings are removed from Claude Code's configuration. Your other Claude Code settings, skills and history stay. This action cannot be undone." }, "toast": { "renameFailed": "Couldn't rename the account", + "deleteFailed": "Couldn't delete the account", "switchFailed": "Couldn't switch accounts" }, "providers": { diff --git a/src/shared/types/agent.ts b/src/shared/types/agent.ts index a5c020b9fe..fb532cf466 100644 --- a/src/shared/types/agent.ts +++ b/src/shared/types/agent.ts @@ -254,6 +254,11 @@ export interface DetectedClaudeCodeAccount { plan?: string; /** Settings and variables that configure it (effective first) */ values: DetectedClaudeCodeValue[]; + /** + * Its provider is set up from outside the config dir (environment variables or managed + * settings), so cleaning the dir's own files doesn't remove it + */ + definedOutside?: boolean; } /** From 63183fba80364c5bdbda848415f5ba00daba89b0 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sat, 7 Nov 2026 23:26:57 +0400 Subject: [PATCH 04/74] fix(api-profiles): import the API key helper by relative path The main process build doesn't resolve the @shared alias for runtime imports, so `npm run dev` failed to start. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 ++-- package.json | 2 +- src/main/services/profile/profile-service.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index d2e17fc98c..0dfc2c8cc8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.3", + "version": "1.6.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.3", + "version": "1.6.4", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index ad0f135a43..93f5d73398 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.3", + "version": "1.6.4", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/main/services/profile/profile-service.ts b/src/main/services/profile/profile-service.ts index afcb2311fc..228d4f0e69 100644 --- a/src/main/services/profile/profile-service.ts +++ b/src/main/services/profile/profile-service.ts @@ -15,7 +15,7 @@ import Anthropic, { import { loadProfilesFile, generateProfileId, atomicModifyProfiles } from './profile-manager'; import type { APIProfile, TestConnectionResult, ModelInfo, DiscoverModelsResult } from '@shared/types/profile'; -import { apiKeyToSend, isApiKeyOptional } from '@shared/utils/api-profile-key'; +import { apiKeyToSend, isApiKeyOptional } from '../../../shared/utils/api-profile-key'; /** * Input type for creating a profile (without id, createdAt, updatedAt) From 8c16dbba092e7acb76d2d2b757c19fd82a52d233 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sat, 7 Nov 2026 23:26:57 +0400 Subject: [PATCH 05/74] fix(accounts): ignore the OAuth token inherited from a Workbench terminal An app started from an agent window inherited that window's CLAUDE_CODE_OAUTH_TOKEN, which account detection read as a machine-wide setup overriding every sign-in: accounts showed "OAuth token" without usage and lost "Sign in again". Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 ++-- package.json | 2 +- src/main/index.ts | 5 +++++ 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0dfc2c8cc8..95094696be 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.4", + "version": "1.6.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.4", + "version": "1.6.5", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index 93f5d73398..f33b6a472a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.4", + "version": "1.6.5", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/main/index.ts b/src/main/index.ts index 7c231b2f07..91738ebc22 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -30,6 +30,11 @@ for (const envPath of possibleEnvPaths) { } } +// Started from a Workbench terminal (agent window): that window's account token, which it injects +// for its own Claude Code, isn't this app's setup. Left in, account detection read it as an +// environment-wide OAuth token overriding every account's sign-in. +if (process.env.WORKBENCH_TERMINAL_ID) delete process.env.CLAUDE_CODE_OAUTH_TOKEN; + import { app, BrowserWindow, ipcMain, shell, nativeImage, session, screen, Menu, MenuItem, type Rectangle } from 'electron'; import { join } from 'path'; import { writeFileSync, rmSync, cpSync } from 'fs'; From 75895f960602e3ad46e7307ec03130c322ffad1f Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sat, 7 Nov 2026 23:26:57 +0400 Subject: [PATCH 06/74] fix(accounts): delete accounts from their row, on hover Claude accounts get a trash button before their menu, shown on hover like API profiles' buttons, instead of a Delete button in the Details dialog. The account or API profile in use shows no delete button instead of a disabled one. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- package-lock.json | 4 +- package.json | 2 +- .../settings/ClaudeAccountsSection.tsx | 110 ++++++++++++++++-- .../settings/DetectedAccountDialog.tsx | 94 +-------------- .../components/settings/ProfileList.test.tsx | 11 ++ .../components/settings/ProfileList.tsx | 30 +++-- .../__tests__/ClaudeAccountsSection.test.tsx | 24 ++-- src/shared/i18n/locales/en/settings.json | 5 +- 9 files changed, 139 insertions(+), 143 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fa51c0cecc..e1b1d724cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -540,7 +540,7 @@ relays their events), `agent-state.ts` (the profile and session of each running refresh), `usage-monitor.ts` (usage and rate limits). On every start, `claude-code-detection.ts` finds Claude Code's own setups (`~/.claude`, `CLAUDE_CONFIG_DIR`, `~/.claude-*`: subscription sign-in, cloud provider, API key or gateway, from managed settings, the dir's `settings.json` and the environment) and -lists them as accounts (`ClaudeProfile.detected`): usable and renamable. Deleting one (its Details dialog; never the account in use, the only one, or one with running +lists them as accounts (`ClaudeProfile.detected`): usable and renamable. Deleting one (the trash button in its row, shown for accounts not in use; never one with running tasks) signs it out with `claude auth logout` and removes its config dir, or for the default `~/.claude` only the settings that set up how it reaches Claude (`claude-profile/account-deletion.ts`); projects that chose it lose the reference. Claude Code's default `~/.claude` diff --git a/package-lock.json b/package-lock.json index 95094696be..60be294fa8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.5", + "version": "1.6.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.5", + "version": "1.6.6", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index f33b6a472a..c40117690a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.5", + "version": "1.6.6", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/renderer/components/settings/ClaudeAccountsSection.tsx b/src/renderer/components/settings/ClaudeAccountsSection.tsx index 64deed8de2..740fc0159b 100644 --- a/src/renderer/components/settings/ClaudeAccountsSection.tsx +++ b/src/renderer/components/settings/ClaudeAccountsSection.tsx @@ -3,14 +3,24 @@ * claude-code-detection). Each project window has its own account in use (saved for its project); * while an API profile is in use, that profile is the one in use and no account is marked. Each row * shows the account's email and usage (or its provider); its menu switches to it (leaving an API - * profile in use), signs it in again and shows its details (where it can be removed). Adding an account + * profile in use), signs it in again and shows its details; accounts not in use can be deleted from their row. Adding an account * (or signing one in again) runs Claude Code's own sign-in (`claude auth login`) in the user's * terminal; the accounts are then detected again until the sign-in shows up. */ import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Check, Info, MoreHorizontal, Plus, RefreshCw } from 'lucide-react'; -import { Button } from '../ui/button'; +import { Check, Info, MoreHorizontal, Plus, RefreshCw, Trash2 } from 'lucide-react'; +import { Button, buttonVariants } from '../ui/button'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle +} from '../ui/alert-dialog'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../ui/dropdown-menu'; import { cn } from '../../lib/utils'; import { SettingsRow } from './SettingsRow'; @@ -44,6 +54,29 @@ export function ClaudeAccountsSection() { const [busyId, setBusyId] = useState(null); // The last failed action on an account, shown in its row instead of the description const [rowError, setRowError] = useState<{ id: string; message: string } | null>(null); + // The account whose deletion waits for confirmation + const [deleteTarget, setDeleteTarget] = useState(null); + const [isDeleting, setIsDeleting] = useState(false); + const [deleteError, setDeleteError] = useState(null); + + const handleDelete = async () => { + if (!deleteTarget) return; + setIsDeleting(true); + setDeleteError(null); + try { + const result = await window.electronAPI.deleteClaudeProfile(deleteTarget.id); + if (!result.success) { + setDeleteError(result.error || t('claudeAccounts.toast.deleteFailed')); + return; + } + setDeleteTarget(null); + await reload(); + } catch { + setDeleteError(t('claudeAccounts.toast.deleteFailed')); + } finally { + setIsDeleting(false); + } + }; const handleUse = async (profile: ClaudeProfile) => { setBusyId(profile.id); @@ -114,14 +147,13 @@ export function ClaudeAccountsSection() { }; }, [login, reload, t]); - // Why an account can't be deleted: the account in use (this window's or the app's), the only - // one, or one set up from outside its config dir (it would be listed again) - const deleteBlockedReason = (profile: ClaudeProfile): string | undefined => { - if (profile.id === accountId || profile.id === activeProfileId) return t('claudeAccounts.dialog.deleteInUse'); - if (profiles.length <= 1) return t('claudeAccounts.dialog.deleteOnly'); - if (profile.detected?.isDefaultDir && profile.detected.definedOutside) return t('claudeAccounts.dialog.deleteOutside'); - return undefined; - }; + // Only accounts that can be deleted show the delete button (on hover, like API profiles): not the + // account in use (this window's or the app's), nor one set up from outside its config dir, which + // would be listed again + const canDelete = (profile: ClaudeProfile) => + profile.id !== accountId + && profile.id !== activeProfileId + && !(profile.detected?.isDefaultDir && profile.detected.definedOutside); const describe = (profile: ClaudeProfile): string => { // A setup on a cloud provider, an API key or a gateway: what it reaches Claude through @@ -161,6 +193,7 @@ export function ClaudeAccountsSection() { return ( {profile.name} @@ -175,6 +208,24 @@ export function ClaudeAccountsSection() { ) } > + {canDelete(profile) && ( +
+ +
+ )} @@ -161,42 +112,5 @@ export function DetectedAccountDialog({ open, profile, onOpenChange, onSaved, de - - {/* Confirm before the account leaves the list */} - { - if (isDeleting) return; - setConfirmDelete(next); - if (!next) setDeleteError(null); - }} - > - - - {t('claudeAccounts.dialog.deleteTitle')} - - {detected.isDefaultDir - ? t('claudeAccounts.dialog.deleteDescriptionDefault', { name: profile.name }) - : t('claudeAccounts.dialog.deleteDescription', { name: profile.name, dir: profile.configDir })} - - {deleteError &&

{deleteError}

} -
- - {t('claudeAccounts.dialog.cancel')} - { - // Stay open until the delete finishes, so a failure can be shown here - e.preventDefault(); - void handleDelete(); - }} - disabled={isDeleting} - className={buttonVariants({ variant: 'destructive', size: 'sm' })} - > - {isDeleting ? t('claudeAccounts.dialog.deleting') : t('claudeAccounts.dialog.delete')} - - -
-
- ); } diff --git a/src/renderer/components/settings/ProfileList.test.tsx b/src/renderer/components/settings/ProfileList.test.tsx index 78d9def073..d9320348ef 100644 --- a/src/renderer/components/settings/ProfileList.test.tsx +++ b/src/renderer/components/settings/ProfileList.test.tsx @@ -243,6 +243,17 @@ describe('ProfileList - Delete Confirmation Dialog', () => { expect(mockStore.deleteProfile).not.toHaveBeenCalled(); }); + it('shows no delete button for the profile in use', () => { + vi.mocked(useSettingsStore).mockReturnValue( + createSettingsStoreMock({ activeProfileId: 'profile-2' }) + ); + + renderWithWrapper(); + + expect(screen.queryByTestId('profile-delete-button-profile-2')).not.toBeInTheDocument(); + expect(screen.getByTestId('profile-delete-button-profile-1')).toBeInTheDocument(); + }); + // Test 6: Delete confirmation dialog has delete action button it('should show delete action button in confirmation dialog', () => { vi.mocked(useSettingsStore).mockReturnValue( diff --git a/src/renderer/components/settings/ProfileList.tsx b/src/renderer/components/settings/ProfileList.tsx index 73a9ed78c1..06a5a850ce 100644 --- a/src/renderer/components/settings/ProfileList.tsx +++ b/src/renderer/components/settings/ProfileList.tsx @@ -139,22 +139,20 @@ export function ProfileList({ onProfileSaved }: ProfileListProps) { > - + {/* The profile in use can't be deleted: no button, like Claude accounts */} + {!isActive && ( + + )}
{isActive ? ( + + {t(agentMode ? 'insights.agentMode.on' : 'insights.agentMode.off')} + + ); const kanbanButton = ( @@ -608,7 +634,7 @@ export function Insights({ projectId }: InsightsProps) { {isEmpty ? ( /* Toolbar (new chat): attach on the left; the model and send on the right */
-
{attachButton}{mcpButton}{githubButton}{gitlabButton}{kanbanButton}
+
{attachButton}{mcpButton}{githubButton}{gitlabButton}{clawdButton}{kanbanButton}
{modelSelector} {/* Send button only appears once there is something to send; it turns into stop while Claude works */} @@ -846,7 +872,7 @@ export function Insights({ projectId }: InsightsProps) { {composer} {/* Under the field: attach, disclaimer, model */}
-
{attachButton}{mcpButton}{githubButton}{gitlabButton}{kanbanButton}
+
{attachButton}{mcpButton}{githubButton}{gitlabButton}{clawdButton}{kanbanButton}
{t('insights.disclaimer')}
{modelSelector}
@@ -1122,6 +1148,37 @@ const mcpToolIcon = (toolName: string): React.ElementType | null => { return BUILTIN_CONNECTOR_META.find(({ id }) => id === server.toLowerCase())?.icon ?? McpIcon; }; +/** Tools a read-only turn has too (without the Clawd button) */ +const READ_ONLY_TOOLS = new Set(['Read', 'Glob', 'Grep', 'WebFetch', 'WebSearch', 'ListAgents', 'SendMessage', 'CodebaseGraph']); + +/** + * The MCP servers Workbench gives the chat itself: its task tools, the built-in connectors and the + * custom ones (named as buildMcpConfig names them). Any other server is the user's own, which only + * a Clawd turn loads + */ +const useWorkbenchMcpServers = (): Set => { + const customServers = useSettingsStore((state) => state.settings.mcpConnectors?.customServers); + return useMemo(() => new Set([ + 'workbench', + ...BUILTIN_CONNECTOR_META.map(({ id }) => id), + ...(customServers ?? []).map((server) => (server.name || server.id).replace(/[^A-Za-z0-9_-]/g, '_')), + ]), [customServers]); +}; + +/** + * Whether only a turn with the Clawd button could make this call: changing files (other than the + * project memory), shell commands besides the gh, glab and graphify ones, the user's own MCP + * servers and every tool a read-only turn doesn't have (subagents, skills, ...) + */ +const isClawdTool = (toolName: string, input: string | undefined, workbenchServers: Set): boolean => { + const server = /^mcp__(.+?)__/.exec(toolName)?.[1]; + if (server) return !workbenchServers.has(server) && !workbenchServers.has(server.toLowerCase()); + if (READ_ONLY_TOOLS.has(toolName) || cliCall(toolName, input)) return false; + // Saving a project memory (self-improve) is allowed read-only + if ((toolName === 'Write' || toolName === 'Edit') && input?.replace(/\\/g, '/').includes('.workbench/compeng/')) return false; + return true; +}; + const getToolIcon = (toolName: string) => { if (taskToolName(toolName)) return KanbanIcon; const mcpIcon = mcpToolIcon(toolName); @@ -1294,6 +1351,7 @@ function RegenerateMessageButton({ onClick }: { onClick: () => void }) { function ToolUsageHistory({ tools, actions, trailing }: ToolUsageHistoryProps) { const { t } = useTranslation('common'); const [expanded, setExpanded] = useState(false); + const workbenchServers = useWorkbenchMcpServers(); if (tools.length === 0) return null; @@ -1317,8 +1375,9 @@ function ToolUsageHistory({ tools, actions, trailing }: ToolUsageHistoryProps) {
{tools.map((tool, index) => { // gh, glab and graphify calls show as GitHub, GitLab and Graphify, like the task tools show as Kanban steps + // Calls only the Clawd button allows show Clawd const cli = cliCall(tool.name, tool.input); - const Icon = cli?.icon ?? getToolIcon(tool.name); + const Icon = isClawdTool(tool.name, tool.input, workbenchServers) ? ClawdIcon : cli?.icon ?? getToolIcon(tool.name); const taskTool = taskToolName(tool.name); const label = cli?.label ?? (taskTool ? t(`insights.taskTools.${taskTool}`, { defaultValue: taskTool }) : tool.name); @@ -1353,6 +1412,7 @@ interface ToolIndicatorProps { function ToolIndicator({ name, input }: ToolIndicatorProps) { const { t } = useTranslation('common'); + const workbenchServers = useWorkbenchMcpServers(); // Get friendly name and icon for each tool const getToolInfo = (toolName: string) => { @@ -1377,7 +1437,9 @@ function ToolIndicator({ name, input }: ToolIndicatorProps) { } }; - const { icon: Icon, label } = cliCall(name, input) ?? getToolInfo(name); + const info = cliCall(name, input) ?? getToolInfo(name); + // Calls only the Clawd button allows show Clawd + const { icon: Icon, label } = isClawdTool(name, input, workbenchServers) ? { ...info, icon: ClawdIcon } : info; return ( diff --git a/src/renderer/components/icons/app-icons.tsx b/src/renderer/components/icons/app-icons.tsx index 691f671468..c42e441cda 100644 --- a/src/renderer/components/icons/app-icons.tsx +++ b/src/renderer/components/icons/app-icons.tsx @@ -111,6 +111,20 @@ export function KanbanIcon(props: IconProps) { ); } +/** + * Clawd, the crab from Claude Code's welcome screen, drawn from its block glyphs (` ▐▛███▜▌`, + * `▝▜█████▛▘`, ` ▘▘ ▝▝`): each quadrant one unit wide and two tall, on a 16-unit grid, so at + * 16px every edge falls on a whole pixel (smaller sizes soften its one-unit legs and eyes). Eyes + * are left open; filled with `currentColor` + */ +export function ClawdIcon({ strokeWidth: _strokeWidth, ...props }: IconProps) { + return ( + + ); +} + /** Open folder — the active project / Projects page */ export function ProjectIcon(props: IconProps) { // The artwork only spans ~812 of the 1024 units; zoom the view onto it so it reads the same diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index cdd69bdf16..2eb210a334 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -234,6 +234,11 @@ }, "githubTools": "GitHub", "gitlabTools": "GitLab", + "agentMode": { + "label": "Claude Code", + "off": "Let Claude work like an agent window: change files, run commands and use slash commands and skills", + "on": "Claude works like an agent window: it can change files, run commands and use slash commands and skills" + }, "cliNotFound": "{{name}} CLI not detected", "kanbanTools": { "label": "Kanban", diff --git a/src/shared/types/insights.ts b/src/shared/types/insights.ts index a5992bcc9d..61bcea58d9 100644 --- a/src/shared/types/insights.ts +++ b/src/shared/types/insights.ts @@ -25,6 +25,12 @@ export interface InsightsModelConfig { githubTools?: boolean; /** The GitLab button: Claude can use the GitLab CLI (glab) in this conversation */ gitlabTools?: boolean; + /** + * The Clawd button: the conversation's turns get what an agent window has (every tool, changing + * the project's files, the user's own MCP servers, slash commands and skills). Turning it off + * keeps the same Claude Code session; later turns are read-only again + */ + agentMode?: boolean; /** * The browser the chat's Playwright opens (picked in the browser drawer; null: Playwright's own * Chromium); unset = the one in Settings > Connectors From d8610e0a8ccc4261ba697f26cb7c74f2e98f1e01 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sun, 8 Nov 2026 00:17:23 +0400 Subject: [PATCH 10/74] feat(chat): open a chat's Claude Code session in an agent window A Clawd button under the browser button resumes the chat's session in a new agent window of the project (`claude --resume` on the account it ran on), like a task's "Open agent". Shown once the chat has a session; disabled while it replies or when the project has no room for another window. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 +- package.json | 2 +- src/renderer/components/Insights.tsx | 7 +- .../components/InsightsAgentWindowButton.tsx | 69 +++++++++++++++++++ src/renderer/components/Terminal.tsx | 3 + src/renderer/stores/terminal-store.ts | 21 ++++++ src/shared/i18n/locales/en/common.json | 5 ++ 7 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 src/renderer/components/InsightsAgentWindowButton.tsx diff --git a/package-lock.json b/package-lock.json index de2f2fd738..5f83fe698e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.9", + "version": "1.6.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.9", + "version": "1.6.10", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index 64605be8e2..c01c7bcc77 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.9", + "version": "1.6.10", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/renderer/components/Insights.tsx b/src/renderer/components/Insights.tsx index 2183f4e105..f930eba2fc 100644 --- a/src/renderer/components/Insights.tsx +++ b/src/renderer/components/Insights.tsx @@ -64,6 +64,7 @@ import { import { IS_DEV_BUILD, TITLE_BAR_STRIP_HEIGHT } from '../lib/title-bar'; import { InsightsModelSelector } from './InsightsModelSelector'; import { InsightsMcpMenu } from './InsightsMcpMenu'; +import { InsightsAgentWindowButton } from './InsightsAgentWindowButton'; import { useSettingsStore } from '../stores/settings-store'; import { getDefaultMcpConnectorIds } from '../../shared/utils/mcp-connectors'; import { AttachmentPreviewDialog } from './AttachmentPreviewDialog'; @@ -777,7 +778,11 @@ export function Insights({ projectId }: InsightsProps) { {t('insights.newChat')}
- + {/* The browser drawer's button, and under it the chat's session in an agent window */} +
+ + +
{isEmpty ? ( diff --git a/src/renderer/components/InsightsAgentWindowButton.tsx b/src/renderer/components/InsightsAgentWindowButton.tsx new file mode 100644 index 0000000000..bf2a6dc0c3 --- /dev/null +++ b/src/renderer/components/InsightsAgentWindowButton.tsx @@ -0,0 +1,69 @@ +/** + * The Claude page's "Open in agent window" button (top bar, under the browser button): opens the + * chat's Claude Code session in a new agent window of the project (`claude --resume`, on the + * account it ran on), like a task's "Open agent" button. Hidden until the chat has a session; + * disabled while the chat replies (its turn is writing the session) or when the project has no + * room for another window. + */ +import { useTranslation } from 'react-i18next'; +import { Button } from './ui/button'; +import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'; +import { ClawdIcon } from './icons/app-icons'; +import { useProjectStore } from '../stores/project-store'; +import { useTerminalStore } from '../stores/terminal-store'; +import type { InsightsSession } from '../../shared/types'; + +interface InsightsAgentWindowButtonProps { + projectId: string; + session: InsightsSession | null; + /** The chat is replying */ + replying: boolean; +} + +export function InsightsAgentWindowButton({ projectId, session, replying }: InsightsAgentWindowButtonProps) { + const { t } = useTranslation('common'); + const projectPath = useProjectStore((state) => state.projects.find((project) => project.id === projectId)?.path); + const canAddWindow = useTerminalStore((state) => (projectPath ? state.canAddTerminal(projectPath) : false)); + + // The session the chat's latest reply ended in (edits and regenerations fork into a new one) + const ref = [...(session?.messages ?? [])].reverse().find((message) => message.claudeRef)?.claudeRef; + if (!session || !ref || !projectPath) return null; + + const reason = replying + ? t('insights.agentWindow.replying') + : !canAddWindow + ? t('insights.agentWindow.noRoom') + : null; + const label = t('insights.agentWindow.open'); + + const handleOpen = () => { + if (reason) return; + useTerminalStore.getState().openProjectSession({ + projectPath, + title: session.title || label, + sessionId: ref.sessionId, + profileId: ref.profileId, + }); + }; + + return ( + + + {/* The wrapper keeps the tooltip on a disabled button */} + + + + + {reason ?? label} + + ); +} diff --git a/src/renderer/components/Terminal.tsx b/src/renderer/components/Terminal.tsx index 0a52750e00..6932081460 100644 --- a/src/renderer/components/Terminal.tsx +++ b/src/renderer/components/Terminal.tsx @@ -347,6 +347,9 @@ export const Terminal = forwardRef(function Termi console.error('Failed to sync worktree config after PTY creation:', error); } pendingWorktreeConfigRef.current = null; + } else if (created?.pendingTaskSession && created.title) { + // A session of the project's own folder (a Claude chat's): titled after it + window.electronAPI.setTerminalTitle(id, created.title); } // "New agent" terminals (and agents moved to another worktree) start Claude Code as soon as // the shell is ready; the store holds the current cwd (the worktree path after a switch). diff --git a/src/renderer/stores/terminal-store.ts b/src/renderer/stores/terminal-store.ts index 68b9c7e13a..e6d668b6f1 100644 --- a/src/renderer/stores/terminal-store.ts +++ b/src/renderer/stores/terminal-store.ts @@ -286,6 +286,13 @@ interface TerminalState { * show the Agents page. Returns null when the project has no room for another window. */ openTaskSession: (request: TaskSessionRequest) => Terminal | null; + /** + * Open a Claude Code session that ran in the project's own folder (a Claude chat's) in a new + * agent window: it resumes the session on the account it ran on and is titled `title`. Also + * asks the app to show the Agents page. Returns null when the project has no room for another + * window. + */ + openProjectSession: (request: { projectPath: string; title: string; sessionId: string; profileId?: string }) => Terminal | null; // Selectors getTerminal: (id: string) => Terminal | undefined; @@ -725,6 +732,20 @@ export const useTerminalStore = create((set, get) => ({ return terminal ? get().getTerminal(terminal.id) ?? null : null; }, + openProjectSession: (request) => { + const terminal = get().addTerminal(request.projectPath, request.projectPath, { launchCLI: true }); + if (terminal) { + get().updateTerminal(terminal.id, { + title: request.title, + pendingTaskSession: { sessionId: request.sessionId, profileId: request.profileId } + }); + } + set((state) => ({ + agentsViewRequest: { projectPath: request.projectPath, seq: (state.agentsViewRequest?.seq ?? 0) + 1 } + })); + return terminal ? get().getTerminal(terminal.id) ?? null : null; + }, + getTerminal: (id: string) => { return get().terminals.find((t) => t.id === id); }, diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index 2eb210a334..7e31e37ac7 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -239,6 +239,11 @@ "off": "Let Claude work like an agent window: change files, run commands and use slash commands and skills", "on": "Claude works like an agent window: it can change files, run commands and use slash commands and skills" }, + "agentWindow": { + "open": "Open agent", + "replying": "Wait for the reply to finish", + "noRoom": "This project has no room for another agent window" + }, "cliNotFound": "{{name}} CLI not detected", "kanbanTools": { "label": "Kanban", From b0b42808e3c5f02f1f044ea751f923aabaa49f10 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sun, 8 Nov 2026 00:17:40 +0400 Subject: [PATCH 11/74] feat(chat): slash commands and skills menu in the composer With the Clawd button on, a `/` at the start of the input or of a word opens a menu of Claude Code's slash commands and skills in the project, filtered as the user types (arrows, Enter or Tab to pick, Escape to close). They are asked once per project with the control protocol's initialize request, which needs no model call. Also documents the Clawd button in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 7 + package-lock.json | 4 +- package.json | 2 +- .../insights/__tests__/chat-commands.test.ts | 43 +++++ src/main/insights/chat-commands.ts | 98 ++++++++++++ src/main/ipc-handlers/insights-handlers.ts | 18 +++ src/preload/api/modules/insights-api.ts | 5 + src/renderer/components/Insights.tsx | 35 +++- src/renderer/components/InsightsSlashMenu.tsx | 72 +++++++++ .../__tests__/insights-slash-commands.test.ts | 38 +++++ .../components/insights-slash-commands.ts | 151 ++++++++++++++++++ src/renderer/lib/mocks/insights-mock.ts | 1 + src/shared/constants/ipc.ts | 1 + src/shared/i18n/locales/en/common.json | 5 + src/shared/types/insights.ts | 7 + src/shared/types/ipc.ts | 5 +- 16 files changed, 487 insertions(+), 5 deletions(-) create mode 100644 src/main/insights/__tests__/chat-commands.test.ts create mode 100644 src/main/insights/chat-commands.ts create mode 100644 src/renderer/components/InsightsSlashMenu.tsx create mode 100644 src/renderer/components/__tests__/insights-slash-commands.test.ts create mode 100644 src/renderer/components/insights-slash-commands.ts diff --git a/CLAUDE.md b/CLAUDE.md index e1b1d724cf..f225585697 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -435,6 +435,13 @@ headless stream-json run built in `insights/claude-code-runner.ts`, on the proje its workspace root (where files a tool call names are written) is that folder, not the project; the guard also leaves out `browser_run_code_unsafe`. The chat may read that folder (`--add-dir`), where snapshots are linked. It attaches to the chat's own browser (see Chat browsers above); in WSL with interop off each turn launches its own. +- **Clawd button** (`InsightsModelConfig.agentMode`) — the chat's turns get what an agent window has instead: no + `--tools` or `--strict-mcp-config` (every tool, the user's own MCP servers too) and the agent windows' permissions + (`--dangerously-skip-permissions` when Settings skips them, else `--permission-mode auto`, since a headless turn can't + ask). Off again, the same session continues read-only. With it on, the composer's `/` menu lists Claude Code's slash + commands and skills (`insights-slash-commands.ts`; asked once per project with the control protocol's `initialize` + request, `insights/chat-commands.ts`, no model call). A chat with a session also shows a Clawd button under the browser + button that opens its session in an agent window (`claude --resume` on its account, `openProjectSession`). - **MCP per chat** — `--strict-mcp-config` loads only the servers chosen in the chat's MCP menu (`InsightsMcpMenu.tsx`, the Connectors defaults until changed) and, with the Kanban button on, Workbench's task tools (`insights/task-tools.ts`, served over local MCP HTTP by `task-tools-server.ts` with a token per turn): they create, diff --git a/package-lock.json b/package-lock.json index 5f83fe698e..4898c89399 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.10", + "version": "1.6.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.10", + "version": "1.6.11", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index c01c7bcc77..ff02e87980 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.10", + "version": "1.6.11", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/main/insights/__tests__/chat-commands.test.ts b/src/main/insights/__tests__/chat-commands.test.ts new file mode 100644 index 0000000000..2cfd89550d --- /dev/null +++ b/src/main/insights/__tests__/chat-commands.test.ts @@ -0,0 +1,43 @@ +/** + * The chat's `/` menu asks Claude Code for its commands with the control protocol's initialize + * request: only the answer to that request counts, and each command keeps its name, description + * and argument hint. + */ +import { describe, it, expect, vi } from 'vitest'; + +vi.mock('../../claude-code/env', () => ({ resolveClaudeEnv: vi.fn() })); +vi.mock('../../platform/runtime-exec', () => ({ spawnTool: vi.fn(), killRuntimeProcess: vi.fn() })); +vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn() } })); + +import { parseCommandsResponse } from '../chat-commands'; + +const response = (body: Record) => JSON.stringify({ type: 'control_response', response: { request_id: 'workbench-commands', ...body } }); + +describe('parseCommandsResponse', () => { + it('reads the commands of the initialize answer', () => { + const line = response({ + subtype: 'success', + response: { + commands: [ + { name: 'graphify', description: 'Query the graph (user)', argumentHint: '' }, + { name: 'design', description: 'Grant access', argumentHint: 'consent | revoke', builtin: true }, + { description: 'nameless' }, + ], + }, + }); + expect(parseCommandsResponse(line)).toEqual([ + { name: 'graphify', description: 'Query the graph (user)' }, + { name: 'design', description: 'Grant access', argumentHint: 'consent | revoke' }, + ]); + }); + + it('ignores other lines and other requests\' answers', () => { + expect(parseCommandsResponse('{"type":"system","subtype":"init"}')).toBeNull(); + expect(parseCommandsResponse('not json')).toBeNull(); + expect(parseCommandsResponse(JSON.stringify({ type: 'control_response', response: { request_id: 'other', subtype: 'success' } }))).toBeNull(); + }); + + it('fails with Claude Code\'s error', () => { + expect(() => parseCommandsResponse(response({ subtype: 'error', error: 'not signed in' }))).toThrow('not signed in'); + }); +}); diff --git a/src/main/insights/chat-commands.ts b/src/main/insights/chat-commands.ts new file mode 100644 index 0000000000..73e4a670c6 --- /dev/null +++ b/src/main/insights/chat-commands.ts @@ -0,0 +1,98 @@ +/** + * The slash commands and skills Claude Code offers in a project, for the chat's `/` menu (with + * the Clawd button on, a chat message may start with one). + * + * Asked the way the Agent SDK asks: a headless Claude Code with stream-json input gets the + * control protocol's `initialize` request and answers with its commands (built-in ones that work + * headless, the user's and the project's commands, skills and plugins'), each with a description + * and argument hint. No message is sent, so the model isn't called; the process is stopped once + * it answered. + */ +import type { ChatSlashCommand } from '../../shared/types'; +import { resolveClaudeEnv } from '../claude-code/env'; +import { killRuntimeProcess, spawnTool } from '../platform/runtime-exec'; +import { appLog } from '../app-logger'; + +/** How long Claude Code may take to start and answer */ +const PROBE_TIMEOUT_MS = 30_000; + +const REQUEST_ID = 'workbench-commands'; + +/** The commands from a control response line, or null when the line is something else */ +export function parseCommandsResponse(line: string): ChatSlashCommand[] | null { + let message: { type?: unknown; response?: { request_id?: unknown; subtype?: unknown; error?: unknown; response?: { commands?: unknown } } }; + try { + message = JSON.parse(line) as typeof message; + } catch { + return null; + } + if (message.type !== 'control_response' || message.response?.request_id !== REQUEST_ID) return null; + if (message.response.subtype !== 'success') { + throw new Error(typeof message.response.error === 'string' ? message.response.error : 'Claude Code did not list its commands'); + } + const commands = Array.isArray(message.response.response?.commands) ? message.response.response.commands : []; + return (commands as Array<{ name?: unknown; description?: unknown; argumentHint?: unknown }>) + .filter((command) => typeof command.name === 'string' && command.name) + .map((command) => ({ + name: command.name as string, + description: typeof command.description === 'string' ? command.description : '', + ...(typeof command.argumentHint === 'string' && command.argumentHint ? { argumentHint: command.argumentHint } : {}), + })); +} + +/** Claude Code's slash commands and skills in `projectDir`, on the project's account */ +export async function listChatCommands(projectDir: string, profileId?: string): Promise { + const { command, env } = await resolveClaudeEnv({ profileId }); + const child = spawnTool('claude', [ + '-p', + '--input-format', 'stream-json', + '--output-format', 'stream-json', + '--verbose', + '--no-session-persistence', + ], { command, cwd: projectDir, env, windowsHide: true, stdio: 'pipe' }); + + return new Promise((resolve, reject) => { + let buffer = ''; + let stderr = ''; + let settled = false; + const finish = (error: Error | null, commands?: ChatSlashCommand[]) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (child.exitCode === null && !child.killed) killRuntimeProcess(child); + if (error) reject(error); + else resolve(commands ?? []); + }; + const timer = setTimeout(() => finish(new Error('Claude Code did not list its commands in time')), PROBE_TIMEOUT_MS); + + child.stdout?.setEncoding('utf8'); + child.stdout?.on('data', (chunk: string) => { + buffer += chunk; + let newline: number; + while ((newline = buffer.indexOf('\n')) >= 0) { + const line = buffer.slice(0, newline).trim(); + buffer = buffer.slice(newline + 1); + if (!line.startsWith('{')) continue; + try { + const commands = parseCommandsResponse(line); + if (commands) finish(null, commands); + } catch (error) { + finish(error instanceof Error ? error : new Error(String(error))); + } + } + }); + child.stderr?.setEncoding('utf8'); + child.stderr?.on('data', (chunk: string) => { + stderr = (stderr + chunk).slice(-2000); + }); + child.on('error', (error) => finish(error)); + child.on('exit', (code) => { + if (!settled) { + appLog.warn(`[Insights] Claude Code exited (${code}) before listing its commands: ${stderr.trim()}`); + finish(new Error(stderr.trim() || `Claude Code exited with code ${code}`)); + } + }); + + child.stdin?.write(`${JSON.stringify({ type: 'control_request', request_id: REQUEST_ID, request: { subtype: 'initialize' } })}\n`); + }); +} diff --git a/src/main/ipc-handlers/insights-handlers.ts b/src/main/ipc-handlers/insights-handlers.ts index 6630a0822d..88e0ca65a8 100644 --- a/src/main/ipc-handlers/insights-handlers.ts +++ b/src/main/ipc-handlers/insights-handlers.ts @@ -12,6 +12,7 @@ import type { InsightsSession, InsightsSessionSummary, InsightsModelConfig, + ChatSlashCommand, ImageAttachment, Task, TaskMetadata, @@ -19,6 +20,7 @@ import type { import { projectStore } from "../project-store"; import { insightsService } from "../insights-service"; import { safeSendToRenderer } from "./utils"; +import { listChatCommands } from "../insights/chat-commands"; import type { ThinkingLevel } from "../../shared/types/settings"; /** Default model for Insights turns (Claude Code model alias) */ @@ -428,6 +430,22 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu } ); + // Claude Code's slash commands and skills in the project (the chat's `/` menu) + ipcMain.handle( + IPC_CHANNELS.INSIGHTS_LIST_COMMANDS, + async (_, projectId: string): Promise> => { + const project = projectStore.getProject(projectId); + if (!project) { + return { success: false, error: "Project not found" }; + } + try { + return { success: true, data: await listChatCommands(project.path, project.settings?.claudeProfileId) }; + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : "Failed to list Claude Code's commands" }; + } + } + ); + // Update model configuration for a session ipcMain.handle( IPC_CHANNELS.INSIGHTS_UPDATE_MODEL_CONFIG, diff --git a/src/preload/api/modules/insights-api.ts b/src/preload/api/modules/insights-api.ts index 5dfd4c29a4..5dbd9b240b 100644 --- a/src/preload/api/modules/insights-api.ts +++ b/src/preload/api/modules/insights-api.ts @@ -5,6 +5,7 @@ import type { InsightsChatStatus, InsightsStreamChunk, InsightsModelConfig, + ChatSlashCommand, ImageAttachment, Task, TaskMetadata, @@ -40,6 +41,7 @@ export interface InsightsAPI { renameInsightsSession: (projectId: string, sessionId: string, newTitle: string) => Promise; updateInsightsModelConfig: (projectId: string, sessionId: string, modelConfig: InsightsModelConfig) => Promise; getInsightsAttachment: (projectId: string, relativePath: string, mimeType: string) => Promise>; + listInsightsCommands: (projectId: string) => Promise>; // Event Listeners onInsightsStreamChunk: ( @@ -120,6 +122,9 @@ export const createInsightsAPI = (): InsightsAPI => ({ getInsightsAttachment: (projectId: string, relativePath: string, mimeType: string): Promise> => invokeIpc(IPC_CHANNELS.INSIGHTS_GET_ATTACHMENT, projectId, relativePath, mimeType), + listInsightsCommands: (projectId: string): Promise> => + invokeIpc(IPC_CHANNELS.INSIGHTS_LIST_COMMANDS, projectId), + // Event Listeners onInsightsStreamChunk: ( callback: (projectId: string, chunk: InsightsStreamChunk) => void diff --git a/src/renderer/components/Insights.tsx b/src/renderer/components/Insights.tsx index f930eba2fc..f257b10cde 100644 --- a/src/renderer/components/Insights.tsx +++ b/src/renderer/components/Insights.tsx @@ -64,7 +64,9 @@ import { import { IS_DEV_BUILD, TITLE_BAR_STRIP_HEIGHT } from '../lib/title-bar'; import { InsightsModelSelector } from './InsightsModelSelector'; import { InsightsMcpMenu } from './InsightsMcpMenu'; +import { InsightsSlashMenu } from './InsightsSlashMenu'; import { InsightsAgentWindowButton } from './InsightsAgentWindowButton'; +import { useSlashCommandMenu } from './insights-slash-commands'; import { useSettingsStore } from '../stores/settings-store'; import { getDefaultMcpConnectorIds } from '../../shared/utils/mcp-connectors'; import { AttachmentPreviewDialog } from './AttachmentPreviewDialog'; @@ -102,6 +104,8 @@ export function Insights({ projectId }: InsightsProps) { const isLoadingSessions = useInsightsStore((state) => state.isLoadingSessions); const [inputValue, setInputValue] = useState(''); + // Where the caret is in the composer (the `/` menu follows it) + const [caret, setCaret] = useState(0); const [creatingTask, setCreatingTask] = useState>(new Set()); const [taskCreated, setTaskCreated] = useState>(new Set()); const [showSidebar, setShowSidebar] = useState(true); @@ -174,6 +178,19 @@ export function Insights({ projectId }: InsightsProps) { const effectiveModelConfig = chatModelConfig({ session, draftModelConfig }); + // The composer's `/` menu: Claude Code's slash commands and skills, with the Clawd button on + const slashMenu = useSlashCommandMenu({ + projectId, + enabled: effectiveModelConfig?.agentMode === true, + value: inputValue, + caret, + onInsert: (value, nextCaret) => { + setInputValue(value); + setCaret(nextCaret); + requestAnimationFrame(() => textareaRef.current?.setSelectionRange(nextCaret, nextCaret)); + }, + }); + const isLoading = status.phase === 'thinking' || status.phase === 'streaming'; const replyingIds = replyingSessionIds({ session, status, backgroundRuns }); @@ -303,6 +320,8 @@ export function Insights({ projectId }: InsightsProps) { }; const handleKeyDown = (e: React.KeyboardEvent) => { + // The open `/` menu takes the arrows, Enter, Tab and Escape + if (slashMenu.handleKeyDown(e)) return; if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); @@ -574,6 +593,16 @@ export function Insights({ projectId }: InsightsProps) { 'transition-shadow duration-150 focus-within:shadow-[0_4px_20px_rgba(0,0,0,0.1),0_0_0_1px_var(--input)]' )} > + {slashMenu.open && ( + + )} {/* Image preview strip */} {pendingImages.length > 0 && (
@@ -616,7 +645,11 @@ export function Insights({ projectId }: InsightsProps) { ref={textareaRef} rows={1} value={inputValue} - onChange={(e) => setInputValue(e.target.value)} + onChange={(e) => { + setInputValue(e.target.value); + setCaret(e.target.selectionStart ?? e.target.value.length); + }} + onSelect={(e) => setCaret(e.currentTarget.selectionStart ?? 0)} onKeyDown={handleKeyDown} onPaste={handlePaste} placeholder={isEmpty ? t('insights.placeholder') : t('insights.replyPlaceholder')} diff --git a/src/renderer/components/InsightsSlashMenu.tsx b/src/renderer/components/InsightsSlashMenu.tsx new file mode 100644 index 0000000000..7256fac595 --- /dev/null +++ b/src/renderer/components/InsightsSlashMenu.tsx @@ -0,0 +1,72 @@ +/** + * The composer's `/` menu: Claude Code's slash commands and skills matching what was typed after + * the slash (state and keys: insights-slash-commands.ts). Sits above the composer; the textarea + * keeps focus, so the menu is driven by its keys and picked with the mouse too. + */ +import { useEffect, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; +import { cn } from '../lib/utils'; +import type { ChatSlashCommand } from '../../shared/types'; + +interface InsightsSlashMenuProps { + items: ChatSlashCommand[]; + activeIndex: number; + loading: boolean; + error: string | null; + onSelect: (command: ChatSlashCommand) => void; + onHover: (index: number) => void; +} + +export function InsightsSlashMenu({ items, activeIndex, loading, error, onSelect, onHover }: InsightsSlashMenuProps) { + const { t } = useTranslation('common'); + const listRef = useRef(null); + + // Keep the active command in view while moving with the arrows + useEffect(() => { + listRef.current?.querySelector(`[data-index="${activeIndex}"]`)?.scrollIntoView({ block: 'nearest' }); + }, [activeIndex]); + + return ( +
e.preventDefault()} + > + {items.length === 0 ? ( +

+ {error && !loading ? t('insights.slashCommands.failed', { error }) : t('insights.slashCommands.loading')} +

+ ) : ( + items.map((command, index) => ( +
onHover(index)} + onClick={() => onSelect(command)} + className={cn( + 'flex min-w-0 cursor-pointer items-baseline gap-3 rounded-lg px-3 py-1.5 text-sm', + index === activeIndex ? 'bg-nav-hover text-foreground' : 'text-foreground' + )} + > + {/* Both parts end in an ellipsis when they don't fit; the command keeps up to 60% of the row */} + + /{command.name} + {command.argumentHint && {command.argumentHint}} + + + {command.description} + +
+ )) + )} +
+ ); +} diff --git a/src/renderer/components/__tests__/insights-slash-commands.test.ts b/src/renderer/components/__tests__/insights-slash-commands.test.ts new file mode 100644 index 0000000000..454d39a028 --- /dev/null +++ b/src/renderer/components/__tests__/insights-slash-commands.test.ts @@ -0,0 +1,38 @@ +/** + * The composer's `/` menu: it opens on a `/` that starts the input or a word, filters by what + * follows, and a picked command replaces the token. + */ +import { describe, it, expect } from 'vitest'; +import { filterSlashCommands, insertSlashCommand, slashTokenAt } from '../insights-slash-commands'; + +describe('slashTokenAt', () => { + it('finds a slash at the start or after a space, up to the caret', () => { + expect(slashTokenAt('/', 1)).toEqual({ start: 0, query: '' }); + expect(slashTokenAt('/gra', 4)).toEqual({ start: 0, query: 'gra' }); + expect(slashTokenAt('run /gra now', 8)).toEqual({ start: 4, query: 'gra' }); + }); + + it('is no token inside a word, a path or after a space', () => { + expect(slashTokenAt('and/or', 6)).toBeNull(); + expect(slashTokenAt('src/main', 8)).toBeNull(); + expect(slashTokenAt('/usr/bin', 8)).toBeNull(); + expect(slashTokenAt('/graphify ', 10)).toBeNull(); + }); +}); + +describe('filterSlashCommands', () => { + const commands = [{ name: 'review', description: '' }, { name: 'graphify', description: '' }, { name: 'pr-review', description: '' }]; + + it('lists names starting with the query first, then names containing it', () => { + expect(filterSlashCommands(commands, 'rev').map((c) => c.name)).toEqual(['review', 'pr-review']); + expect(filterSlashCommands(commands, '').map((c) => c.name)).toEqual(['graphify', 'pr-review', 'review']); + expect(filterSlashCommands(commands, 'xyz')).toEqual([]); + }); +}); + +describe('insertSlashCommand', () => { + it('replaces the token with the command and a space, the caret after it', () => { + expect(insertSlashCommand('/gra', { start: 0, query: 'gra' }, 4, 'graphify')).toEqual({ value: '/graphify ', caret: 10 }); + expect(insertSlashCommand('run /gr now', { start: 4, query: 'gr' }, 7, 'graphify')).toEqual({ value: 'run /graphify now', caret: 14 }); + }); +}); diff --git a/src/renderer/components/insights-slash-commands.ts b/src/renderer/components/insights-slash-commands.ts new file mode 100644 index 0000000000..de2e0d5418 --- /dev/null +++ b/src/renderer/components/insights-slash-commands.ts @@ -0,0 +1,151 @@ +/** + * The chat composer's `/` menu (with the Clawd button on): Claude Code's slash commands and skills + * in the project, listed when the caret follows a `/` that starts the input or a word, filtered + * by what was typed after it, as in Claude Code's own prompt. The commands are asked once per + * project (main: insights/chat-commands.ts) and kept for the app's session. + */ +import { useCallback, useEffect, useMemo, useState, type KeyboardEvent } from 'react'; +import type { ChatSlashCommand } from '../../shared/types'; + +/** The `/` token the caret is in: where it starts and what follows the slash */ +export interface SlashToken { + start: number; + query: string; +} + +/** The `/` token that ends at the caret, or null (a `/` inside a word or a path isn't one) */ +export function slashTokenAt(value: string, caret: number): SlashToken | null { + const match = /(^|\s)\/([^\s/]*)$/.exec(value.slice(0, caret)); + if (!match) return null; + return { start: match.index + match[1].length, query: match[2] }; +} + +/** Commands matching the query: names starting with it first, then names containing it */ +export function filterSlashCommands(commands: ChatSlashCommand[], query: string): ChatSlashCommand[] { + const q = query.toLowerCase(); + const byName = (a: ChatSlashCommand, b: ChatSlashCommand) => a.name.localeCompare(b.name); + const starts = commands.filter((command) => command.name.toLowerCase().startsWith(q)).sort(byName); + const contains = q + ? commands.filter((command) => !command.name.toLowerCase().startsWith(q) && command.name.toLowerCase().includes(q)).sort(byName) + : []; + return [...starts, ...contains]; +} + +/** The input with the token replaced by the command (and a space), and the caret after it */ +export function insertSlashCommand(value: string, token: SlashToken, caret: number, name: string): { value: string; caret: number } { + const inserted = `/${name} `; + const rest = value.slice(caret).replace(/^\S*/, ''); + return { value: value.slice(0, token.start) + inserted + rest.replace(/^ /, ''), caret: token.start + inserted.length }; +} + +type CommandsState = { status: 'loading' } | { status: 'ready'; commands: ChatSlashCommand[] } | { status: 'error'; error: string }; + +/** Each project's commands, asked once per app session */ +const commandsByProject = new Map(); +const pending = new Map>(); + +function loadCommands(projectId: string): Promise { + const existing = pending.get(projectId); + if (existing) return existing; + const request = window.electronAPI.listInsightsCommands(projectId) + .then((result): CommandsState => result.success && result.data + ? { status: 'ready', commands: result.data } + : { status: 'error', error: result.error ?? '' }) + .catch((error: unknown): CommandsState => ({ status: 'error', error: error instanceof Error ? error.message : String(error) })) + .then((state) => { + commandsByProject.set(projectId, state); + pending.delete(projectId); + return state; + }); + pending.set(projectId, request); + return request; +} + +interface SlashMenuOptions { + projectId: string; + /** The Clawd button is on: the menu works only then */ + enabled: boolean; + value: string; + caret: number; + /** Apply the input after a command was picked */ + onInsert: (value: string, caret: number) => void; +} + +/** The `/` menu's state and keyboard handling for the composer */ +export function useSlashCommandMenu({ projectId, enabled, value, caret, onInsert }: SlashMenuOptions) { + const [commands, setCommands] = useState(() => commandsByProject.get(projectId)); + const [activeIndex, setActiveIndex] = useState(0); + // The token the user closed the menu on (Escape): it stays closed until another one starts + const [dismissedAt, setDismissedAt] = useState(null); + + const token = enabled ? slashTokenAt(value, caret) : null; + const open = !!token && token.start !== dismissedAt; + + // Asked once the menu is first needed (stored for the app's session afterwards; asked again + // only after a failure) + useEffect(() => { + setCommands(commandsByProject.get(projectId)); + if (!enabled || commandsByProject.get(projectId)?.status === 'ready') return; + let cancelled = false; + void loadCommands(projectId).then((state) => { + if (!cancelled) setCommands(state); + }); + return () => { + cancelled = true; + }; + }, [projectId, enabled]); + + const items = useMemo( + () => (open && commands?.status === 'ready' ? filterSlashCommands(commands.commands, token.query) : []), + [open, commands, token?.query] + ); + + // A new query starts at the top + useEffect(() => setActiveIndex(0), [token?.query, token?.start]); + // A new token can open the menu again + useEffect(() => { + if (dismissedAt !== null && token?.start !== dismissedAt) setDismissedAt(null); + }, [token?.start, dismissedAt]); + + const select = useCallback((command: ChatSlashCommand) => { + if (!token) return; + const next = insertSlashCommand(value, token, caret, command.name); + onInsert(next.value, next.caret); + }, [token, value, caret, onInsert]); + + /** Keys the open menu takes (arrows, Enter or Tab to pick, Escape to close); true when handled */ + const handleKeyDown = (e: KeyboardEvent): boolean => { + if (!open || !token) return false; + if (e.key === 'Escape') { + e.preventDefault(); + setDismissedAt(token.start); + return true; + } + if (items.length === 0) return false; + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + const step = e.key === 'ArrowDown' ? 1 : -1; + setActiveIndex((index) => (index + step + items.length) % items.length); + return true; + } + if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') { + e.preventDefault(); + select(items[Math.min(activeIndex, items.length - 1)]); + return true; + } + return false; + }; + + // Shown while open: the matches, or the list's state while it loads or when it failed + const visible = open && (items.length > 0 || commands === undefined || commands.status !== 'ready'); + return { + open: visible, + items, + activeIndex: Math.min(activeIndex, Math.max(items.length - 1, 0)), + setActiveIndex, + loading: !commands || commands.status === 'loading', + error: commands?.status === 'error' ? commands.error : null, + select, + handleKeyDown, + }; +} diff --git a/src/renderer/lib/mocks/insights-mock.ts b/src/renderer/lib/mocks/insights-mock.ts index 086ef49d01..a1e7587efd 100644 --- a/src/renderer/lib/mocks/insights-mock.ts +++ b/src/renderer/lib/mocks/insights-mock.ts @@ -84,6 +84,7 @@ export const insightsMock = { success: false, error: 'Not available in browser mock' }), + listInsightsCommands: async (_projectId: string) => ({ success: true, data: [] }), updateInsightsModelConfig: async (_projectId: string, _sessionId: string, _modelConfig: unknown) => { console.warn('[Browser Mock] updateInsightsModelConfig called'); return { success: true }; diff --git a/src/shared/constants/ipc.ts b/src/shared/constants/ipc.ts index f23c6372a4..076146a040 100644 --- a/src/shared/constants/ipc.ts +++ b/src/shared/constants/ipc.ts @@ -212,6 +212,7 @@ export const IPC_CHANNELS = { INSIGHTS_RENAME_SESSION: 'insights:renameSession', INSIGHTS_UPDATE_MODEL_CONFIG: 'insights:updateModelConfig', INSIGHTS_GET_ATTACHMENT: 'insights:getAttachment', + INSIGHTS_LIST_COMMANDS: 'insights:listCommands', // Claude Code's slash commands and skills in a project // Insights events (main -> renderer) INSIGHTS_STREAM_CHUNK: 'insights:streamChunk', diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index 7e31e37ac7..8525609a04 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -244,6 +244,11 @@ "replying": "Wait for the reply to finish", "noRoom": "This project has no room for another agent window" }, + "slashCommands": { + "label": "Slash commands and skills", + "loading": "Loading commands...", + "failed": "Couldn't list Claude Code's commands: {{error}}" + }, "cliNotFound": "{{name}} CLI not detected", "kanbanTools": { "label": "Kanban", diff --git a/src/shared/types/insights.ts b/src/shared/types/insights.ts index 61bcea58d9..4cb4d492a4 100644 --- a/src/shared/types/insights.ts +++ b/src/shared/types/insights.ts @@ -38,6 +38,13 @@ export interface InsightsModelConfig { playwrightBrowser?: PlaywrightBrowserChoice | null; } +/** A slash command or skill Claude Code offers in the project (the chat's `/` menu) */ +export interface ChatSlashCommand { + name: string; + description: string; + argumentHint?: string; +} + type InsightsChatRole = 'user' | 'assistant'; // Tool usage record for showing what tools the AI used diff --git a/src/shared/types/ipc.ts b/src/shared/types/ipc.ts index 849c7d28a1..2a7dc94aa4 100644 --- a/src/shared/types/ipc.ts +++ b/src/shared/types/ipc.ts @@ -91,7 +91,8 @@ import type { InsightsSessionSummary, InsightsChatStatus, InsightsStreamChunk, - InsightsModelConfig + InsightsModelConfig, + ChatSlashCommand } from './insights'; import type { APIProfile, ProfilesFile, TestConnectionResult, DiscoverModelsResult } from './profile'; @@ -422,6 +423,8 @@ export interface ElectronAPI { updateInsightsModelConfig: (projectId: string, sessionId: string, modelConfig: InsightsModelConfig) => Promise; /** Full-size image stored for an Insights message, as a data URL */ getInsightsAttachment: (projectId: string, relativePath: string, mimeType: string) => Promise>; + /** Claude Code's slash commands and skills in the project (the chat's `/` menu with the Clawd button) */ + listInsightsCommands: (projectId: string) => Promise>; // Insights event listeners onInsightsStreamChunk: ( From c7b684bf2c1a9422dae1164e95394033c6464050 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sun, 8 Nov 2026 00:51:41 +0400 Subject: [PATCH 12/74] fix(chat): review fixes for the slash commands menu - A local command's output (/compact) is its reply and keeps the session, instead of failing as an empty response; the menu leaves out built-ins that don't fit a chat (/clear, /model, internal ones). - A slash command folded into a new session's prompt stays at its start, where Claude Code runs it. - The commands probe runs through startClaudeProcess (no uncaught EPIPE, stderr read after close), without MCP servers, and fails with codes the renderer words. - The list is kept per project and account, asked again when the Clawd button is switched on and after a failure. - Enter sends a command typed out in full, Shift+Tab and IME keys are left alone, the pointer only picks rows when it moves, and the menu is a portal placed above or below the composer so nothing clips it. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +- package-lock.json | 4 +- package.json | 2 +- .../insights/__tests__/chat-commands.test.ts | 74 +++++++-- .../__tests__/claude-code-runner.test.ts | 23 +++ src/main/insights/__tests__/prompts.test.ts | 8 + src/main/insights/chat-commands.ts | 149 ++++++++++-------- src/main/insights/claude-code-runner.ts | 36 ++++- src/main/insights/prompts.ts | 8 +- src/main/ipc-handlers/insights-handlers.ts | 10 +- src/renderer/components/Insights.tsx | 14 ++ src/renderer/components/InsightsSlashMenu.tsx | 78 +++++++-- .../__tests__/insights-slash-commands.test.ts | 5 +- .../insights-slash-menu-keys.test.ts | 75 +++++++++ .../components/insights-slash-commands.ts | 134 +++++++++++----- src/shared/i18n/locales/en/common.json | 8 +- src/shared/types/insights.ts | 7 + 17 files changed, 486 insertions(+), 154 deletions(-) create mode 100644 src/renderer/components/__tests__/insights-slash-menu-keys.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index f225585697..487cc781e1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -439,8 +439,9 @@ headless stream-json run built in `insights/claude-code-runner.ts`, on the proje `--tools` or `--strict-mcp-config` (every tool, the user's own MCP servers too) and the agent windows' permissions (`--dangerously-skip-permissions` when Settings skips them, else `--permission-mode auto`, since a headless turn can't ask). Off again, the same session continues read-only. With it on, the composer's `/` menu lists Claude Code's slash - commands and skills (`insights-slash-commands.ts`; asked once per project with the control protocol's `initialize` - request, `insights/chat-commands.ts`, no model call). A chat with a session also shows a Clawd button under the browser + commands and skills, minus built-ins that don't fit a chat (`/clear`, `/model`...) (`insights-slash-commands.ts`; asked per project and account with the + control protocol's `initialize` request, without MCP servers or a model call, again when the button is switched on, + `insights/chat-commands.ts`). A local command's output (`/compact`) is its reply and keeps the session. A chat with a session also shows a Clawd button under the browser button that opens its session in an agent window (`claude --resume` on its account, `openProjectSession`). - **MCP per chat** — `--strict-mcp-config` loads only the servers chosen in the chat's MCP menu (`InsightsMcpMenu.tsx`, the Connectors defaults until changed) and, with the Kanban button on, Workbench's task tools diff --git a/package-lock.json b/package-lock.json index 4898c89399..29257b9e17 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.11", + "version": "1.6.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.11", + "version": "1.6.12", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index ff02e87980..5f8dc064e6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.11", + "version": "1.6.12", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/main/insights/__tests__/chat-commands.test.ts b/src/main/insights/__tests__/chat-commands.test.ts index 2cfd89550d..779a4d3afe 100644 --- a/src/main/insights/__tests__/chat-commands.test.ts +++ b/src/main/insights/__tests__/chat-commands.test.ts @@ -1,43 +1,83 @@ /** * The chat's `/` menu asks Claude Code for its commands with the control protocol's initialize - * request: only the answer to that request counts, and each command keeps its name, description - * and argument hint. + * request: only the answer to that request counts, commands that don't fit a chat are left out, + * and a failure comes back as a code the renderer words. */ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; -vi.mock('../../claude-code/env', () => ({ resolveClaudeEnv: vi.fn() })); -vi.mock('../../platform/runtime-exec', () => ({ spawnTool: vi.fn(), killRuntimeProcess: vi.fn() })); +const startClaudeProcess = vi.hoisted(() => vi.fn()); +vi.mock('../../claude-code/env', () => ({ resolveClaudeEnv: vi.fn(async () => ({ command: 'claude', env: {} })) })); +vi.mock('../../claude-code/process', () => ({ startClaudeProcess })); vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn() } })); -import { parseCommandsResponse } from '../chat-commands'; +import { ChatCommandsListError, listChatCommands, parseCommandsResponse } from '../chat-commands'; -const response = (body: Record) => JSON.stringify({ type: 'control_response', response: { request_id: 'workbench-commands', ...body } }); +const response = (body: Record) => ({ type: 'control_response', response: { request_id: 'workbench-commands', ...body } }); + +/** A fake Claude Code that sends `messages`, then ends with `outcome` */ +function fakeRun(messages: unknown[], outcome: Record = {}) { + startClaudeProcess.mockImplementation((options: { onMessage: (message: unknown) => void }) => { + const stop = vi.fn(); + const done = Promise.resolve().then(() => { + for (const message of messages) options.onMessage(message); + return { exitCode: 0, stderr: '', timedOut: false, ...outcome }; + }); + return { done, stop }; + }); +} + +beforeEach(() => { + startClaudeProcess.mockReset(); +}); describe('parseCommandsResponse', () => { - it('reads the commands of the initialize answer', () => { - const line = response({ + it('reads the commands of the initialize answer, leaving out the ones that don\'t fit a chat', () => { + const commands = parseCommandsResponse(response({ subtype: 'success', response: { commands: [ { name: 'graphify', description: 'Query the graph (user)', argumentHint: '' }, { name: 'design', description: 'Grant access', argumentHint: 'consent | revoke', builtin: true }, + { name: 'clear', description: 'Clear the conversation' }, + { name: '__remote-workflow', description: 'internal' }, + { name: 'compact', description: 'Compact' }, + { name: 'graphify', description: 'duplicate' }, { description: 'nameless' }, ], }, - }); - expect(parseCommandsResponse(line)).toEqual([ + })); + expect(commands).toEqual([ { name: 'graphify', description: 'Query the graph (user)' }, { name: 'design', description: 'Grant access', argumentHint: 'consent | revoke' }, + { name: 'compact', description: 'Compact' }, ]); }); - it('ignores other lines and other requests\' answers', () => { - expect(parseCommandsResponse('{"type":"system","subtype":"init"}')).toBeNull(); - expect(parseCommandsResponse('not json')).toBeNull(); - expect(parseCommandsResponse(JSON.stringify({ type: 'control_response', response: { request_id: 'other', subtype: 'success' } }))).toBeNull(); + it('ignores other messages and other requests\' answers', () => { + expect(parseCommandsResponse({ type: 'system', subtype: 'init' })).toBeNull(); + expect(parseCommandsResponse({ type: 'control_response', response: { request_id: 'other', subtype: 'success' } })).toBeNull(); + }); + + it('fails when Claude Code refuses or answers without a list', () => { + expect(() => parseCommandsResponse(response({ subtype: 'error', error: 'not signed in' }))).toThrow(ChatCommandsListError); + expect(() => parseCommandsResponse(response({ subtype: 'success', response: {} }))).toThrow(ChatCommandsListError); + }); +}); + +describe('listChatCommands', () => { + it('asks with initialize, without MCP servers or a saved session, and returns the list', async () => { + fakeRun([{ type: 'system' }, response({ subtype: 'success', response: { commands: [{ name: 'review', description: 'Review' }] } })]); + await expect(listChatCommands('/project')).resolves.toEqual([{ name: 'review', description: 'Review' }]); + const options = startClaudeProcess.mock.calls[0][0] as { args: string[]; input: string; cwd: string }; + expect(options.cwd).toBe('/project'); + expect(options.args).toEqual(expect.arrayContaining(['--strict-mcp-config', '--no-session-persistence', '--input-format', 'stream-json'])); + expect(JSON.parse(options.input)).toMatchObject({ type: 'control_request', request: { subtype: 'initialize' } }); }); - it('fails with Claude Code\'s error', () => { - expect(() => parseCommandsResponse(response({ subtype: 'error', error: 'not signed in' }))).toThrow('not signed in'); + it('fails with a code: timeout, or failed when Claude Code exits without answering', async () => { + fakeRun([], { timedOut: true, exitCode: null }); + await expect(listChatCommands('/project')).rejects.toMatchObject({ code: 'timeout' }); + fakeRun([], { exitCode: 1, stderr: 'error: unknown option' }); + await expect(listChatCommands('/project')).rejects.toMatchObject({ code: 'failed' }); }); }); diff --git a/src/main/insights/__tests__/claude-code-runner.test.ts b/src/main/insights/__tests__/claude-code-runner.test.ts index 0a36b11863..81a54b4727 100644 --- a/src/main/insights/__tests__/claude-code-runner.test.ts +++ b/src/main/insights/__tests__/claude-code-runner.test.ts @@ -372,6 +372,29 @@ describe('runInsights', () => { expect(systemPrompt).not.toContain('glab'); }); + it('takes a local slash command\'s output as the reply and keeps its session (no assistant message)', async () => { + setRun([ + { type: 'system', subtype: 'init', session_id: 'sess-1', tools: [] }, + { type: 'system', subtype: 'compact_boundary', session_id: 'sess-1', uuid: 'boundary-1' }, + { type: 'user', uuid: 'stdout-1', message: { content: 'Compacted ' } }, + { type: 'result', subtype: 'success', is_error: false, result: '', session_id: 'sess-1' }, + ]); + const result = await (await run({ message: '/compact' })).promise; + expect(result.text).toBe('Compacted'); + expect(result.claudeRef).toEqual({ sessionId: 'sess-1', messageUuid: 'stdout-1', profileId: 'main' }); + }); + + it('accepts a slash command that printed nothing; other empty replies are still an error', async () => { + const quiet = [ + { type: 'system', subtype: 'init', session_id: 'sess-1', tools: [] }, + { type: 'result', subtype: 'success', is_error: false, result: '', session_id: 'sess-1' }, + ]; + setRun(quiet); + await expect((await run({ message: '/reload-plugins' })).promise).resolves.toMatchObject({ text: '' }); + setRun(quiet); + await expect((await run()).promise).rejects.toThrow('empty response'); + }); + it('gives a turn with the Clawd button what an agent window has: every tool, the user\'s MCP servers, auto mode', async () => { setRun(conversation); await (await run({ agentMode: { skipPermissions: false }, cliTools: { github: true } })).promise; diff --git a/src/main/insights/__tests__/prompts.test.ts b/src/main/insights/__tests__/prompts.test.ts index d9bd51f333..17afaeca92 100644 --- a/src/main/insights/__tests__/prompts.test.ts +++ b/src/main/insights/__tests__/prompts.test.ts @@ -15,6 +15,14 @@ describe('buildConversationPrompt', () => { }); }); +describe('buildConversationPrompt with a slash command', () => { + it('keeps the command at the start, where Claude Code runs it, with the conversation after it', () => { + const prompt = buildConversationPrompt('/review the auth module', [{ role: 'user', content: 'Hi' }, { role: 'assistant', content: 'Hello' }]); + expect(prompt.startsWith('/review the auth module\n\n')).toBe(true); + expect(prompt).toContain('User: Hi'); + }); +}); + describe('extractToolInput', () => { it('describes common tool arguments', () => { expect(extractToolInput({ command: 'graphify query auth' })).toBe('graphify query auth'); diff --git a/src/main/insights/chat-commands.ts b/src/main/insights/chat-commands.ts index 73e4a670c6..d53f338bb4 100644 --- a/src/main/insights/chat-commands.ts +++ b/src/main/insights/chat-commands.ts @@ -5,12 +5,14 @@ * Asked the way the Agent SDK asks: a headless Claude Code with stream-json input gets the * control protocol's `initialize` request and answers with its commands (built-in ones that work * headless, the user's and the project's commands, skills and plugins'), each with a description - * and argument hint. No message is sent, so the model isn't called; the process is stopped once - * it answered. + * and argument hint. No message is sent, so the model isn't called, and Claude Code exits once it + * answered (its input ends after the request). It starts without MCP servers + * (`--strict-mcp-config`): starting the user's servers only to read the list would launch them for + * nothing; their prompts are left out of the menu. */ -import type { ChatSlashCommand } from '../../shared/types'; +import type { ChatCommandsError, ChatSlashCommand } from '../../shared/types'; import { resolveClaudeEnv } from '../claude-code/env'; -import { killRuntimeProcess, spawnTool } from '../platform/runtime-exec'; +import { startClaudeProcess } from '../claude-code/process'; import { appLog } from '../app-logger'; /** How long Claude Code may take to start and answer */ @@ -18,23 +20,53 @@ const PROBE_TIMEOUT_MS = 30_000; const REQUEST_ID = 'workbench-commands'; -/** The commands from a control response line, or null when the line is something else */ -export function parseCommandsResponse(line: string): ChatSlashCommand[] | null { - let message: { type?: unknown; response?: { request_id?: unknown; subtype?: unknown; error?: unknown; response?: { commands?: unknown } } }; - try { - message = JSON.parse(line) as typeof message; - } catch { - return null; +/** A failure to list the commands, with its code for the renderer (the details are logged) */ +export class ChatCommandsListError extends Error { + constructor(readonly code: ChatCommandsError, details?: string) { + super(details || code); } - if (message.type !== 'control_response' || message.response?.request_id !== REQUEST_ID) return null; - if (message.response.subtype !== 'success') { - throw new Error(typeof message.response.error === 'string' ? message.response.error : 'Claude Code did not list its commands'); +} + +/** + * Built-in commands that don't fit a chat, left out of the menu: `/clear` starts an empty session + * behind the chat's history; the model, effort and output settings are the chat's own buttons; + * the rest only work in Claude Code's interactive terminal or are internal + */ +const CHAT_HIDDEN_COMMANDS = new Set([ + 'clear', + 'model', + 'effort', + 'fast', + 'output-style', + 'color', + 'config', + 'focus', + 'heapdump', + 'auto-mode-setup', + 'workflow-launch-exec', +]); + +/** Whether a command belongs in the chat's menu (see CHAT_HIDDEN_COMMANDS; `__` names are internal) */ +function isChatCommand(name: string): boolean { + return !name.startsWith('__') && !CHAT_HIDDEN_COMMANDS.has(name); +} + +/** The commands from a control response message, or null when the message is something else */ +export function parseCommandsResponse(message: unknown): ChatSlashCommand[] | null { + const raw = message as { type?: unknown; response?: { request_id?: unknown; subtype?: unknown; error?: unknown; response?: { commands?: unknown } } }; + if (raw?.type !== 'control_response' || raw.response?.request_id !== REQUEST_ID) return null; + if (raw.response.subtype !== 'success') { + throw new ChatCommandsListError('notListed', typeof raw.response.error === 'string' ? raw.response.error : undefined); } - const commands = Array.isArray(message.response.response?.commands) ? message.response.response.commands : []; + const commands = raw.response.response?.commands; + // A Claude Code that answers without a command list can't fill the menu + if (!Array.isArray(commands)) throw new ChatCommandsListError('notListed'); + const seen = new Set(); return (commands as Array<{ name?: unknown; description?: unknown; argumentHint?: unknown }>) - .filter((command) => typeof command.name === 'string' && command.name) + .filter((command): command is { name: string } & typeof command => typeof command.name === 'string' && !!command.name) + .filter((command) => isChatCommand(command.name) && !seen.has(command.name) && !!seen.add(command.name)) .map((command) => ({ - name: command.name as string, + name: command.name, description: typeof command.description === 'string' ? command.description : '', ...(typeof command.argumentHint === 'string' && command.argumentHint ? { argumentHint: command.argumentHint } : {}), })); @@ -43,56 +75,39 @@ export function parseCommandsResponse(line: string): ChatSlashCommand[] | null { /** Claude Code's slash commands and skills in `projectDir`, on the project's account */ export async function listChatCommands(projectDir: string, profileId?: string): Promise { const { command, env } = await resolveClaudeEnv({ profileId }); - const child = spawnTool('claude', [ - '-p', - '--input-format', 'stream-json', - '--output-format', 'stream-json', - '--verbose', - '--no-session-persistence', - ], { command, cwd: projectDir, env, windowsHide: true, stdio: 'pipe' }); - - return new Promise((resolve, reject) => { - let buffer = ''; - let stderr = ''; - let settled = false; - const finish = (error: Error | null, commands?: ChatSlashCommand[]) => { - if (settled) return; - settled = true; - clearTimeout(timer); - if (child.exitCode === null && !child.killed) killRuntimeProcess(child); - if (error) reject(error); - else resolve(commands ?? []); - }; - const timer = setTimeout(() => finish(new Error('Claude Code did not list its commands in time')), PROBE_TIMEOUT_MS); - - child.stdout?.setEncoding('utf8'); - child.stdout?.on('data', (chunk: string) => { - buffer += chunk; - let newline: number; - while ((newline = buffer.indexOf('\n')) >= 0) { - const line = buffer.slice(0, newline).trim(); - buffer = buffer.slice(newline + 1); - if (!line.startsWith('{')) continue; - try { - const commands = parseCommandsResponse(line); - if (commands) finish(null, commands); - } catch (error) { - finish(error instanceof Error ? error : new Error(String(error))); - } + let commands: ChatSlashCommand[] | null = null; + let parseError: unknown; + const handle = startClaudeProcess({ + command, + args: [ + '-p', + '--input-format', 'stream-json', + '--output-format', 'stream-json', + '--verbose', + '--no-session-persistence', + '--strict-mcp-config', + ], + cwd: projectDir, + env, + // The request, then the end of input: Claude Code answers and exits + input: `${JSON.stringify({ type: 'control_request', request_id: REQUEST_ID, request: { subtype: 'initialize' } })}\n`, + onMessage: (message) => { + if (commands || parseError) return; + try { + commands = parseCommandsResponse(message); + } catch (error) { + parseError = error; } - }); - child.stderr?.setEncoding('utf8'); - child.stderr?.on('data', (chunk: string) => { - stderr = (stderr + chunk).slice(-2000); - }); - child.on('error', (error) => finish(error)); - child.on('exit', (code) => { - if (!settled) { - appLog.warn(`[Insights] Claude Code exited (${code}) before listing its commands: ${stderr.trim()}`); - finish(new Error(stderr.trim() || `Claude Code exited with code ${code}`)); - } - }); - - child.stdin?.write(`${JSON.stringify({ type: 'control_request', request_id: REQUEST_ID, request: { subtype: 'initialize' } })}\n`); + // Nothing else is needed from it + if (commands || parseError) handle.stop(); + }, + timeoutMs: PROBE_TIMEOUT_MS, }); + const outcome = await handle.done; + if (parseError) throw parseError; + if (commands) return commands; + if (outcome.timedOut) throw new ChatCommandsListError('timeout'); + const details = outcome.stderr.trim() || `exit code ${outcome.exitCode}`; + appLog.warn(`[Insights] Claude Code did not list its commands: ${details}`); + throw new ChatCommandsListError('failed', details); } diff --git a/src/main/insights/claude-code-runner.ts b/src/main/insights/claude-code-runner.ts index 8d8dee5e74..10c09bf9d5 100644 --- a/src/main/insights/claude-code-runner.ts +++ b/src/main/insights/claude-code-runner.ts @@ -329,6 +329,24 @@ interface StreamState { sessionId?: string; /** The turn's last assistant message, where a later fork can cut the session */ lastAssistantUuid?: string; + /** + * The last message the turn wrote to its session (a slash command's output, a compact boundary): + * the session's point after a turn with no assistant message + */ + lastUuid?: string; + /** What a local slash command printed (`/compact`'s "Compacted"), its reply when no text came */ + localOutput?: string; +} + +/** A local slash command's output, from the user message Claude Code records it in */ +function localCommandOutput(content: unknown): string | undefined { + const text = typeof content === 'string' + ? content + : Array.isArray(content) + ? (content as Array<{ type?: string; text?: string }>).map((block) => (block.type === 'text' ? block.text ?? '' : '')).join('') + : ''; + const match = /([\s\S]*?)<\/local-command-stdout>/.exec(text); + return match ? match[1].trim() : undefined; } function createStreamState(): StreamState { @@ -343,6 +361,9 @@ function handleInsightsEvent( ): void { const raw = event as Record; if (typeof raw.session_id === 'string' && (raw.type === 'system' || raw.type === 'result')) state.sessionId = raw.session_id; + if (typeof raw.uuid === 'string' && (raw.type === 'assistant' || raw.type === 'user' || raw.subtype === 'compact_boundary')) { + state.lastUuid = raw.uuid; + } switch (raw.type) { case 'assistant': { if (typeof raw.uuid === 'string') state.lastAssistantUuid = raw.uuid; @@ -389,6 +410,8 @@ function handleInsightsEvent( } case 'user': { const content = (raw.message as { content?: unknown } | undefined)?.content; + const output = localCommandOutput(content); + if (output !== undefined) state.localOutput = output; if (Array.isArray(content)) { for (const block of content as Array<{ type?: string; tool_use_id?: string }>) { if (block.type === 'tool_result') { @@ -663,18 +686,23 @@ export async function runInsights(config: InsightsRunConfig, onStream?: Insights throw new Error(outcome.stderr.trim() || `Claude Code exited with code ${outcome.exitCode}`); } - const text = state.text.trim() ? state.text : (state.result?.text ?? ''); - if (!text.trim()) { + // A local slash command (`/compact`) has no assistant message: its output (or nothing) is the reply + const slashCommand = message.trimStart().startsWith('/'); + const text = state.text.trim() ? state.text : (state.result?.text || state.localOutput || ''); + if (!text.trim() && !slashCommand) { throw new Error(EMPTY_RESPONSE_ERROR); } + // Where the session is now: the reply's last assistant message, else (a local command) the + // last message the turn wrote + const cutAt = state.lastAssistantUuid ?? (slashCommand ? state.lastUuid : undefined); // Suggestion lines become cards: the reply keeps the rest return { text: stripTaskSuggestions(text), taskSuggestions: extractTaskSuggestions(text), toolCalls: state.toolCalls, - claudeRef: state.sessionId && state.lastAssistantUuid - ? { sessionId: state.sessionId, messageUuid: state.lastAssistantUuid, profileId } + claudeRef: state.sessionId && cutAt + ? { sessionId: state.sessionId, messageUuid: cutAt, profileId } : undefined, }; } catch (error) { diff --git a/src/main/insights/prompts.ts b/src/main/insights/prompts.ts index 077654f2d5..e30c35cb7d 100644 --- a/src/main/insights/prompts.ts +++ b/src/main/insights/prompts.ts @@ -17,12 +17,18 @@ export interface InsightsMessage { export type { TaskSuggestion } from '../../shared/utils/task-suggestions'; -/** Fold the conversation history into a single prompt (each turn is a fresh run) */ +/** + * Fold the conversation history into a single prompt (each turn is a fresh run). A slash command + * stays at the start, where Claude Code runs it, with the conversation after it as context + */ export function buildConversationPrompt(message: string, history: InsightsMessage[] = []): string { if (history.length === 0) return message; const conversationContext = history .map((msg) => `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}`) .join('\n\n'); + if (message.trimStart().startsWith('/')) { + return `${message.trim()}\n\nThe conversation so far, for context:\n${conversationContext}`; + } return `Previous conversation:\n${conversationContext}\n\nCurrent question: ${message}`; } diff --git a/src/main/ipc-handlers/insights-handlers.ts b/src/main/ipc-handlers/insights-handlers.ts index 88e0ca65a8..3211b6929c 100644 --- a/src/main/ipc-handlers/insights-handlers.ts +++ b/src/main/ipc-handlers/insights-handlers.ts @@ -13,6 +13,7 @@ import type { InsightsSessionSummary, InsightsModelConfig, ChatSlashCommand, + ChatCommandsError, ImageAttachment, Task, TaskMetadata, @@ -20,7 +21,8 @@ import type { import { projectStore } from "../project-store"; import { insightsService } from "../insights-service"; import { safeSendToRenderer } from "./utils"; -import { listChatCommands } from "../insights/chat-commands"; +import { ChatCommandsListError, listChatCommands } from "../insights/chat-commands"; +import { appLog } from "../app-logger"; import type { ThinkingLevel } from "../../shared/types/settings"; /** Default model for Insights turns (Claude Code model alias) */ @@ -434,14 +436,16 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu ipcMain.handle( IPC_CHANNELS.INSIGHTS_LIST_COMMANDS, async (_, projectId: string): Promise> => { + // The error is a ChatCommandsError code, which the renderer words const project = projectStore.getProject(projectId); if (!project) { - return { success: false, error: "Project not found" }; + return { success: false, error: "projectNotFound" satisfies ChatCommandsError }; } try { return { success: true, data: await listChatCommands(project.path, project.settings?.claudeProfileId) }; } catch (error) { - return { success: false, error: error instanceof Error ? error.message : "Failed to list Claude Code's commands" }; + if (!(error instanceof ChatCommandsListError)) appLog.warn("[Insights] Listing Claude Code's commands failed:", error); + return { success: false, error: error instanceof ChatCommandsListError ? error.code : ("failed" satisfies ChatCommandsError) }; } } ); diff --git a/src/renderer/components/Insights.tsx b/src/renderer/components/Insights.tsx index f257b10cde..a1085d59ea 100644 --- a/src/renderer/components/Insights.tsx +++ b/src/renderer/components/Insights.tsx @@ -67,6 +67,7 @@ import { InsightsMcpMenu } from './InsightsMcpMenu'; import { InsightsSlashMenu } from './InsightsSlashMenu'; import { InsightsAgentWindowButton } from './InsightsAgentWindowButton'; import { useSlashCommandMenu } from './insights-slash-commands'; +import { useWindowClaudeAccountId } from '../hooks/useWindowClaudeAccount'; import { useSettingsStore } from '../stores/settings-store'; import { getDefaultMcpConnectorIds } from '../../shared/utils/mcp-connectors'; import { AttachmentPreviewDialog } from './AttachmentPreviewDialog'; @@ -117,6 +118,8 @@ export function Insights({ projectId }: InsightsProps) { const setPendingImages = useInsightsStore((state) => state.setPendingImages); const textareaRef = useRef(null); + // The composer's box: the `/` menu is placed at it + const composerRef = useRef(null); const fileInputRef = useRef(null); const [previewAttachment, setPreviewAttachment] = useState(null); @@ -179,8 +182,13 @@ export function Insights({ projectId }: InsightsProps) { const effectiveModelConfig = chatModelConfig({ session, draftModelConfig }); // The composer's `/` menu: Claude Code's slash commands and skills, with the Clawd button on + // The account the chat's turns run on (an API profile in use, else the project's Claude + // account): the commands depend on it + const claudeAccountId = useWindowClaudeAccountId(); + const apiProfileId = useSettingsStore((state) => state.activeProfileId); const slashMenu = useSlashCommandMenu({ projectId, + accountKey: apiProfileId ? `api:${apiProfileId}` : claudeAccountId, enabled: effectiveModelConfig?.agentMode === true, value: inputValue, caret, @@ -587,6 +595,7 @@ export function Insights({ projectId }: InsightsProps) { const composer = (
{slashMenu.open && ( setNow(Date.now())}> {content && {content}} + {/* A slash command that ran without output (a local one such as /compact) */} + {!content && !message.stopped && !message.toolsUsed?.length && ( +

{t('insights.slashCommands.noOutput')}

+ )} {/* A stopped reply says so, under what it had written by then */} {message.stopped && (

{t('insights.stoppedByUser')}

diff --git a/src/renderer/components/InsightsSlashMenu.tsx b/src/renderer/components/InsightsSlashMenu.tsx index 7256fac595..1aada49f15 100644 --- a/src/renderer/components/InsightsSlashMenu.tsx +++ b/src/renderer/components/InsightsSlashMenu.tsx @@ -1,43 +1,93 @@ /** * The composer's `/` menu: Claude Code's slash commands and skills matching what was typed after - * the slash (state and keys: insights-slash-commands.ts). Sits above the composer; the textarea - * keeps focus, so the menu is driven by its keys and picked with the mouse too. + * the slash (state and keys: insights-slash-commands.ts). The textarea keeps focus, so the menu is + * driven by its keys and picked with the mouse too. It is drawn over the page (a portal placed at + * the composer), above the composer when there is room there and below it otherwise, so the chat's + * scrolling column never cuts it off. */ -import { useEffect, useRef } from 'react'; +import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react'; +import { createPortal } from 'react-dom'; import { useTranslation } from 'react-i18next'; import { cn } from '../lib/utils'; -import type { ChatSlashCommand } from '../../shared/types'; +import type { ChatCommandsError, ChatSlashCommand } from '../../shared/types'; + +/** Tallest the menu gets, the least room above the composer it opens in, and its gap to it */ +const MENU_MAX_HEIGHT = 288; +const MENU_MIN_HEIGHT = 120; +const MENU_GAP = 8; interface InsightsSlashMenuProps { + /** The composer the menu is placed at */ + anchorRef: RefObject; items: ChatSlashCommand[]; activeIndex: number; loading: boolean; - error: string | null; + error: ChatCommandsError | null; onSelect: (command: ChatSlashCommand) => void; onHover: (index: number) => void; } -export function InsightsSlashMenu({ items, activeIndex, loading, error, onSelect, onHover }: InsightsSlashMenuProps) { +interface MenuPlace { + left: number; + width: number; + maxHeight: number; + /** Top edge (below the composer) or bottom edge (above it), in viewport pixels */ + top?: number; + bottom?: number; +} + +export function InsightsSlashMenu({ anchorRef, items, activeIndex, loading, error, onSelect, onHover }: InsightsSlashMenuProps) { const { t } = useTranslation('common'); const listRef = useRef(null); + const [place, setPlace] = useState(null); + + // Placed at the composer, and again when it resizes, the window resizes or the page scrolls + useLayoutEffect(() => { + const anchor = anchorRef.current; + if (!anchor) return; + const update = () => { + const rect = anchor.getBoundingClientRect(); + const above = rect.top - MENU_GAP * 2; + const below = window.innerHeight - rect.bottom - MENU_GAP * 2; + const useAbove = above >= MENU_MIN_HEIGHT || above >= below; + setPlace({ + left: rect.left, + width: rect.width, + maxHeight: Math.max(Math.min(MENU_MAX_HEIGHT, useAbove ? above : below), 0), + ...(useAbove ? { bottom: window.innerHeight - rect.top + MENU_GAP } : { top: rect.bottom + MENU_GAP }), + }); + }; + update(); + const observer = new ResizeObserver(update); + observer.observe(anchor); + window.addEventListener('resize', update); + window.addEventListener('scroll', update, true); + return () => { + observer.disconnect(); + window.removeEventListener('resize', update); + window.removeEventListener('scroll', update, true); + }; + }, [anchorRef]); // Keep the active command in view while moving with the arrows useEffect(() => { listRef.current?.querySelector(`[data-index="${activeIndex}"]`)?.scrollIntoView({ block: 'nearest' }); }, [activeIndex]); - return ( + if (!place) return null; + return createPortal(
e.preventDefault()} > {items.length === 0 ? ( -

- {error && !loading ? t('insights.slashCommands.failed', { error }) : t('insights.slashCommands.loading')} +

+ {error && !loading ? t(`insights.slashCommands.errors.${error}`) : t('insights.slashCommands.loading')}

) : ( items.map((command, index) => ( @@ -46,7 +96,10 @@ export function InsightsSlashMenu({ items, activeIndex, loading, error, onSelect role="option" data-index={index} aria-selected={index === activeIndex} - onMouseEnter={() => onHover(index)} + // Moving the pointer picks a row; a row scrolling under a still pointer doesn't + onMouseMove={() => { + if (index !== activeIndex) onHover(index); + }} onClick={() => onSelect(command)} className={cn( 'flex min-w-0 cursor-pointer items-baseline gap-3 rounded-lg px-3 py-1.5 text-sm', @@ -67,6 +120,7 @@ export function InsightsSlashMenu({ items, activeIndex, loading, error, onSelect
)) )} -
+
, + document.body ); } diff --git a/src/renderer/components/__tests__/insights-slash-commands.test.ts b/src/renderer/components/__tests__/insights-slash-commands.test.ts index 454d39a028..2bb558a262 100644 --- a/src/renderer/components/__tests__/insights-slash-commands.test.ts +++ b/src/renderer/components/__tests__/insights-slash-commands.test.ts @@ -33,6 +33,9 @@ describe('filterSlashCommands', () => { describe('insertSlashCommand', () => { it('replaces the token with the command and a space, the caret after it', () => { expect(insertSlashCommand('/gra', { start: 0, query: 'gra' }, 4, 'graphify')).toEqual({ value: '/graphify ', caret: 10 }); - expect(insertSlashCommand('run /gr now', { start: 4, query: 'gr' }, 7, 'graphify')).toEqual({ value: 'run /graphify now', caret: 14 }); + }); + + it('keeps a command picked further in where it was typed', () => { + expect(insertSlashCommand('please use /code-re skill', { start: 11, query: 'code-re' }, 19, 'code-review')).toEqual({ value: 'please use /code-review skill', caret: 24 }); }); }); diff --git a/src/renderer/components/__tests__/insights-slash-menu-keys.test.ts b/src/renderer/components/__tests__/insights-slash-menu-keys.test.ts new file mode 100644 index 0000000000..8d02a2a6c7 --- /dev/null +++ b/src/renderer/components/__tests__/insights-slash-menu-keys.test.ts @@ -0,0 +1,75 @@ +/** + * @vitest-environment jsdom + */ +/** + * The `/` menu's keys: Enter on a command typed out in full sends it, Shift+Tab and keys of an + * input method stay theirs, and a failed list is asked again when the menu opens again. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { KeyboardEvent } from 'react'; +import { useSlashCommandMenu } from '../insights-slash-commands'; + +const listInsightsCommands = vi.fn(); + +beforeEach(() => { + listInsightsCommands.mockReset(); + (window as unknown as { electronAPI: unknown }).electronAPI = { listInsightsCommands }; +}); + +const key = (k: string, extra: { shiftKey?: boolean; isComposing?: boolean } = {}) => ({ + key: k, + shiftKey: extra.shiftKey ?? false, + nativeEvent: { isComposing: extra.isComposing ?? false }, + preventDefault: vi.fn(), +}) as unknown as KeyboardEvent; + +let account = 0; +function render(value: string, onInsert = vi.fn()) { + // Each test its own account, so the cached lists don't carry over + const accountKey = `account-${++account}`; + return renderHook( + (props: { value: string }) => useSlashCommandMenu({ projectId: 'p', accountKey, enabled: true, value: props.value, caret: props.value.length, onInsert }), + { initialProps: { value } } + ); +} + +describe('useSlashCommandMenu keys', () => { + it('lets Enter send a command typed out in full, and picks with Enter on a partial one', async () => { + listInsightsCommands.mockResolvedValue({ success: true, data: [{ name: 'review', description: '' }, { name: 'review-pr', description: '' }] }); + const onInsert = vi.fn(); + const { result, rerender } = render('/review', onInsert); + await waitFor(() => expect(result.current.items).toHaveLength(2)); + expect(result.current.handleKeyDown(key('Enter'))).toBe(false); + + rerender({ value: '/rev' }); + let handled = false; + act(() => { + handled = result.current.handleKeyDown(key('Enter')); + }); + expect(handled).toBe(true); + expect(onInsert).toHaveBeenCalledWith('/review ', 8); + }); + + it('leaves Shift+Tab and an input method\'s keys alone', async () => { + listInsightsCommands.mockResolvedValue({ success: true, data: [{ name: 'design', description: '' }, { name: 'debug', description: '' }] }); + const { result } = render('/de'); + await waitFor(() => expect(result.current.items).toHaveLength(2)); + expect(result.current.handleKeyDown(key('Tab', { shiftKey: true }))).toBe(false); + expect(result.current.handleKeyDown(key('Enter', { isComposing: true }))).toBe(false); + expect(result.current.handleKeyDown(key('ArrowDown', { isComposing: true }))).toBe(false); + }); + + it('shows a failure, then asks again when the menu opens again', async () => { + listInsightsCommands.mockResolvedValueOnce({ success: false, error: 'timeout' }); + const { result, rerender } = render('/'); + await waitFor(() => expect(result.current.error).toBe('timeout')); + expect(result.current.open).toBe(true); + + listInsightsCommands.mockResolvedValueOnce({ success: true, data: [{ name: 'review', description: '' }] }); + rerender({ value: '' }); + rerender({ value: '/' }); + await waitFor(() => expect(result.current.items).toHaveLength(1)); + expect(listInsightsCommands).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/renderer/components/insights-slash-commands.ts b/src/renderer/components/insights-slash-commands.ts index de2e0d5418..0b54911dbc 100644 --- a/src/renderer/components/insights-slash-commands.ts +++ b/src/renderer/components/insights-slash-commands.ts @@ -1,11 +1,16 @@ /** * The chat composer's `/` menu (with the Clawd button on): Claude Code's slash commands and skills * in the project, listed when the caret follows a `/` that starts the input or a word, filtered - * by what was typed after it, as in Claude Code's own prompt. The commands are asked once per - * project (main: insights/chat-commands.ts) and kept for the app's session. + * by what was typed after it, as in Claude Code's own prompt. A picked command takes the token's + * place in the message. + * + * The commands (main: insights/chat-commands.ts) are kept per project and account, since the + * account's config dir holds the user's skills and plugins. They are asked when first needed and + * again each time the Clawd button is switched on (new skills or plugins show up then), keeping + * the list on screen meanwhile; a failed request is retried when the menu opens again. */ -import { useCallback, useEffect, useMemo, useState, type KeyboardEvent } from 'react'; -import type { ChatSlashCommand } from '../../shared/types'; +import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'; +import type { ChatCommandsError, ChatSlashCommand } from '../../shared/types'; /** The `/` token the caret is in: where it starts and what follows the slash */ export interface SlashToken { @@ -34,35 +39,49 @@ export function filterSlashCommands(commands: ChatSlashCommand[], query: string) /** The input with the token replaced by the command (and a space), and the caret after it */ export function insertSlashCommand(value: string, token: SlashToken, caret: number, name: string): { value: string; caret: number } { const inserted = `/${name} `; - const rest = value.slice(caret).replace(/^\S*/, ''); - return { value: value.slice(0, token.start) + inserted + rest.replace(/^ /, ''), caret: token.start + inserted.length }; + const rest = value.slice(caret).replace(/^\S*/, '').replace(/^ /, ''); + return { value: value.slice(0, token.start) + inserted + rest, caret: token.start + inserted.length }; } -type CommandsState = { status: 'loading' } | { status: 'ready'; commands: ChatSlashCommand[] } | { status: 'error'; error: string }; +type CommandsState = + | { status: 'loading'; commands?: ChatSlashCommand[] } + | { status: 'ready'; commands: ChatSlashCommand[] } + | { status: 'error'; error: ChatCommandsError }; -/** Each project's commands, asked once per app session */ -const commandsByProject = new Map(); +/** The commands of each project and account (`projectId`, account key) */ +const commandsByKey = new Map(); const pending = new Map>(); -function loadCommands(projectId: string): Promise { - const existing = pending.get(projectId); +const CHAT_COMMANDS_ERRORS: readonly ChatCommandsError[] = ['projectNotFound', 'timeout', 'notListed', 'failed']; + +function loadCommands(key: string, projectId: string): Promise { + const existing = pending.get(key); if (existing) return existing; const request = window.electronAPI.listInsightsCommands(projectId) - .then((result): CommandsState => result.success && result.data - ? { status: 'ready', commands: result.data } - : { status: 'error', error: result.error ?? '' }) - .catch((error: unknown): CommandsState => ({ status: 'error', error: error instanceof Error ? error.message : String(error) })) + .then((result): CommandsState => { + if (result.success && result.data) return { status: 'ready', commands: result.data }; + const code = CHAT_COMMANDS_ERRORS.find((known) => known === result.error) ?? 'failed'; + return { status: 'error', error: code }; + }) + .catch((): CommandsState => ({ status: 'error', error: 'failed' })) .then((state) => { - commandsByProject.set(projectId, state); - pending.delete(projectId); - return state; + // A failed refresh keeps the list it had + const previous = commandsByKey.get(key); + const next = state.status === 'error' && previous?.status === 'loading' && previous.commands + ? { status: 'ready' as const, commands: previous.commands } + : state; + commandsByKey.set(key, next); + pending.delete(key); + return next; }); - pending.set(projectId, request); + pending.set(key, request); return request; } interface SlashMenuOptions { projectId: string; + /** The account the chat's turns run on (the commands depend on its config dir) */ + accountKey: string; /** The Clawd button is on: the menu works only then */ enabled: boolean; value: string; @@ -72,8 +91,9 @@ interface SlashMenuOptions { } /** The `/` menu's state and keyboard handling for the composer */ -export function useSlashCommandMenu({ projectId, enabled, value, caret, onInsert }: SlashMenuOptions) { - const [commands, setCommands] = useState(() => commandsByProject.get(projectId)); +export function useSlashCommandMenu({ projectId, accountKey, enabled, value, caret, onInsert }: SlashMenuOptions) { + const key = `${projectId}\n${accountKey}`; + const [commands, setCommands] = useState(() => commandsByKey.get(key)); const [activeIndex, setActiveIndex] = useState(0); // The token the user closed the menu on (Escape): it stays closed until another one starts const [dismissedAt, setDismissedAt] = useState(null); @@ -81,23 +101,41 @@ export function useSlashCommandMenu({ projectId, enabled, value, caret, onInsert const token = enabled ? slashTokenAt(value, caret) : null; const open = !!token && token.start !== dismissedAt; - // Asked once the menu is first needed (stored for the app's session afterwards; asked again - // only after a failure) - useEffect(() => { - setCommands(commandsByProject.get(projectId)); - if (!enabled || commandsByProject.get(projectId)?.status === 'ready') return; - let cancelled = false; - void loadCommands(projectId).then((state) => { - if (!cancelled) setCommands(state); + const keyRef = useRef(key); + keyRef.current = key; + + const load = (refresh: boolean) => { + const current = commandsByKey.get(key); + if (!refresh && current && current.status !== 'error') return; + // Loading again keeps the list on screen + const keep = current?.status === 'ready' ? current.commands : current?.status === 'loading' ? current.commands : undefined; + if (!pending.has(key)) commandsByKey.set(key, { status: 'loading', commands: keep }); + setCommands(commandsByKey.get(key)); + void loadCommands(key, projectId).then((state) => { + if (keyRef.current === key) setCommands(state); }); - return () => { - cancelled = true; - }; - }, [projectId, enabled]); + }; + + // Switching the Clawd button on asks again (new skills and plugins show up); another project or + // account shows its own list, asked when it has none + const wasEnabled = useRef(enabled); + useEffect(() => { + const switchedOn = enabled && !wasEnabled.current; + wasEnabled.current = enabled; + setCommands(commandsByKey.get(key)); + if (enabled) load(switchedOn); + // `load` reads the current key, which is a dependency + }, [key, enabled]); + + // A failed list is asked again when the menu opens + useEffect(() => { + if (open && commands?.status === 'error') load(false); + }, [open, token?.start]); + const listed = commands?.status === 'ready' || commands?.status === 'loading' ? commands.commands : undefined; const items = useMemo( - () => (open && commands?.status === 'ready' ? filterSlashCommands(commands.commands, token.query) : []), - [open, commands, token?.query] + () => (open && listed ? filterSlashCommands(listed, token.query) : []), + [open, listed, token?.query] ); // A new query starts at the top @@ -107,15 +145,16 @@ export function useSlashCommandMenu({ projectId, enabled, value, caret, onInsert if (dismissedAt !== null && token?.start !== dismissedAt) setDismissedAt(null); }, [token?.start, dismissedAt]); - const select = useCallback((command: ChatSlashCommand) => { + const select = (command: ChatSlashCommand) => { if (!token) return; const next = insertSlashCommand(value, token, caret, command.name); onInsert(next.value, next.caret); - }, [token, value, caret, onInsert]); + }; /** Keys the open menu takes (arrows, Enter or Tab to pick, Escape to close); true when handled */ const handleKeyDown = (e: KeyboardEvent): boolean => { - if (!open || !token) return false; + // Keys of an input method (IME) composing text are its own + if (!open || !token || e.nativeEvent.isComposing) return false; if (e.key === 'Escape') { e.preventDefault(); setDismissedAt(token.start); @@ -128,22 +167,31 @@ export function useSlashCommandMenu({ projectId, enabled, value, caret, onInsert setActiveIndex((index) => (index + step + items.length) % items.length); return true; } - if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') { + const active = items[Math.min(activeIndex, items.length - 1)]; + // Enter on a command typed out in full sends it, as in Claude Code's prompt + if (e.key === 'Enter' && !e.shiftKey && active.name.toLowerCase() !== token.query.toLowerCase()) { + e.preventDefault(); + select(active); + return true; + } + if (e.key === 'Tab' && !e.shiftKey) { e.preventDefault(); - select(items[Math.min(activeIndex, items.length - 1)]); + select(active); return true; } return false; }; - // Shown while open: the matches, or the list's state while it loads or when it failed - const visible = open && (items.length > 0 || commands === undefined || commands.status !== 'ready'); + const loading = !commands || commands.status === 'loading'; + // Shown while open: the matches, or the list's state while it loads (with nothing to show yet) + // or when it failed + const visible = open && (items.length > 0 || (loading && !listed) || commands?.status === 'error'); return { open: visible, items, activeIndex: Math.min(activeIndex, Math.max(items.length - 1, 0)), setActiveIndex, - loading: !commands || commands.status === 'loading', + loading, error: commands?.status === 'error' ? commands.error : null, select, handleKeyDown, diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index 8525609a04..0f4baf2f82 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -247,7 +247,13 @@ "slashCommands": { "label": "Slash commands and skills", "loading": "Loading commands...", - "failed": "Couldn't list Claude Code's commands: {{error}}" + "noOutput": "The command ran without output", + "errors": { + "projectNotFound": "Couldn't list Claude Code's commands: the project isn't open", + "timeout": "Claude Code didn't list its commands in time. Type / again to retry", + "notListed": "This Claude Code version doesn't list its commands", + "failed": "Couldn't list Claude Code's commands. Type / again to retry" + } }, "cliNotFound": "{{name}} CLI not detected", "kanbanTools": { diff --git a/src/shared/types/insights.ts b/src/shared/types/insights.ts index 4cb4d492a4..979ffa8fac 100644 --- a/src/shared/types/insights.ts +++ b/src/shared/types/insights.ts @@ -45,6 +45,13 @@ export interface ChatSlashCommand { argumentHint?: string; } +/** + * Why the chat's `/` menu couldn't list the commands (the error of `listInsightsCommands`; the + * renderer words each one): the project is gone, Claude Code didn't answer in time, answered + * without a list, or failed to start + */ +export type ChatCommandsError = 'projectNotFound' | 'timeout' | 'notListed' | 'failed'; + type InsightsChatRole = 'user' | 'assistant'; // Tool usage record for showing what tools the AI used From 99c834f0a176de5aa55bc5e18ac86885cbbb7f75 Mon Sep 17 00:00:00 2001 From: Artyom Vancyan Date: Sun, 8 Nov 2026 00:51:41 +0400 Subject: [PATCH 13/74] feat(chat): color slash commands and skills in the composer With the Clawd button on, the commands and skills the `/` menu lists show in the primary color where the message names them (a path or an unlisted word starting with `/` stays plain). A copy of the text behind the field draws them; the field's own text is transparent while it holds one. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 4 +- package.json | 2 +- src/renderer/components/Insights.tsx | 49 +++++++++++++++++-- .../__tests__/insights-slash-commands.test.ts | 22 ++++++++- .../components/insights-slash-commands.ts | 29 +++++++++++ 5 files changed, 99 insertions(+), 7 deletions(-) diff --git a/package-lock.json b/package-lock.json index 29257b9e17..93ac3dc7fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "workbench", - "version": "1.6.12", + "version": "1.6.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "workbench", - "version": "1.6.12", + "version": "1.6.13", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^0.78.0", diff --git a/package.json b/package.json index 5f8dc064e6..3d7821e7b0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workbench", - "version": "1.6.12", + "version": "1.6.13", "author": { "name": "Artyom Vancyan", "email": "44609997+artyomvancyan@users.noreply.github.com" diff --git a/src/renderer/components/Insights.tsx b/src/renderer/components/Insights.tsx index a1085d59ea..58b593ca90 100644 --- a/src/renderer/components/Insights.tsx +++ b/src/renderer/components/Insights.tsx @@ -66,7 +66,7 @@ import { InsightsModelSelector } from './InsightsModelSelector'; import { InsightsMcpMenu } from './InsightsMcpMenu'; import { InsightsSlashMenu } from './InsightsSlashMenu'; import { InsightsAgentWindowButton } from './InsightsAgentWindowButton'; -import { useSlashCommandMenu } from './insights-slash-commands'; +import { splitSlashCommands, useSlashCommandMenu } from './insights-slash-commands'; import { useWindowClaudeAccountId } from '../hooks/useWindowClaudeAccount'; import { useSettingsStore } from '../stores/settings-store'; import { getDefaultMcpConnectorIds } from '../../shared/utils/mcp-connectors'; @@ -419,6 +419,12 @@ export function Insights({ projectId }: InsightsProps) { : hour < 18 ? 'insights.greeting.afternoon' : 'insights.greeting.evening'; + // The composer's text split around the listed slash commands it names (colored with the Clawd + // button on) + const inputParts = useMemo(() => splitSlashCommands(inputValue, slashMenu.names), [inputValue, slashMenu.names]); + const commandHighlight = inputParts.some((part) => part.command); + const highlightRef = useRef(null); + // Auto-grow the composer textarea with its content (capped by max-h-96) useLayoutEffect(() => { const el = textareaRef.current; @@ -427,6 +433,15 @@ export function Insights({ projectId }: InsightsProps) { el.style.height = `${Math.min(el.scrollHeight, 384)}px`; }, [inputValue, isEmpty]); + // The copy behind the field leaves out the field's scrollbar and follows its scroll + useLayoutEffect(() => { + const field = textareaRef.current; + const copy = highlightRef.current; + if (!field || !copy) return; + copy.style.right = `${field.offsetWidth - field.clientWidth}px`; + copy.scrollTop = field.scrollTop; + }); + // The composer moves between the empty-state and conversation layouts; keep focus on it useEffect(() => { if (!isLoading) { @@ -651,6 +666,28 @@ export function Insights({ projectId }: InsightsProps) {
)} + {/* The listed slash commands in the text show in the primary color: the text is drawn by a + copy behind the field (same box, wrapping and scroll), and the field's own text is + transparent while it holds one */} +
+ {commandHighlight && ( + + )}