Skip to main content

Overview

The HAI Build Code Generator extension provides various events and hooks that allow you to integrate with and extend its functionality. These events are triggered at different stages of the extension lifecycle and user interactions.

Extension Lifecycle Events

Extension Activation

The extension activates when specific events occur:
onLanguage
ActivationEvent
Triggered when any language file is opened in the editor
onStartupFinished
ActivationEvent
Triggered when VS Code finishes its startup sequence
workspaceContains
ActivationEvent
Triggered when the workspace contains specific files (e.g., evals.env)
Usage:
"activationEvents": [
  "onLanguage",
  "onStartupFinished",
  "workspaceContains:evals.env"
]

Extension Deactivation

When the extension deactivates, cleanup operations are performed:
  • Disposes of non-VS Code-specific services (via tearDown())
  • Disposes of VS Code-specific services (comment controllers, watchers, etc.)
  • Cleans up registered commands and subscriptions
Hook into deactivation:
export async function deactivate() {
  // Your cleanup code here
  await tearDown();
  disposeVscodeCommentReviewController();
}

User Interaction Events

Button Click Events

The extension provides event handlers for sidebar button interactions:
sendChatButtonClickedEvent
() => Promise<void>
Triggered when the new task (+) button is clicked
sendMcpButtonClickedEvent
() => Promise<void>
Triggered when the MCP Servers button is clicked
sendHistoryButtonClickedEvent
() => Promise<void>
Triggered when the History button is clicked
sendSettingsButtonClickedEvent
() => Promise<void>
Triggered when the Settings button is clicked
sendAccountButtonClickedEvent
() => Promise<void>
Triggered when the Account button is clicked
sendWorktreesButtonClickedEvent
() => Promise<void>
Triggered when the Worktrees button is clicked
sendHaiBuildTaskListClickedEvent
() => Promise<void>
Triggered when the HAI Tasks button is clicked
Example:
import { sendChatButtonClickedEvent } from './core/controller/ui/subscribeToChatButtonClicked';

// Trigger the new task event
await sendChatButtonClickedEvent();

Webview Events

sendShowWebviewEvent
(preserveEditorFocus?: boolean) => void
Shows the HAI Build webview sidebarParameters:
  • preserveEditorFocus - When true, shows webview without forcing focus away from editor
sendAddToInputEvent
(content: string) => Promise<void>
Adds content to the chat input fieldParameters:
  • content - The text to add to the input
Example:
import { sendAddToInputEvent } from './core/controller/ui/subscribeToAddToInput';

// Add terminal output to chat
await sendAddToInputEvent(`Terminal output:\n\`\`\`\n${terminalContents}\n\`\`\``);

State Management Events

Secret Storage Events

The extension listens for changes to secure credential storage: Event Handler:
context.secrets.onDidChange(async (event) => {
  if (event.key === 'cline:clineAccountId') {
    const secretValue = await context.secrets.get(event.key);
    if (secretValue) {
      // Login from another window - restore auth
      authService?.restoreRefreshTokenAndRetrieveAuthInfo();
    } else {
      // Logout - handle deauth
      authService?.handleDeauth(LogoutReason.CROSS_WINDOW_SYNC);
    }
  }
});
event.key
string
The key of the secret that changed (e.g., cline:clineAccountId)
Use cases:
  • Cross-window authentication sync
  • Credential updates
  • Logout propagation

Workspace Change Events

The extension tracks workspace folder changes for hook discovery: Event Handler:
vscode.workspace.onDidChangeWorkspaceFolders((callback) => {
  // Re-initialize hook discovery cache
  HookDiscoveryCache.getInstance().refresh();
});

File System Events

Hook Discovery Watcher

The extension watches for changes to hook files: File System Watcher:
const watcher = vscode.workspace.createFileSystemWatcher(
  new vscode.RelativePattern(dir, '*')
);

watcher.onDidCreate((uri) => {
  // Hook file created
});

watcher.onDidChange((uri) => {
  // Hook file modified
});

watcher.onDidDelete((uri) => {
  // Hook file deleted
});
Watched directories:
  • .clinerules/ - Local Cline rules
  • Custom hook directories

URI Handling Events

