Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions packages/cli-kit/src/private/node/plugin-hints.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import {emitClaudeCodePluginHint, runningUnderClaudeCode, SHOPIFY_AI_TOOLKIT_PLUGIN_HINT} from './plugin-hints.js'
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest'

describe('runningUnderClaudeCode', () => {
test.each(['1', 'true', 'TRUE', 'yes', 'YES'])('returns true for CLAUDECODE=%s', (value) => {
expect(runningUnderClaudeCode({CLAUDECODE: value})).toBe(true)
})

test('returns true for a Claude Code child session', () => {
expect(runningUnderClaudeCode({CLAUDE_CODE_CHILD_SESSION: '1'})).toBe(true)
})

test.each([
['CLAUDECODE', ''],
['CLAUDECODE', '0'],
['CLAUDECODE', 'false'],
['CLAUDE_CODE_CHILD_SESSION', ''],
['CLAUDE_CODE_CHILD_SESSION', '0'],
['CLAUDE_CODE_CHILD_SESSION', 'false'],
])('returns false for %s=%s when the other marker is absent', (variable, value) => {
expect(runningUnderClaudeCode({[variable]: value})).toBe(false)
})
})

describe('emitClaudeCodePluginHint', () => {
let write: ReturnType<typeof vi.spyOn>
let stdout: ReturnType<typeof vi.spyOn>

beforeEach(() => {
write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true)
})

afterEach(() => {
write.mockRestore()
stdout.mockRestore()
})

test.each([
['CLAUDECODE', '1'],
['CLAUDECODE', 'true'],
['CLAUDE_CODE_CHILD_SESSION', '1'],
['CLAUDE_CODE_CHILD_SESSION', 'true'],
])('writes the marker for %s=%s', (variable, value) => {
emitClaudeCodePluginHint({[variable]: value})

expect(write).toHaveBeenCalledWith(`${SHOPIFY_AI_TOOLKIT_PLUGIN_HINT}\n`)
expect(stdout).not.toHaveBeenCalled()
})

test.each([
['CLAUDECODE', ''],
['CLAUDECODE', '0'],
['CLAUDECODE', 'false'],
['CLAUDE_CODE_CHILD_SESSION', ''],
['CLAUDE_CODE_CHILD_SESSION', '0'],
['CLAUDE_CODE_CHILD_SESSION', 'false'],
])('does not write for %s=%s', (variable, value) => {
emitClaudeCodePluginHint({[variable]: value})

expect(write).not.toHaveBeenCalled()
})

test('writes the exact marker on every command invocation under Claude Code', () => {
emitClaudeCodePluginHint({CLAUDECODE: '1'})
emitClaudeCodePluginHint({CLAUDECODE: '1'})

expect(write).toHaveBeenCalledTimes(2)
expect(write).toHaveBeenNthCalledWith(1, `${SHOPIFY_AI_TOOLKIT_PLUGIN_HINT}\n`)
expect(write).toHaveBeenNthCalledWith(2, `${SHOPIFY_AI_TOOLKIT_PLUGIN_HINT}\n`)
})

test('does not make errors fatal, including diagnostic errors', () => {
write.mockImplementation(() => {
throw new Error('write failed')
})

expect(() => emitClaudeCodePluginHint({CLAUDECODE: '1'})).not.toThrow()
})
})
40 changes: 40 additions & 0 deletions packages/cli-kit/src/private/node/plugin-hints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {getEnvironmentVariables} from '../../public/node/environment.js'
import {isTruthy} from '../../public/node/context/utilities.js'
import {outputDebug} from '../../public/node/output.js'

/** The Claude Code plugin hint protocol marker. */
export const SHOPIFY_AI_TOOLKIT_PLUGIN_HINT =
'<claude-code-hint v="1" type="plugin" value="shopify-ai-toolkit@claude-plugins-official" />'

