diff --git a/src/tui/App.tsx b/src/tui/App.tsx index e6bdb842a..884d72797 100644 --- a/src/tui/App.tsx +++ b/src/tui/App.tsx @@ -1,4 +1,5 @@ import chalk from 'chalk'; +import * as fs from 'fs'; import { Box, Text, @@ -17,8 +18,11 @@ import type { Settings } from '../types/Settings'; import type { WidgetItem } from '../types/Widget'; import { CCSTATUSLINE_COMMANDS, + getActiveClaudeSettingsPath, + getClaudeLocalSettingsPath, getClaudeSettingsPath, getExistingStatusLine, + hasLocalSettings, installStatusLine, isBunxAvailable, isClaudeCodeVersionAtLeast, @@ -47,6 +51,7 @@ import { loadClaudeStatusLineState } from './claude-status'; import { ColorMenu, ConfirmDialog, + FileTargetSelect, GlobalOverridesMenu, InstallMenu, ItemsEditor, @@ -78,6 +83,7 @@ type AppScreen = 'main' | 'confirm' | 'powerline' | 'install' + | 'fileTarget' | 'refreshInterval'; interface ConfirmDialogState { @@ -117,6 +123,13 @@ export const App: React.FC = () => { const [existingStatusLine, setExistingStatusLine] = useState(null); const [flashMessage, setFlashMessage] = useState(null); const [previewIsTruncated, setPreviewIsTruncated] = useState(false); + const [localSettingsDetected, setLocalSettingsDetected] = useState(false); + const [pendingInstall, setPendingInstall] = useState<{ + command: string; + displayName: string; + useBunx: boolean; + targetPath?: string; + } | null>(null); const [currentRefreshInterval, setCurrentRefreshInterval] = useState(null); const [supportsRefreshInterval] = useState(() => isClaudeCodeVersionAtLeast('2.1.97')); @@ -132,6 +145,7 @@ export const App: React.FC = () => { setOriginalSettings(cloneSettings(loadedSettings)); }); void isInstalled().then(setIsClaudeInstalled); + setLocalSettingsDetected(hasLocalSettings()); // Check for Powerline fonts on startup (use sync version that doesn't call execSync) const fontStatus = checkPowerlineFonts(); @@ -188,24 +202,42 @@ export const App: React.FC = () => { } }); - const handleInstallSelection = useCallback((command: string, displayName: string, useBunx: boolean) => { + const handleInstallSelection = useCallback((command: string, displayName: string, useBunx: boolean, targetPath?: string) => { + const effectiveTarget = targetPath ?? getClaudeSettingsPath(); + void getExistingStatusLine().then((existing) => { const isAlreadyInstalled = isKnownCommand(existing ?? ''); let message: string; if (existing && !isAlreadyInstalled) { - message = `This will modify ${getClaudeSettingsPath()}\n\nA status line is already configured: "${existing}"\nReplace it with ${command}?`; + message = `This will modify ${effectiveTarget}\n\nA status line is already configured: "${existing}"\nReplace it with ${command}?`; } else if (isAlreadyInstalled) { - message = `ccstatusline is already installed in ${getClaudeSettingsPath()}\nUpdate it with ${command}?`; + message = `ccstatusline is already installed in ${getActiveClaudeSettingsPath()}\nUpdate it with ${command} in ${effectiveTarget}?`; } else { - message = `This will modify ${getClaudeSettingsPath()} to add ccstatusline with ${displayName}.\nContinue?`; + message = `This will modify ${effectiveTarget} to add ccstatusline with ${displayName}.\nContinue?`; + } + + // Warn if installing to global while local has a statusLine (install won't take effect) + if (targetPath !== getClaudeLocalSettingsPath() && hasLocalSettings()) { + try { + const localContent = fs.readFileSync(getClaudeLocalSettingsPath(), 'utf-8'); + const localData = JSON.parse(localContent) as { statusLine?: { command?: string } }; + if (localData.statusLine?.command) { + message += '\n\n\u26a0 settings.local.json has a statusLine entry that will take precedence over this file. The install may not take effect.'; + } + } catch { + // Can't read local — skip warning + } } setConfirmDialog({ message, cancelScreen: 'install', action: async () => { - await installStatusLine(useBunx, supportsRefreshInterval); + await installStatusLine(useBunx, { + targetPath, + supportsRefreshInterval + }); const installedStatusLineState = await loadClaudeStatusLineState(); setIsClaudeInstalled(true); setExistingStatusLine(installedStatusLineState.existingStatusLine ?? command); @@ -220,13 +252,23 @@ export const App: React.FC = () => { const handleNpxInstall = useCallback(() => { setMenuSelections(prev => ({ ...prev, install: 0 })); - handleInstallSelection(CCSTATUSLINE_COMMANDS.NPM, 'npx', false); - }, [handleInstallSelection]); + if (localSettingsDetected) { + setPendingInstall({ command: CCSTATUSLINE_COMMANDS.NPM, displayName: 'npx', useBunx: false }); + setScreen('fileTarget'); + } else { + handleInstallSelection(CCSTATUSLINE_COMMANDS.NPM, 'npx', false); + } + }, [handleInstallSelection, localSettingsDetected]); const handleBunxInstall = useCallback(() => { setMenuSelections(prev => ({ ...prev, install: 1 })); - handleInstallSelection(CCSTATUSLINE_COMMANDS.BUNX, 'bunx', true); - }, [handleInstallSelection]); + if (localSettingsDetected) { + setPendingInstall({ command: CCSTATUSLINE_COMMANDS.BUNX, displayName: 'bunx', useBunx: true }); + setScreen('fileTarget'); + } else { + handleInstallSelection(CCSTATUSLINE_COMMANDS.BUNX, 'bunx', true); + } + }, [handleInstallSelection, localSettingsDetected]); const handleInstallMenuCancel = useCallback(() => { setMenuSelections(clearInstallMenuSelection); @@ -241,7 +283,7 @@ export const App: React.FC = () => { if (isClaudeInstalled) { // Uninstall setConfirmDialog({ - message: `This will remove ccstatusline from ${getClaudeSettingsPath()}. Continue?`, + message: `This will remove ccstatusline from ${getActiveClaudeSettingsPath()}. Continue?`, action: async () => { await uninstallStatusLine(); setIsClaudeInstalled(false); @@ -507,6 +549,24 @@ export const App: React.FC = () => { onSelectBunx={handleBunxInstall} onCancel={handleInstallMenuCancel} initialSelection={menuSelections.install} + localSettingsDetected={localSettingsDetected} + /> + )} + {screen === 'fileTarget' && pendingInstall && ( + { + handleInstallSelection( + pendingInstall.command, + pendingInstall.displayName, + pendingInstall.useBunx, + targetPath + ); + setPendingInstall(null); + }} + onCancel={() => { + setPendingInstall(null); + setScreen('install'); + }} /> )} {screen === 'refreshInterval' && ( diff --git a/src/tui/components/FileTargetSelect.tsx b/src/tui/components/FileTargetSelect.tsx new file mode 100644 index 000000000..820e9dab0 --- /dev/null +++ b/src/tui/components/FileTargetSelect.tsx @@ -0,0 +1,80 @@ +import * as fs from 'fs'; +import { + Box, + Text, + useInput +} from 'ink'; +import React from 'react'; + +import type { ClaudeSettings } from '../../types/ClaudeSettings'; +import { + getClaudeLocalSettingsPath, + getClaudeSettingsPath +} from '../../utils/claude-settings'; + +import { List } from './List'; + +export interface FileTargetSelectProps { + onSelect: (targetPath: string) => void; + onCancel: () => void; +} + +export const FileTargetSelect: React.FC = ({ + onSelect, + onCancel +}) => { + useInput((_, key) => { + if (key.escape) { + onCancel(); + } + }); + + const globalPath = getClaudeSettingsPath(); + const localPath = getClaudeLocalSettingsPath(); + + // Check if local already has a statusLine — installing to global would be overridden + let localHasStatusLine = false; + try { + const content = fs.readFileSync(localPath, 'utf-8'); + const data = JSON.parse(content) as ClaudeSettings; + localHasStatusLine = !!data.statusLine?.command; + } catch { + // file unreadable — no warning needed + } + + const items = [ + { + label: 'settings.json', + sublabel: localHasStatusLine + ? '(will be overridden by settings.local.json)' + : '(default)', + value: 'global' + }, + { label: 'settings.local.json', sublabel: '(local override)', value: 'local' } + ]; + + return ( + + settings.local.json detected + + Select which file to install to: + + { + if (value === 'back') { + onCancel(); + return; + } + onSelect(value === 'local' ? localPath : globalPath); + }} + showBackButton={true} + /> + + Press Enter to select, ESC to go back + + + ); +}; diff --git a/src/tui/components/InstallMenu.tsx b/src/tui/components/InstallMenu.tsx index 7fdf191eb..6016b2da8 100644 --- a/src/tui/components/InstallMenu.tsx +++ b/src/tui/components/InstallMenu.tsx @@ -16,6 +16,7 @@ export interface InstallMenuProps { onSelectBunx: () => void; onCancel: () => void; initialSelection?: number; + localSettingsDetected?: boolean; } export const InstallMenu: React.FC = ({ @@ -24,7 +25,8 @@ export const InstallMenu: React.FC = ({ onSelectNpx, onSelectBunx, onCancel, - initialSelection = 0 + initialSelection = 0, + localSettingsDetected = false }) => { useInput((_, key) => { if (key.escape) { @@ -97,9 +99,9 @@ export const InstallMenu: React.FC = ({ - The selected command will be written to - {' '} - {getClaudeSettingsPath()} + {localSettingsDetected + ? 'You will be asked which settings file to target next.' + : `The selected command will be written to ${getClaudeSettingsPath()}`} diff --git a/src/tui/components/index.ts b/src/tui/components/index.ts index 3a140aa68..d0ac328ac 100644 --- a/src/tui/components/index.ts +++ b/src/tui/components/index.ts @@ -1,6 +1,7 @@ // Barrel file - exports all components and their types export * from './ColorMenu'; export * from './ConfirmDialog'; +export * from './FileTargetSelect'; export * from './GlobalOverridesMenu'; export * from './InstallMenu'; export * from './ItemsEditor'; diff --git a/src/utils/__tests__/claude-settings.test.ts b/src/utils/__tests__/claude-settings.test.ts index 59efb0f86..15887a155 100644 --- a/src/utils/__tests__/claude-settings.test.ts +++ b/src/utils/__tests__/claude-settings.test.ts @@ -15,11 +15,14 @@ import { import { DEFAULT_SETTINGS } from '../../types/Settings'; import { CCSTATUSLINE_COMMANDS, + getActiveClaudeSettingsPath, getClaudeCodeVersion, getClaudeJsonPath, + getClaudeLocalSettingsPath, getClaudeSettingsPath, getExistingStatusLine, getRefreshInterval, + hasLocalSettings, installStatusLine, isClaudeCodeVersionAtLeast, isInstalled, @@ -54,6 +57,11 @@ function writeRawClaudeSettings(content: string): void { fs.writeFileSync(settingsPath, content, 'utf-8'); } +function writeLocalClaudeSettings(content: string): void { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, content, 'utf-8'); +} + beforeEach(() => { testClaudeConfigDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccstatusline-claude-settings-')); process.env.CLAUDE_CONFIG_DIR = testClaudeConfigDir; @@ -149,6 +157,27 @@ describe('Claude config paths', () => { }); }); +describe('local settings path helpers', () => { + it('getClaudeLocalSettingsPath should return settings.local.json in config dir', () => { + expect(getClaudeLocalSettingsPath()).toBe( + path.join(testClaudeConfigDir, 'settings.local.json') + ); + }); + + it('hasLocalSettings should return false when file does not exist', () => { + expect(hasLocalSettings()).toBe(false); + }); + + it('hasLocalSettings should return true when file exists', () => { + fs.writeFileSync( + path.join(testClaudeConfigDir, 'settings.local.json'), + '{}', + 'utf-8' + ); + expect(hasLocalSettings()).toBe(true); + }); +}); + describe('buildCommand via installStatusLine', () => { it('should use base command when no custom config path', async () => { initConfigPath(); @@ -505,6 +534,240 @@ describe('backup and error handling behavior', () => { }); }); +describe('file-path-aware load/save', () => { + it('loadClaudeSettings should load from specified filePath', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ statusLine: { type: 'command', command: 'local-command', padding: 0 } }), 'utf-8'); + + const settings = await loadClaudeSettings({ filePath: localPath }); + expect(settings.statusLine?.command).toBe('local-command'); + }); + + it('loadClaudeSettings should return empty object when specified filePath does not exist', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + const settings = await loadClaudeSettings({ filePath: localPath }); + expect(settings).toEqual({}); + }); + + it('saveClaudeSettings should save to specified filePath', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + await saveClaudeSettings({ statusLine: { type: 'command', command: 'test-cmd', padding: 0 } }, localPath); + + const content = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { statusLine?: { command?: string } }; + expect(content.statusLine?.command).toBe('test-cmd'); + }); + + it('saveClaudeSettings should create backup for specified filePath', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ existing: true }), 'utf-8'); + + await saveClaudeSettings({ statusLine: { type: 'command', command: 'new-cmd', padding: 0 } }, localPath); + + expect(fs.existsSync(`${localPath}.bak`)).toBe(true); + const backup = JSON.parse(fs.readFileSync(`${localPath}.bak`, 'utf-8')) as { existing?: boolean }; + expect(backup.existing).toBe(true); + }); +}); + +describe('dual-file detection', () => { + it('isInstalled should detect installation in settings.local.json', async () => { + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + await expect(isInstalled()).resolves.toBe(true); + }); + + it('isInstalled should prefer local over global', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'other-command', padding: 0 } })); + // Local has non-ccstatusline command, so isInstalled should be false + await expect(isInstalled()).resolves.toBe(false); + }); + + it('isInstalled should fall back to global when local has no statusLine', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + writeLocalClaudeSettings(JSON.stringify({})); + await expect(isInstalled()).resolves.toBe(true); + }); + + it('getExistingStatusLine should return command from local first', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'global-command' } })); + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'local-command' } })); + await expect(getExistingStatusLine()).resolves.toBe('local-command'); + }); + + it('getExistingStatusLine should fall back to global', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'global-command' } })); + await expect(getExistingStatusLine()).resolves.toBe('global-command'); + }); + + it('getActiveClaudeSettingsPath should return local path when local has statusLine', () => { + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'local-command' } })); + expect(getActiveClaudeSettingsPath()).toBe( + path.join(testClaudeConfigDir, 'settings.local.json') + ); + }); + + it('getActiveClaudeSettingsPath should return global path when local has no statusLine', () => { + writeLocalClaudeSettings(JSON.stringify({})); + expect(getActiveClaudeSettingsPath()).toBe( + path.join(testClaudeConfigDir, 'settings.json') + ); + }); + + it('getActiveClaudeSettingsPath should return global path when no local file', () => { + expect(getActiveClaudeSettingsPath()).toBe( + path.join(testClaudeConfigDir, 'settings.json') + ); + }); + + it('should fall through to global when local file is malformed JSON', async () => { + writeLocalClaudeSettings('{ invalid json'); + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + await expect(isInstalled()).resolves.toBe(true); + await expect(getExistingStatusLine()).resolves.toBe(CCSTATUSLINE_COMMANDS.NPM); + }); + + it('should treat ccstatusline as inactive when local has a different statusLine', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'some-other-tool' } })); + // Local wins — and local is not ccstatusline + await expect(isInstalled()).resolves.toBe(false); + // But getExistingStatusLine returns whatever is effective + await expect(getExistingStatusLine()).resolves.toBe('some-other-tool'); + }); +}); + +describe('file-targeted installStatusLine', () => { + it('should install to settings.local.json when targetPath specified', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + await installStatusLine(false, localPath); + + const content = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { statusLine?: { command?: string } }; + expect(content.statusLine?.command).toBe(CCSTATUSLINE_COMMANDS.NPM); + + // settings.json should not have been created + const globalPath = getClaudeSettingsPath(); + expect(fs.existsSync(globalPath)).toBe(false); + }); + + it('should create .orig backup for targeted file', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ existing: 'data' }), 'utf-8'); + + await installStatusLine(false, localPath); + + expect(fs.existsSync(`${localPath}.orig`)).toBe(true); + const orig = JSON.parse(fs.readFileSync(`${localPath}.orig`, 'utf-8')) as { existing?: string }; + expect(orig.existing).toBe('data'); + }); + + it('should still install to settings.json by default', async () => { + await installStatusLine(false); + expect(readInstalledCommand()).toBe(CCSTATUSLINE_COMMANDS.NPM); + }); + + it('should sync hooks to settings.json when settings.local.json overrides statusLine', async () => { + const configPath = path.join(testClaudeConfigDir, 'ccstatusline-settings.json'); + initConfigPath(configPath); + const settingsWithSkills = { + ...DEFAULT_SETTINGS, + lines: [[{ id: 'skills-1', type: 'skills' }], [], []] + }; + fs.writeFileSync(configPath, JSON.stringify(settingsWithSkills, null, 2), 'utf-8'); + writeLocalClaudeSettings(JSON.stringify({ + statusLine: { + type: 'command', + command: 'user-custom-tool', + padding: 0 + } + })); + + await installStatusLine(false, getClaudeSettingsPath()); + + const globalContent = JSON.parse(fs.readFileSync(getClaudeSettingsPath(), 'utf-8')) as { + hooks?: Record; + statusLine?: { command?: string }; + }; + const installedCommand = `${CCSTATUSLINE_COMMANDS.NPM} --config ${configPath}`; + expect(globalContent.statusLine?.command).toBe(installedCommand); + expect(globalContent.hooks?.PreToolUse?.[0]?.hooks?.[0]?.command).toBe(`${installedCommand} --hook`); + + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + const localContent = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { + hooks?: Record; + statusLine?: { command?: string }; + }; + expect(localContent.statusLine?.command).toBe('user-custom-tool'); + expect(localContent.hooks).toBeUndefined(); + }); +}); + +describe('dual-file uninstallStatusLine', () => { + it('should remove statusLine from settings.local.json', async () => { + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + + await uninstallStatusLine(); + + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + const content = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { statusLine?: unknown }; + expect(content.statusLine).toBeUndefined(); + }); + + it('should remove statusLine from both files when both have it', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.BUNX, padding: 0 } })); + + await uninstallStatusLine(); + + const globalContent = JSON.parse(fs.readFileSync(getClaudeSettingsPath(), 'utf-8')) as { statusLine?: unknown }; + expect(globalContent.statusLine).toBeUndefined(); + + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + const localContent = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { statusLine?: unknown }; + expect(localContent.statusLine).toBeUndefined(); + }); + + it('should not error when local file does not exist', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + + await expect(uninstallStatusLine()).resolves.toBeUndefined(); + + const content = JSON.parse(fs.readFileSync(getClaudeSettingsPath(), 'utf-8')) as { statusLine?: unknown }; + expect(content.statusLine).toBeUndefined(); + }); + + it('should preserve non-ccstatusline statusLine in settings.json', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'company-managed-tool', padding: 0 } })); + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + + await uninstallStatusLine(); + + // Our entry in local should be removed + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + const localContent = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { statusLine?: unknown }; + expect(localContent.statusLine).toBeUndefined(); + + // Company's entry in global should survive + const globalContent = JSON.parse(fs.readFileSync(getClaudeSettingsPath(), 'utf-8')) as { statusLine?: { command?: string } }; + expect(globalContent.statusLine?.command).toBe('company-managed-tool'); + }); + + it('should preserve non-ccstatusline statusLine in settings.local.json', async () => { + writeRawClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: CCSTATUSLINE_COMMANDS.NPM, padding: 0 } })); + writeLocalClaudeSettings(JSON.stringify({ statusLine: { type: 'command', command: 'user-custom-tool' } })); + + await uninstallStatusLine(); + + // Our entry in global should be removed + const globalContent = JSON.parse(fs.readFileSync(getClaudeSettingsPath(), 'utf-8')) as { statusLine?: unknown }; + expect(globalContent.statusLine).toBeUndefined(); + + // User's custom entry in local should survive + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + const localContent = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { statusLine?: { command?: string } }; + expect(localContent.statusLine?.command).toBe('user-custom-tool'); + }); +}); + describe('getClaudeCodeVersion', () => { it('should parse version from claude --version output', () => { vi.spyOn(childProcess, 'execSync').mockReturnValue('2.1.97 (Claude Code)\n'); diff --git a/src/utils/__tests__/hooks.test.ts b/src/utils/__tests__/hooks.test.ts index 59439cc23..9e997771b 100644 --- a/src/utils/__tests__/hooks.test.ts +++ b/src/utils/__tests__/hooks.test.ts @@ -11,6 +11,7 @@ import { } from 'vitest'; import { DEFAULT_SETTINGS } from '../../types/Settings'; +import { CCSTATUSLINE_COMMANDS } from '../claude-settings'; import { syncWidgetHooks } from '../hooks'; const ORIGINAL_CLAUDE_CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR; @@ -76,4 +77,151 @@ describe('syncWidgetHooks', () => { ] }); }); + + it('syncs hooks to settings.local.json when statusLine lives there', async () => { + // Write statusLine to local file, not global + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ + statusLine: { + type: 'command', + command: CCSTATUSLINE_COMMANDS.NPM, + padding: 0 + } + }, null, 2), 'utf-8'); + + const settingsWithSkills = { + ...DEFAULT_SETTINGS, + lines: [[{ id: 'skills-1', type: 'skills' }], [], []] + }; + + await syncWidgetHooks(settingsWithSkills); + + // Hooks should be written to local file, not global + const localSaved = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { hooks?: Record }; + expect(localSaved.hooks?.PreToolUse).toBeDefined(); + + // Global should not have hooks + const globalPath = path.join(testClaudeConfigDir, 'settings.json'); + if (fs.existsSync(globalPath)) { + const globalSaved = JSON.parse(fs.readFileSync(globalPath, 'utf-8')) as { hooks?: Record }; + expect(globalSaved.hooks?.PreToolUse).toBeUndefined(); + } + }); + + it('syncs hooks to an explicit target instead of an overriding local statusLine', async () => { + const globalPath = path.join(testClaudeConfigDir, 'settings.json'); + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(globalPath, JSON.stringify({ + statusLine: { + type: 'command', + command: CCSTATUSLINE_COMMANDS.NPM, + padding: 0 + } + }, null, 2), 'utf-8'); + fs.writeFileSync(localPath, JSON.stringify({ + statusLine: { + type: 'command', + command: 'user-custom-tool', + padding: 0 + } + }, null, 2), 'utf-8'); + + const settingsWithSkills = { + ...DEFAULT_SETTINGS, + lines: [[{ id: 'skills-1', type: 'skills' }], [], []] + }; + + await syncWidgetHooks(settingsWithSkills, { targetPath: globalPath }); + + const globalSaved = JSON.parse(fs.readFileSync(globalPath, 'utf-8')) as { hooks?: Record }; + expect(globalSaved.hooks?.PreToolUse?.[0]?.hooks?.[0]?.command).toBe(`${CCSTATUSLINE_COMMANDS.NPM} --hook`); + + const localSaved = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { hooks?: Record; statusLine?: { command?: string } }; + expect(localSaved.statusLine?.command).toBe('user-custom-tool'); + expect(localSaved.hooks).toBeUndefined(); + }); + + it('does not create hooks for a non-ccstatusline statusLine command', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ + statusLine: { + type: 'command', + command: 'user-custom-tool', + padding: 0 + } + }, null, 2), 'utf-8'); + + const settingsWithSkills = { + ...DEFAULT_SETTINGS, + lines: [[{ id: 'skills-1', type: 'skills' }], [], []] + }; + + await syncWidgetHooks(settingsWithSkills); + + const localSaved = JSON.parse(fs.readFileSync(localPath, 'utf-8')) as { hooks?: Record }; + expect(localSaved.hooks).toBeUndefined(); + }); + + it('subsequent sync does not recreate hooks in old file', async () => { + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ + statusLine: { + type: 'command', + command: CCSTATUSLINE_COMMANDS.NPM, + padding: 0 + } + }, null, 2), 'utf-8'); + + const settingsWithSkills = { + ...DEFAULT_SETTINGS, + lines: [[{ id: 'skills-1', type: 'skills' }], [], []] + }; + + // First sync + await syncWidgetHooks(settingsWithSkills); + // Second sync (simulates saving settings again) + await syncWidgetHooks(settingsWithSkills); + + // Global should still have no managed hooks + const globalPath = path.join(testClaudeConfigDir, 'settings.json'); + if (fs.existsSync(globalPath)) { + const globalSaved = JSON.parse(fs.readFileSync(globalPath, 'utf-8')) as { hooks?: Record }; + const hasManagedHooks = Object.values(globalSaved.hooks ?? {}).some( + (entries: unknown[]) => (entries as { _tag?: string }[]).some(e => e._tag === 'ccstatusline-managed') + ); + expect(hasManagedHooks).toBe(false); + } + }); + + it('cleans stale managed hooks from non-active file', async () => { + // Global file has stale managed hooks + const globalPath = path.join(testClaudeConfigDir, 'settings.json'); + fs.writeFileSync(globalPath, JSON.stringify({ + hooks: { + PreToolUse: [ + { + _tag: 'ccstatusline-managed', + matcher: 'Skill', + hooks: [{ type: 'command', command: 'old-command --hook' }] + } + ] + } + }, null, 2), 'utf-8'); + + // StatusLine is in local file + const localPath = path.join(testClaudeConfigDir, 'settings.local.json'); + fs.writeFileSync(localPath, JSON.stringify({ + statusLine: { + type: 'command', + command: CCSTATUSLINE_COMMANDS.NPM, + padding: 0 + } + }, null, 2), 'utf-8'); + + await syncWidgetHooks(DEFAULT_SETTINGS); + + // Stale hooks should be removed from global + const globalSaved = JSON.parse(fs.readFileSync(globalPath, 'utf-8')) as { hooks?: Record }; + expect(globalSaved.hooks).toBeUndefined(); + }); }); diff --git a/src/utils/claude-settings.ts b/src/utils/claude-settings.ts index 944ae9fe1..b58d02004 100644 --- a/src/utils/claude-settings.ts +++ b/src/utils/claude-settings.ts @@ -113,10 +113,71 @@ export function getClaudeSettingsPath(): string { } /** - * Creates a backup of the current Claude settings file. + * Gets the full path to the Claude settings.local.json file. + * Claude Code merges this file on top of settings.json. */ -async function backupClaudeSettings(suffix = '.bak'): Promise { - const settingsPath = getClaudeSettingsPath(); +export function getClaudeLocalSettingsPath(): string { + return path.join(getClaudeConfigDir(), 'settings.local.json'); +} + +/** + * Checks whether a settings.local.json file exists in the Claude config directory. + */ +export function hasLocalSettings(): boolean { + return fs.existsSync(getClaudeLocalSettingsPath()); +} + +/** + * Private resolver — single source of truth for dual-file statusLine precedence. + * Checks settings.local.json first (matching Claude Code's merge semantics), + * falls back to settings.json. + */ +interface ResolvedStatusLine { + command: string | null; + sourcePath: string; + isLocal: boolean; +} + +function resolveStatusLine(): ResolvedStatusLine { + const localPath = getClaudeLocalSettingsPath(); + if (fs.existsSync(localPath)) { + try { + const content = fs.readFileSync(localPath, 'utf-8'); + const data = JSON.parse(content) as ClaudeSettings; + if (data.statusLine?.command) { + return { command: data.statusLine.command, sourcePath: localPath, isLocal: true }; + } + } catch { + // Malformed local file — fall through to global + } + } + // Check global file + const globalPath = getClaudeSettingsPath(); + if (fs.existsSync(globalPath)) { + try { + const content = fs.readFileSync(globalPath, 'utf-8'); + const data = JSON.parse(content) as ClaudeSettings; + if (data.statusLine?.command) { + return { command: data.statusLine.command, sourcePath: globalPath, isLocal: false }; + } + } catch { + // fall through + } + } + return { command: null, sourcePath: globalPath, isLocal: false }; +} + +/** + * Returns the path to the Claude settings file that currently contains a statusLine entry. + */ +export function getActiveClaudeSettingsPath(): string { + return resolveStatusLine().sourcePath; +} + +/** + * Creates a backup of the given Claude settings file. + */ +async function backupClaudeSettings(settingsPath: string, suffix = '.bak'): Promise { const backupPath = settingsPath + suffix; try { if (fs.existsSync(settingsPath)) { @@ -131,11 +192,30 @@ async function backupClaudeSettings(suffix = '.bak'): Promise { return null; } -interface LoadClaudeSettingsOptions { logErrors?: boolean } +interface LoadClaudeSettingsOptions { logErrors?: boolean; filePath?: string } + +interface InstallStatusLineOptions { + targetPath?: string; + supportsRefreshInterval?: boolean; +} + +function normalizeInstallStatusLineOptions( + options: string | boolean | InstallStatusLineOptions +): InstallStatusLineOptions { + if (typeof options === 'string') { + return { targetPath: options }; + } + + if (typeof options === 'boolean') { + return { supportsRefreshInterval: options }; + } + + return options; +} export function loadClaudeSettingsSync(options: LoadClaudeSettingsOptions = {}): ClaudeSettings { - const { logErrors = true } = options; - const settingsPath = getClaudeSettingsPath(); + const { logErrors = true, filePath } = options; + const settingsPath = filePath ?? getClaudeSettingsPath(); // File doesn't exist - return empty object if (!fs.existsSync(settingsPath)) { @@ -154,8 +234,8 @@ export function loadClaudeSettingsSync(options: LoadClaudeSettingsOptions = {}): } export async function loadClaudeSettings(options: LoadClaudeSettingsOptions = {}): Promise { - const { logErrors = true } = options; - const settingsPath = getClaudeSettingsPath(); + const { logErrors = true, filePath } = options; + const settingsPath = filePath ?? getClaudeSettingsPath(); // File doesn't exist - return empty object if (!fs.existsSync(settingsPath)) { @@ -174,33 +254,37 @@ export async function loadClaudeSettings(options: LoadClaudeSettingsOptions = {} } export async function saveClaudeSettings( - settings: ClaudeSettings + settings: ClaudeSettings, + filePath?: string ): Promise { - const settingsPath = getClaudeSettingsPath(); + const settingsPath = filePath ?? getClaudeSettingsPath(); const dir = path.dirname(settingsPath); // Backup settings before overwriting - await backupClaudeSettings(); + await backupClaudeSettings(settingsPath); await mkdir(dir, { recursive: true }); await writeFile(settingsPath, JSON.stringify(settings, null, 2), 'utf-8'); } export async function isInstalled(): Promise { - let settings: ClaudeSettings; + const resolved = resolveStatusLine(); + if (!resolved.command) { + return false; + } + // Load the full settings from the resolved file to check padding try { - settings = await loadClaudeSettings({ logErrors: false }); + const settings = await loadClaudeSettings({ logErrors: false, filePath: resolved.sourcePath }); + const command = settings.statusLine?.command ?? ''; + return ( + isKnownCommand(command) + && (settings.statusLine?.padding === 0 + || settings.statusLine?.padding === undefined) + ); } catch { - return false; // Can't determine if installed, assume not + return false; } - const command = settings.statusLine?.command ?? ''; - - return ( - isKnownCommand(command) - && (settings.statusLine?.padding === 0 - || settings.statusLine?.padding === undefined) - ); } export function isBunxAvailable(): boolean { @@ -274,14 +358,19 @@ async function loadSavedSettingsForHookSync(): Promise { } } -export async function installStatusLine(useBunx = false, supportsRefreshInterval = false): Promise { - let settings: ClaudeSettings; +export async function installStatusLine( + useBunx = false, + options: string | boolean | InstallStatusLineOptions = {} +): Promise { + const { targetPath, supportsRefreshInterval = false } = normalizeInstallStatusLineOptions(options); + const settingsPath = targetPath ?? getClaudeSettingsPath(); - const backupPath = await backupClaudeSettings('.orig'); + const backupPath = await backupClaudeSettings(settingsPath, '.orig'); + let settings: ClaudeSettings; try { - settings = await loadClaudeSettings({ logErrors: false }); + settings = await loadClaudeSettings({ logErrors: false, filePath: settingsPath }); } catch { - const fallbackBackupPath = `${getClaudeSettingsPath()}.orig`; + const fallbackBackupPath = `${settingsPath}.orig`; console.error(`Warning: Could not read existing Claude settings. A backup exists at ${backupPath ?? fallbackBackupPath}.`); settings = {}; } @@ -303,30 +392,42 @@ export async function installStatusLine(useBunx = false, supportsRefreshInterval settings.statusLine.refreshInterval = existingRefreshInterval ?? 10; } - await saveClaudeSettings(settings); + await saveClaudeSettings(settings, settingsPath); const savedSettings = await loadSavedSettingsForHookSync(); if (savedSettings) { const { syncWidgetHooks } = await import('./hooks'); - await syncWidgetHooks(savedSettings); + await syncWidgetHooks(savedSettings, { targetPath: settingsPath }); } } export async function uninstallStatusLine(): Promise { - let settings: ClaudeSettings; - + // Remove from settings.json — only if it's ours try { - settings = await loadClaudeSettings({ logErrors: false }); + const settings = await loadClaudeSettings({ logErrors: false }); + if (settings.statusLine?.command && isKnownCommand(settings.statusLine.command)) { + delete settings.statusLine; + await saveClaudeSettings(settings); + } } catch { console.error('Warning: Could not read existing Claude settings.'); - return; // if we can't read, return... what are we uninstalling? } - if (settings.statusLine) { - delete settings.statusLine; - await saveClaudeSettings(settings); + // Also remove from settings.local.json — only if it's ours + const localPath = getClaudeLocalSettingsPath(); + if (fs.existsSync(localPath)) { + try { + const localSettings = await loadClaudeSettings({ logErrors: false, filePath: localPath }); + if (localSettings.statusLine?.command && isKnownCommand(localSettings.statusLine.command)) { + delete localSettings.statusLine; + await saveClaudeSettings(localSettings, localPath); + } + } catch { + // Ignore errors with local file during uninstall + } } + // Clean managed hooks from both files (stripManagedHooks already only removes _tag: ccstatusline-managed) try { const { removeManagedHooks } = await import('./hooks'); await removeManagedHooks(); @@ -336,17 +437,17 @@ export async function uninstallStatusLine(): Promise { } export async function getExistingStatusLine(): Promise { - try { - const settings = await loadClaudeSettings({ logErrors: false }); - return settings.statusLine?.command ?? null; - } catch { - return null; // Can't read settings, return null - } + return Promise.resolve(resolveStatusLine().command); } export async function getRefreshInterval(): Promise { + const resolved = resolveStatusLine(); + if (!resolved.command) { + return null; + } + try { - const settings = await loadClaudeSettings({ logErrors: false }); + const settings = await loadClaudeSettings({ logErrors: false, filePath: resolved.sourcePath }); return settings.statusLine?.refreshInterval ?? null; } catch { return null; @@ -354,10 +455,11 @@ export async function getRefreshInterval(): Promise { } export async function setRefreshInterval(interval: number | null): Promise { + const settingsPath = getActiveClaudeSettingsPath(); let settings: ClaudeSettings; try { - settings = await loadClaudeSettings({ logErrors: false }); + settings = await loadClaudeSettings({ logErrors: false, filePath: settingsPath }); } catch { return; } @@ -372,5 +474,5 @@ export async function setRefreshInterval(interval: number | null): Promise settings.statusLine.refreshInterval = interval; } - await saveClaudeSettings(settings); + await saveClaudeSettings(settings, settingsPath); } diff --git a/src/utils/hooks.ts b/src/utils/hooks.ts index b37eb548f..4cc622d84 100644 --- a/src/utils/hooks.ts +++ b/src/utils/hooks.ts @@ -1,8 +1,13 @@ +import * as fs from 'fs'; + import type { Settings } from '../types/Settings'; import type { Widget } from '../types/Widget'; import { - getExistingStatusLine, + getActiveClaudeSettingsPath, + getClaudeLocalSettingsPath, + getClaudeSettingsPath, + isKnownCommand, loadClaudeSettings, saveClaudeSettings } from './claude-settings'; @@ -21,6 +26,8 @@ interface HookEntry { hooks?: { type: string; command: string }[]; } +interface SyncWidgetHooksOptions { targetPath?: string } + function stripManagedHooks(hooks: Record): void { for (const event of Object.keys(hooks)) { hooks[event] = (hooks[event] ?? []).filter(entry => entry._tag !== HOOK_TAG); @@ -52,18 +59,43 @@ function getActiveHookDefs(settings: Settings): WidgetHookDef[] { return defs; } -export async function syncWidgetHooks(settings: Settings): Promise { +export async function syncWidgetHooks( + settings: Settings, + options: SyncWidgetHooksOptions = {} +): Promise { const needed = getActiveHookDefs(settings); - const claudeSettings = await loadClaudeSettings({ logErrors: false }); + const activePath = options.targetPath ?? getActiveClaudeSettingsPath(); + const cleanNonTargetFile = options.targetPath === undefined; + + // Clean stale managed hooks from the non-active file to prevent duplicates + const globalPath = getClaudeSettingsPath(); + const localPath = getClaudeLocalSettingsPath(); + const nonActivePath = activePath === localPath ? globalPath : localPath; + if (cleanNonTargetFile && fs.existsSync(nonActivePath)) { + try { + const otherSettings = await loadClaudeSettings({ logErrors: false, filePath: nonActivePath }); + if (Object.keys(otherSettings).length > 0) { + const otherHooks = (otherSettings.hooks ?? {}) as Record; + if (Object.values(otherHooks).some(entries => entries.some(e => e._tag === HOOK_TAG))) { + stripManagedHooks(otherHooks); + otherSettings.hooks = Object.keys(otherHooks).length > 0 ? otherHooks : undefined; + await saveClaudeSettings(otherSettings, nonActivePath); + } + } + } catch { /* ignore cleanup errors */ } + } + + // Load, strip, and re-add hooks on the active file + const claudeSettings = await loadClaudeSettings({ logErrors: false, filePath: activePath }); const hooks = (claudeSettings.hooks ?? {}) as Record; // Remove all ccstatusline-managed hooks stripManagedHooks(hooks); - const statusCommand = await getExistingStatusLine(); - if (!statusCommand) { + const statusCommand = claudeSettings.statusLine?.command ?? null; + if (!statusCommand || !isKnownCommand(statusCommand)) { claudeSettings.hooks = Object.keys(hooks).length > 0 ? hooks : undefined; - await saveClaudeSettings(claudeSettings); + await saveClaudeSettings(claudeSettings, activePath); return; } const hookCommand = `${statusCommand} --hook`; @@ -82,15 +114,23 @@ export async function syncWidgetHooks(settings: Settings): Promise { } claudeSettings.hooks = Object.keys(hooks).length > 0 ? hooks : undefined; - await saveClaudeSettings(claudeSettings); + await saveClaudeSettings(claudeSettings, activePath); } export async function removeManagedHooks(): Promise { - const claudeSettings = await loadClaudeSettings({ logErrors: false }); - const hooks = (claudeSettings.hooks ?? {}) as Record; - - stripManagedHooks(hooks); - - claudeSettings.hooks = Object.keys(hooks).length > 0 ? hooks : undefined; - await saveClaudeSettings(claudeSettings); + // Clean managed hooks from both settings files + for (const filePath of [getClaudeSettingsPath(), getClaudeLocalSettingsPath()]) { + if (!fs.existsSync(filePath)) { + continue; + } + try { + const claudeSettings = await loadClaudeSettings({ logErrors: false, filePath }); + const hooks = (claudeSettings.hooks ?? {}) as Record; + if (Object.values(hooks).some(entries => entries.some(e => e._tag === HOOK_TAG))) { + stripManagedHooks(hooks); + claudeSettings.hooks = Object.keys(hooks).length > 0 ? hooks : undefined; + await saveClaudeSettings(claudeSettings, filePath); + } + } catch { /* ignore cleanup errors */ } + } }