The extension registers a URI handler for deep linking: Event Handler:
vscode.window.registerUriHandler({
  async handleUri(uri: vscode.Uri) {
    const url = decodeURIComponent(uri.toString());
    const isTaskUri = getUriPath(url) === TASK_URI_PATH;
    
    if (isTaskUri) {
      await openClineSidebarForTaskUri();
    }
    
    const success = await SharedUriHandler.handleUri(url);
    // Handle result
  }
});
uri
vscode.Uri
The deep link URI that was opened (e.g., vscode://presidio-inc.hai-build-code-generator/task?id=123)
Supported URI paths:
  • /task - Open a specific task by ID

Telemetry Events

The extension tracks various user interactions for analytics:

Button Click Tracking

telemetryService.captureButtonClick(
  'command_focusChatInput',
  taskUlid?
);
buttonId
string
Identifier for the button that was clicked
taskUlid
string
ULID of the current task (if applicable)

Slash Command Usage

telemetryService.captureSlashCommandUsed(
  taskUlid,
  commandName,
  commandType
);
taskUlid
string
ULID of the current task
commandName
string
Name of the slash command (e.g., ‘newtask’, ‘smol’, ‘my-workflow’)
commandType
'builtin' | 'mcp_prompt' | 'workflow'
Category of the slash command

Code Action Events

The extension provides code actions that appear in the editor:

Code Action Provider

Supported kinds:
  • vscode.CodeActionKind.QuickFix - Quick fixes for diagnostics
  • vscode.CodeActionKind.RefactorExtract - Extract refactoring (Explain)
  • vscode.CodeActionKind.RefactorRewrite - Rewrite refactoring (Improve)
Triggered when:
  • User right-clicks on code
  • User opens the quick fix menu (Ctrl/Cmd + .)
  • Diagnostics (errors/warnings) are present
Available actions:
Add to Cline
CodeAction
Kind: QuickFixAdds selected code and diagnostics to chat
Explain with Cline
CodeAction
Kind: RefactorExtractRequests an explanation of the selected code
Improve with Cline
CodeAction
Kind: RefactorRewriteRequests AI suggestions to improve the code
Fix with Cline
CodeAction
Kind: QuickFix (preferred)Only appears when diagnostics are present. Attempts to fix errors/warnings.

Comment Thread Events

The extension provides a comment controller for AI code review:

Review Comment Controller

Controller ID: hai-ai-review Available commands:
hai.reviewComment.reply
Command
Replies to a comment threadWhen enabled: commentController == hai-ai-review && !commentIsEmpty
hai.reviewComment.addToChat
Command
Adds the comment thread to HAI Build chatWhen enabled: commentController == hai-ai-review

Development Mode Events

Development mode events are only available when IS_DEV === true

File Watcher for Hot Reload

In development mode, the extension watches for source file changes: Event Handler:
const watcher = vscode.workspace.createFileSystemWatcher(
  new vscode.RelativePattern(DEV_WORKSPACE_FOLDER, 'src/**/*')
);

watcher.onDidChange(({ scheme, path }) => {
  Logger.info(`${scheme} ${path} changed. Reloading VSCode...`);
  vscode.commands.executeCommand('workbench.action.reloadWindow');
});
Watched pattern: src/**/* in the development workspace folder Action: Automatically reloads VS Code window when source files change

Storage Migration Events

The extension performs storage migrations on activation: Migration functions:
cleanupOldApiKey
() => void
Removes legacy API key storage
migrateCustomInstructionsToGlobalRules
(context) => Promise<void>
Migrates custom instructions to global Cline rules (one-time)
migrateWelcomeViewCompleted
(context) => Promise<void>
Migrates welcome view state based on existing API keys (one-time)
migrateWorkspaceToGlobalStorage
(context) => Promise<void>
Migrates workspace storage back to global storage (reverting previous migration)
migrateTaskHistoryToFile
(context) => Promise<void>
Ensures taskHistory.json exists and migrates legacy state (one-time)
cleanupMcpMarketplaceCatalogFromGlobalState
(context) => Promise<void>
Cleans up MCP marketplace catalog from global state (moved to disk cache)

Hook Discovery Events

The extension uses a cache system for performance optimization: Cache initialization:
HookDiscoveryCache.getInstance().initialize(
  context,
  createWatcher,
  onWorkspaceFoldersChanged
);
Events:
  • File creation in hook directories
  • File changes in hook directories
  • File deletion in hook directories
  • Workspace folder changes

Custom Event Integration

To integrate with HAI Build events in your own extension:

Listen to Extension Activation

const haiExtension = vscode.extensions.getExtension(
  'presidio-inc.hai-build-code-generator'
);

if (haiExtension) {
  // Extension is installed
  if (haiExtension.isActive) {
    // Already activated
    const api = haiExtension.exports;
  } else {
    // Wait for activation
    const api = await haiExtension.activate();
  }
}

Trigger HAI Build Commands

// Open HAI Build and add content to chat
await vscode.commands.executeCommand('hai.focusChatInput');
await vscode.commands.executeCommand('hai.addToChat', range, diagnostics);

Access the Controller API

const api = haiExtension.exports;
const controller = api.controller;

// Use controller methods
await controller.clearTask();
await controller.postStateToWebview();

Best Practices

Always verify the HAI Build extension is installed and activated before attempting to use its API:
const extension = vscode.extensions.getExtension('presidio-inc.hai-build-code-generator');
if (!extension) {
  vscode.window.showErrorMessage('HAI Build extension not found');
  return;
}
Extension activation might fail. Always handle errors:
try {
  const api = await extension.activate();
} catch (error) {
  Logger.error('Failed to activate HAI Build:', error);
}
When registering event listeners, always add them to your extension’s subscriptions:
const disposable = vscode.workspace.onDidChangeConfiguration((e) => {
  // Handle config change
});
context.subscriptions.push(disposable);
If you’re integrating with HAI Build’s telemetry, ensure you:
  • Follow privacy guidelines
  • Respect user’s telemetry settings
  • Only track meaningful interactions

See Also

Commands

Complete VS Code commands reference

Slash Commands

In-chat slash commands

Build docs developers (and LLMs) love