/**
* Returns whether this process was launched by Claude Code.
*
* @param environment - Environment variables to inspect.
* @returns Whether Claude Code environment markers are truthy.
*/
export function runningUnderClaudeCode(environment = getEnvironmentVariables()): boolean {
return isTruthy(environment.CLAUDECODE) || isTruthy(environment.CLAUDE_CODE_CHILD_SESSION)
}

/**
* Emits the Claude Code plugin hint on every command invocation under Claude Code.
* Claude Code handles deduplication and persistence. A failed optional integration
* must not make the user's command fail.
*
* @param environment - Environment variables to inspect.
*/
export function emitClaudeCodePluginHint(environment = getEnvironmentVariables()): void {
if (!runningUnderClaudeCode(environment)) return

try {
process.stderr.write(`${SHOPIFY_AI_TOOLKIT_PLUGIN_HINT}\n`)
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (error) {
try {
outputDebug(`Unable to emit Claude Code plugin hint: ${(error as Error).message}`)
// eslint-disable-next-line no-catch-all/no-catch-all
} catch {
// Hint emission and its diagnostics are both best effort.
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {SHOPIFY_AI_TOOLKIT_PLUGIN_HINT} from '../../../private/node/plugin-hints.js'
import {afterEach, describe, expect, test, vi} from 'vitest'

vi.mock('../output.js', () => ({outputDebug: vi.fn()}))
vi.mock('../../../private/node/analytics.js', () => ({startAnalytics: vi.fn().mockResolvedValue(undefined)}))
vi.mock('../notifications-system.js', () => ({fetchNotificationsInBackground: vi.fn()}))
vi.mock('../../../common/version.js', () => ({CLI_KIT_VERSION: '1.0.0'}))
vi.mock('../version.js', () => ({isPreReleaseVersion: vi.fn().mockReturnValue(true)}))
vi.mock('../node-package-manager.js', () => ({checkForNewVersion: vi.fn()}))
vi.mock('../../../private/node/plugin-hints.js', () => ({
SHOPIFY_AI_TOOLKIT_PLUGIN_HINT:
'<claude-code-hint v="1" type="plugin" value="shopify-ai-toolkit@claude-plugins-official" />',
emitClaudeCodePluginHint: () => {
if (process.env.CLAUDECODE) process.stderr.write(`${SHOPIFY_AI_TOOLKIT_PLUGIN_HINT}\n`)
},
}))

const options = {
Command: {id: 'app:dev', aliases: [], plugin: {alias: '@shopify/cli'}},
argv: [],
} as any

describe('prerun hook plugin hint integration', () => {
afterEach(() => {
vi.unstubAllEnvs()
})
Comment on lines +24 to +26

test('writes the marker to stderr and completes under Claude Code', async () => {
vi.stubEnv('CLAUDECODE', '1')
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true)
const {hook} = await import('./prerun.js')

await expect((hook as any)(options)).resolves.toBeUndefined()
expect(stderr).toHaveBeenCalledWith(`${SHOPIFY_AI_TOOLKIT_PLUGIN_HINT}\n`)
})

test('completes when the optional emitter module fails to load', async () => {
vi.resetModules()
vi.doMock('../../../private/node/plugin-hints.js', () => Promise.reject(new Error('load failed')))
const {hook} = await import('./prerun.js')

await expect((hook as any)(options)).resolves.toBeUndefined()
})
})
10 changes: 10 additions & 0 deletions packages/cli-kit/src/public/node/hooks/prerun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ export const hook: Hook.Prerun = async (options) => {
})
const args = options.argv

// Emit on every resolved command invocation; --help, --version, and parse errors exit before prerun.
// Claude Code owns deduplication and covers first-party and plugin commands.
try {
const {emitClaudeCodePluginHint} = await import('../../../private/node/plugin-hints.js')
emitClaudeCodePluginHint()
// eslint-disable-next-line no-catch-all/no-catch-all
} catch {
// This optional integration must never make a command fail.
}
Comment on lines +18 to +26

// Load heavy modules in parallel
const [{outputDebug}, analyticsMod, notificationsMod] = await Promise.all([
import('../output.js'),
Expand Down
Loading