fix: auto-restart Claude sessions when switching profiles
When switching Claude profiles via the UI, existing terminal sessions now automatically restart with the new profile's OAuth token. This fixes the issue where users had to manually restart Claude after switching profiles. Changes: - Profile switch handler now iterates active terminals and restarts Claude sessions that are in Claude mode - Added clear terminal before profile switch to hide temp file command - Fixed OAuth token regex to match 'default' profile ID (not just profile-\d+) - Hide "Authenticate" button when profile is already authenticated - Add re-authenticate button (refresh icon) for authenticated profiles - Added debug logging for profile switching (enabled with DEBUG=true) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.5
parent
ce7c95cae7
commit
cf1ba6b57b
@@ -7,6 +7,7 @@ import { getUsageMonitor } from '../claude-profile/usage-monitor';
|
||||
import { TerminalManager } from '../terminal-manager';
|
||||
import { projectStore } from '../project-store';
|
||||
import { terminalNameGenerator } from '../terminal-name-generator';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
|
||||
|
||||
/**
|
||||
@@ -162,14 +163,126 @@ export function registerTerminalHandlers(
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.CLAUDE_PROFILE_SET_ACTIVE,
|
||||
async (_, profileId: string): Promise<IPCResult> => {
|
||||
// Always-on tracing to verify handler is called
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Handler invoked, profileId:', profileId);
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] DEBUG env:', process.env.DEBUG);
|
||||
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] ========== PROFILE SWITCH START ==========');
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Requested profile ID:', profileId);
|
||||
|
||||
try {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const previousProfile = profileManager.getActiveProfile();
|
||||
const previousProfileId = previousProfile.id;
|
||||
const newProfile = profileManager.getProfile(profileId);
|
||||
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Previous profile:', {
|
||||
id: previousProfile.id,
|
||||
name: previousProfile.name,
|
||||
hasOAuthToken: !!previousProfile.oauthToken,
|
||||
isDefault: previousProfile.isDefault
|
||||
});
|
||||
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] New profile:', newProfile ? {
|
||||
id: newProfile.id,
|
||||
name: newProfile.name,
|
||||
hasOAuthToken: !!newProfile.oauthToken,
|
||||
isDefault: newProfile.isDefault
|
||||
} : 'NOT FOUND');
|
||||
|
||||
const success = profileManager.setActiveProfile(profileId);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] setActiveProfile result:', success);
|
||||
|
||||
if (!success) {
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] setActiveProfile returned false');
|
||||
debugError('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Profile not found, aborting');
|
||||
return { success: false, error: 'Profile not found' };
|
||||
}
|
||||
|
||||
// If the profile actually changed, restart Claude in active terminals
|
||||
// This ensures existing Claude sessions use the new profile's OAuth token
|
||||
const profileChanged = previousProfileId !== profileId;
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Profile changed:', profileChanged,
|
||||
'| Previous:', previousProfileId, '| New:', profileId);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Profile changed:', profileChanged, {
|
||||
previousProfileId,
|
||||
newProfileId: profileId
|
||||
});
|
||||
|
||||
if (profileChanged) {
|
||||
const activeTerminalIds = terminalManager.getActiveTerminalIds();
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Active terminals:', activeTerminalIds.length);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Active terminal IDs:', activeTerminalIds);
|
||||
|
||||
const switchPromises: Promise<void>[] = [];
|
||||
const terminalsInClaudeMode: string[] = [];
|
||||
const terminalsNotInClaudeMode: string[] = [];
|
||||
|
||||
for (const terminalId of activeTerminalIds) {
|
||||
const isClaudeMode = terminalManager.isClaudeMode(terminalId);
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal:', terminalId, '| isClaudeMode:', isClaudeMode);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal check:', {
|
||||
terminalId,
|
||||
isClaudeMode
|
||||
});
|
||||
|
||||
if (isClaudeMode) {
|
||||
terminalsInClaudeMode.push(terminalId);
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Queuing terminal for switch:', terminalId);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Queuing terminal for profile switch:', terminalId);
|
||||
switchPromises.push(
|
||||
terminalManager.switchClaudeProfile(terminalId, profileId)
|
||||
.then(() => {
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Switch SUCCESS:', terminalId);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal profile switch SUCCESS:', terminalId);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Switch FAILED:', terminalId, err);
|
||||
debugError('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal profile switch FAILED:', terminalId, err);
|
||||
})
|
||||
);
|
||||
} else {
|
||||
terminalsNotInClaudeMode.push(terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Summary: total=', activeTerminalIds.length,
|
||||
'| inClaudeMode=', terminalsInClaudeMode.length, '| notInClaudeMode=', terminalsNotInClaudeMode.length);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal summary:', {
|
||||
total: activeTerminalIds.length,
|
||||
inClaudeMode: terminalsInClaudeMode.length,
|
||||
notInClaudeMode: terminalsNotInClaudeMode.length,
|
||||
terminalsToSwitch: terminalsInClaudeMode,
|
||||
terminalsSkipped: terminalsNotInClaudeMode
|
||||
});
|
||||
|
||||
// Wait for all switches to complete (but don't fail the main operation if some fail)
|
||||
if (switchPromises.length > 0) {
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Waiting for', switchPromises.length, 'switches...');
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Waiting for', switchPromises.length, 'terminal switches...');
|
||||
const results = await Promise.allSettled(switchPromises);
|
||||
const fulfilled = results.filter(r => r.status === 'fulfilled').length;
|
||||
const rejected = results.filter(r => r.status === 'rejected').length;
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Results: fulfilled=', fulfilled, '| rejected=', rejected);
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Switch results:', {
|
||||
total: results.length,
|
||||
fulfilled,
|
||||
rejected
|
||||
});
|
||||
} else {
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] No terminals in Claude mode to switch');
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] No terminals in Claude mode to switch');
|
||||
}
|
||||
} else {
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Same profile, no switches needed');
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Same profile selected, no terminal switches needed');
|
||||
}
|
||||
|
||||
console.warn('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] ========== COMPLETE ==========');
|
||||
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] ========== PROFILE SWITCH COMPLETE ==========');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
debugError('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] EXCEPTION:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to set active Claude profile'
|
||||
|
||||
@@ -10,6 +10,7 @@ import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
import * as OutputParser from './output-parser';
|
||||
import * as SessionHandler from './session-handler';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
import type {
|
||||
TerminalProcess,
|
||||
WindowGetter,
|
||||
@@ -92,7 +93,8 @@ export function handleOAuthToken(
|
||||
console.warn('[ClaudeIntegration] OAuth token detected, length:', token.length);
|
||||
|
||||
const email = OutputParser.extractEmail(terminal.outputBuffer);
|
||||
const profileIdMatch = terminal.id.match(/claude-login-(profile-\d+)-/);
|
||||
// Match both custom profiles (profile-123456) and the default profile
|
||||
const profileIdMatch = terminal.id.match(/claude-login-(profile-\d+|default)-/);
|
||||
|
||||
if (profileIdMatch) {
|
||||
const profileId = profileIdMatch[1];
|
||||
@@ -161,6 +163,11 @@ export function invokeClaude(
|
||||
getWindow: WindowGetter,
|
||||
onSessionCapture: (terminalId: string, projectPath: string, startTime: number) => void
|
||||
): void {
|
||||
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE START ==========');
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Terminal ID:', terminal.id);
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Requested profile ID:', profileId);
|
||||
debugLog('[ClaudeIntegration:invokeClaude] CWD:', cwd);
|
||||
|
||||
terminal.isClaudeMode = true;
|
||||
terminal.claudeSessionId = undefined;
|
||||
|
||||
@@ -175,31 +182,60 @@ export function invokeClaude(
|
||||
const previousProfileId = terminal.claudeProfileId;
|
||||
terminal.claudeProfileId = activeProfile?.id;
|
||||
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Profile resolution:', {
|
||||
previousProfileId,
|
||||
newProfileId: activeProfile?.id,
|
||||
profileName: activeProfile?.name,
|
||||
hasOAuthToken: !!activeProfile?.oauthToken,
|
||||
isDefault: activeProfile?.isDefault
|
||||
});
|
||||
|
||||
const cwdCommand = cwd ? `cd "${cwd}" && ` : '';
|
||||
const needsEnvOverride = profileId && profileId !== previousProfileId;
|
||||
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Environment override check:', {
|
||||
profileIdProvided: !!profileId,
|
||||
previousProfileId,
|
||||
needsEnvOverride
|
||||
});
|
||||
|
||||
if (needsEnvOverride && activeProfile && !activeProfile.isDefault) {
|
||||
const token = profileManager.getProfileToken(activeProfile.id);
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Token retrieval:', {
|
||||
hasToken: !!token,
|
||||
tokenLength: token?.length
|
||||
});
|
||||
|
||||
if (token) {
|
||||
const tempFile = path.join(os.tmpdir(), `.claude-token-${Date.now()}`);
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Writing token to temp file:', tempFile);
|
||||
fs.writeFileSync(tempFile, `export CLAUDE_CODE_OAUTH_TOKEN="${token}"\n`, { mode: 0o600 });
|
||||
|
||||
terminal.pty.write(`${cwdCommand}source "${tempFile}" && rm -f "${tempFile}" && claude\r`);
|
||||
console.warn('[ClaudeIntegration] Switching to Claude profile:', activeProfile.name, '(via secure temp file)');
|
||||
// Clear terminal before running command to hide the ugly temp file path
|
||||
const command = `clear && ${cwdCommand}source "${tempFile}" && rm -f "${tempFile}" && claude\r`;
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Executing command (temp file method):', command.replace(token, '[TOKEN_REDACTED]'));
|
||||
terminal.pty.write(command);
|
||||
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE COMPLETE (temp file) ==========');
|
||||
return;
|
||||
} else if (activeProfile.configDir) {
|
||||
terminal.pty.write(`${cwdCommand}CLAUDE_CONFIG_DIR="${activeProfile.configDir}" claude\r`);
|
||||
console.warn('[ClaudeIntegration] Using Claude profile:', activeProfile.name, 'config:', activeProfile.configDir);
|
||||
// Clear terminal before running command
|
||||
const command = `clear && ${cwdCommand}CLAUDE_CONFIG_DIR="${activeProfile.configDir}" claude\r`;
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Executing command (configDir method):', command);
|
||||
terminal.pty.write(command);
|
||||
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE COMPLETE (configDir) ==========');
|
||||
return;
|
||||
} else {
|
||||
debugLog('[ClaudeIntegration:invokeClaude] WARNING: No token or configDir available for non-default profile');
|
||||
}
|
||||
}
|
||||
|
||||
if (activeProfile && !activeProfile.isDefault) {
|
||||
console.warn('[ClaudeIntegration] Using Claude profile:', activeProfile.name, '(from terminal environment)');
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Using terminal environment for non-default profile:', activeProfile.name);
|
||||
}
|
||||
|
||||
terminal.pty.write(`${cwdCommand}claude\r`);
|
||||
const command = `${cwdCommand}claude\r`;
|
||||
debugLog('[ClaudeIntegration:invokeClaude] Executing command (default method):', command);
|
||||
terminal.pty.write(command);
|
||||
|
||||
if (activeProfile) {
|
||||
profileManager.markProfileUsed(activeProfile.id);
|
||||
@@ -220,6 +256,8 @@ export function invokeClaude(
|
||||
if (projectPath) {
|
||||
onSessionCapture(terminal.id, projectPath, startTime);
|
||||
}
|
||||
|
||||
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE COMPLETE (default) ==========');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -258,27 +296,73 @@ export async function switchClaudeProfile(
|
||||
invokeClaudeCallback: (terminalId: string, cwd: string | undefined, profileId: string) => void,
|
||||
clearRateLimitCallback: (terminalId: string) => void
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
// Always-on tracing
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Called for terminal:', terminal.id, '| profileId:', profileId);
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Terminal state: isClaudeMode=', terminal.isClaudeMode);
|
||||
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] ========== SWITCH PROFILE START ==========');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal ID:', terminal.id);
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Target profile ID:', profileId);
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal state:', {
|
||||
isClaudeMode: terminal.isClaudeMode,
|
||||
currentProfileId: terminal.claudeProfileId,
|
||||
claudeSessionId: terminal.claudeSessionId,
|
||||
projectPath: terminal.projectPath,
|
||||
cwd: terminal.cwd
|
||||
});
|
||||
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const profile = profileManager.getProfile(profileId);
|
||||
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Profile found:', profile?.name || 'NOT FOUND');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Target profile:', profile ? {
|
||||
id: profile.id,
|
||||
name: profile.name,
|
||||
hasOAuthToken: !!profile.oauthToken,
|
||||
isDefault: profile.isDefault
|
||||
} : 'NOT FOUND');
|
||||
|
||||
if (!profile) {
|
||||
console.error('[ClaudeIntegration:switchClaudeProfile] Profile not found, aborting');
|
||||
debugError('[ClaudeIntegration:switchClaudeProfile] Profile not found, aborting');
|
||||
return { success: false, error: 'Profile not found' };
|
||||
}
|
||||
|
||||
console.warn('[ClaudeIntegration] Switching to Claude profile:', profile.name);
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Switching to profile:', profile.name);
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Switching to Claude profile:', profile.name);
|
||||
|
||||
if (terminal.isClaudeMode) {
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Sending exit commands (Ctrl+C, /exit)');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal is in Claude mode, sending exit commands');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Sending Ctrl+C (\\x03)');
|
||||
terminal.pty.write('\x03');
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Sending /exit command');
|
||||
terminal.pty.write('/exit\r');
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Exit commands sent');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Exit commands sent, waiting for Claude to exit');
|
||||
} else {
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] NOT in Claude mode, skipping exit commands');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal NOT in Claude mode, skipping exit commands');
|
||||
}
|
||||
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Clearing rate limit state for terminal');
|
||||
clearRateLimitCallback(terminal.id);
|
||||
|
||||
const projectPath = terminal.projectPath || terminal.cwd;
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] Invoking Claude with profile:', profileId, '| cwd:', projectPath);
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Invoking Claude with new profile:', {
|
||||
terminalId: terminal.id,
|
||||
projectPath,
|
||||
profileId
|
||||
});
|
||||
invokeClaudeCallback(terminal.id, projectPath, profileId);
|
||||
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] Setting active profile in profile manager');
|
||||
profileManager.setActiveProfile(profileId);
|
||||
|
||||
console.warn('[ClaudeIntegration:switchClaudeProfile] COMPLETE');
|
||||
debugLog('[ClaudeIntegration:switchClaudeProfile] ========== SWITCH PROFILE COMPLETE ==========');
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -404,8 +404,9 @@ export function IntegrationSettings({ settings, onSettingsChange, isOpen }: Inte
|
||||
</div>
|
||||
{editingProfileId !== profile.id && (
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Authenticate button - show if not authenticated */}
|
||||
{!profile.oauthToken && (
|
||||
{/* Authenticate button - show only if NOT authenticated */}
|
||||
{/* A profile is authenticated if: has OAuth token OR (is default AND has configDir) */}
|
||||
{!(profile.oauthToken || (profile.isDefault && profile.configDir)) ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@@ -420,6 +421,22 @@ export function IntegrationSettings({ settings, onSettingsChange, isOpen }: Inte
|
||||
)}
|
||||
Authenticate
|
||||
</Button>
|
||||
) : (
|
||||
/* Re-authenticate button for already authenticated profiles */
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleAuthenticateProfile(profile.id)}
|
||||
disabled={authenticatingProfileId === profile.id}
|
||||
className="h-7 w-7 text-muted-foreground hover:text-foreground"
|
||||
title="Re-authenticate profile"
|
||||
>
|
||||
{authenticatingProfileId === profile.id ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{profile.id !== activeProfileId && (
|
||||
<Button
|
||||
|
||||
Reference in New Issue
Block a user