InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

21-hooks

Shared from "Claude-Code" on Inkdown

React Hooks Architecture

How React connects to all business logic — 70+ hooks organized by domain.


Overview

The hooks/ directory contains ~70 React hooks plus two subdirectories (notifs/ with 16 notification hooks, toolPermission/ with permission orchestration). Hooks follow consistent patterns to bridge React's lifecycle to pure business logic.


Hook Patterns

0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture
1. Effect + Manager Class
TypeScript
function useRemoteSession() {
  useEffect(() => {
    const manager = new RemoteSessionManager()
    manager.onMessage(handleMessage)
    manager.onError(handleError)
    return () => manager.disconnect()
  }, [])
}
2. useSyncExternalStore

For high-frequency external stores:

TypeScript
const queue = useSyncExternalStore(
  messageQueueManager.subscribe,
  () => messageQueueManager.getQueue()
)
3. Ref-Stabilized Closures

Avoid effect re-runs while keeping callbacks fresh:

TypeScript
const isLoadingRef = useRef(isLoading)
isLoadingRef.current = isLoading

useEffect(() => {
  // Uses isLoadingRef.current, not isLoading
}, [])  // Stable deps
4. Feature-Gated Dynamic Imports

Dead-code elimination for external builds:

TypeScript
const replBridge = feature('BRIDGE_MODE')
  ? require('./useReplBridge').useReplBridge
  : null
5. Singleton Stores

Shared state across multiple hook instances:

TypeScript
// Module-level singleton
let store: TasksV2Store | null = null

function useTasksV2() {
  if (!store) store = new TasksV2Store()
  return useSyncExternalStore(store.subscribe, () => store.getState())
}

Core Architecture Hooks

useReplBridge.tsx — Remote Control Bridge

The most complex hook. Manages bidirectional WebSocket bridge between CLI REPL and claude.ai/mobile.

Responsibilities:

  • Init/teardown lifecycle
  • Inbound message injection into REPL
  • Outbound message forwarding to server
  • Permission request/response routing
  • Model/permission mode changes
  • System/init handshake
  • Failure fuse (3-strike circuit breaker)
  • Perpetual session support (assistant mode)
useCanUseTool.tsx — Permission Decision Engine

Every tool call flows through this hook. 4-tier permission flow:

Plain text
Model calls tool
    │
    ▼
1. Config-based auto-allow/deny (settings)
    │
    ▼
2. Coordinator handler (automated checks)
    │
    ▼
3. Swarm worker handler (delegated permissions)
    │
    ▼
4. Interactive user dialog (ask user)

Integrates:

  • Bash classifier (speculative auto-approval)
  • Bridge permission callbacks (remote control)
  • Channel permission callbacks
useInboxPoller.ts — Swarm Communication Backbone

Polls every 1s for unread teammate messages. Classifies 10+ message types:

TypeRouting
Permission requestsToolUseConfirmQueue
Permission responsesBack to requester
Sandbox permissionsWorker sandbox handler
Shutdown requestsShutdown handler
Plan approvalsPlan mode handler
Mode changesMode switcher
Team permission updatesTeam context
Regular messagesXML-wrapped turns

Delivery modes:

  • Idle → immediate submit
  • Busy → queue for later
useSwarmInitialization.ts

Initializes agent swarm features on mount:

  • Handles resumed teammate sessions (--resume//resume)
  • Handles fresh spawns
  • Reads team context from messages or environment
  • Calls initializeTeammateHooks
useManagePlugins.ts — Plugin Lifecycle

On mount:

  1. Load all plugins
  2. Run delisting enforcement
  3. Surface flagged-plugin notifications
  4. Populate AppState.plugins with commands/agents/hooks/MCP/LSP counts

On needsRefresh:

  • Shows notification directing user to /reload-plugins
  • Does NOT auto-refresh (deliberate design)
useQueueProcessor.ts — Command Execution Pipeline

Processes the unified command queue. Fires when:

  1. No query active
  2. No local JSX UI blocking
  3. Queue has items

Priority ordering: 'now' > 'next' > 'later'

All input sources funnel through this queue:

  • User typing
  • Bridge messages
  • Teammate messages
  • Scheduled tasks
  • Task notifications
useScheduledTasks.ts

Mounts a cron scheduler for scheduled/proactive tasks:

  • Fired prompts enqueue at 'later' priority
  • Routes teammate-targeted cron fires to in-process teammates
  • Handles missed-task surfacing
  • Orphaned cron cleanup
  • Workload attribution
useTasksV2.ts

Singleton store for TodoV2 task list UI:

  • Multiple hook instances share one TasksV2Store
  • Auto-hides after 5s when all tasks complete
  • Uses useSyncExternalStore for efficient subscription
useTaskListWatcher.ts

Watches a task list directory via fs.watch for "tasks mode":

  • Automatically claims and submits unowned, unblocked tasks
  • Debounced checks
  • Ref-stabilized props (avoids Bun PathWatcherManager deadlocks)

Remote Session Hooks

All three share the same interface shape (isRemoteMode/sendMessage/cancelRequest/disconnect):

HookTransportUse Case
useRemoteSession.tsWebSocketCCR (Claude Code Runtime)
useDirectConnect.tsWebSocketDirect WebSocket connections
useSSHSession.tsChild processSSH sessions (claude ssh)
useRemoteSession.ts
  • SDK message conversion
  • Echo filtering (BoundedUUIDSet)
  • Permission request/response via ToolUseConfirmQueue
  • Streaming events
  • Subagent lifecycle tracking
  • Compaction-aware timeouts (60s normal, 180s compaction)
  • Session title generation
  • Reconnect on stuck sessions
useSessionBackgrounding.ts

Manages Ctrl+B to background/foreground sessions:

  • Re-backgrounding foregrounded tasks
  • Syncing foregrounded task messages/state to main view
  • Abort controller handoff
useTeleportResume.tsx

Handles resuming a teleported (cloud) code session:

  • Calls teleportResumeCodeSession
  • Sets teleported session info in bootstrap state
  • Emits analytics
  • Manages error state

Input / Text Editing Hooks

useTextInput.ts

Core text input engine for the prompt:

  • Readline-style editing
  • Cursor movement
  • Kill ring (Ctrl+K/U/W)
  • Yank (Ctrl+Y), yank-pop (Meta+Y)
  • Ctrl/meta key mappings
  • Multiline handling
  • SSH-coalesced Enter detection
  • DEL character filtering (SSH/tmux)
  • Ghost text rendering
useVimInput.ts

Full Vim emulation layer wrapping useTextInput:

  • NORMAL/INSERT mode switching
  • Operator-motion grammar
  • Dot-repeat (replayLastChange)
  • Register management
  • Find motions, text objects
  • Count prefixes
useTypeahead.tsx (~1200 lines)

Massive autocomplete engine:

  • Slash command suggestions with argument hints
  • @ file/MCP resource fuzzy search
  • @ agent/teammate DM suggestions
  • # Slack channel suggestions
  • Directory/path completions
  • Bash shell completions
  • Bash history ghost text
  • Common-prefix auto-fill
  • Tab/Enter acceptance
  • Arrow key navigation
  • Inline ghost text
Supporting Input Hooks
HookPurpose
useInputBuffer.tsUndo buffer (debounced push, truncation on new branch)
useArrowKeyHistory.tsxArrow key history navigation
useHistorySearch.tsHistory search (Ctrl+R)
useSearchInput.tsSearch input handling
usePasteHandler.tsPaste event handling
useClipboardImageHint.tsClipboard image paste hint

Keybinding / Interaction Hooks

useCancelRequest.ts

3-tier cancel:

  1. Abort running task
  2. Pop command queue
  3. Clear tool confirm queue

Also implements chat:killAgents with two-press confirmation (3s window).

useDoublePress.ts

Double-press detection utility:

  • Ctrl+C exit
  • Esc clear
  • Ctrl+D exit
useBackgroundTaskNavigation.ts

Shift+Up/Down keyboard navigation for background tasks:

  • Selection cycling (leader ↔ teammates ↔ hide)
  • 'f' to view transcript
  • 'k' to kill
  • Enter to confirm
  • Escape to exit/abort

Voice Hooks

HookPurpose
useVoiceIntegration.tsxHold-to-talk activation, interim/final transcripts, voice prefix/suffix anchoring
useVoice.tsCore voice module (feature-gated)
useVoiceEnabled.tsVoice enabled state (settings + auth + feature flag)

IDE Integration Hooks

HookPurpose
useIDEIntegration.tsxDetects running IDE, auto-connects, sets up dynamic MCP config
useIdeConnectionStatus.tsIDE connection status tracking
useIdeAtMentioned.tsIDE @-mention handling
useIdeSelection.tsIDE code selection integration
useIdeLogging.tsIDE logging integration

State / Settings Hooks

HookPurpose
useSettings.tsReactive settings access, auto-updates on disk changes
useSettingsChange.tsSettings change detection
useDynamicConfig.tsGrowthBook dynamic config values
useMergedClients.tsMerges initial MCP clients with discovered ones
useMergedCommands.tsMerges initial commands with MCP-discovered commands
useMergedTools.tsAssembles full tool pool: built-in + MCP tools

UI / Rendering Hooks

useVirtualScroll.ts

Performance-critical virtualization for message list:

  • Mounts only viewport + overscan items (not all fibers)
  • useSyncExternalStore with scrollTop quantization (40-row bins)
  • Scroll anchoring
  • Lazy height measurement via Yoga
  • Column-resize height scaling
  • Deferred range updates (useDeferredValue)
  • Sliding mount caps (25 items/commit)
  • Runtime clamp bounds (prevents blank screens during fast scroll)
Other UI Hooks
HookPurpose
useTurnDiffs.tsExtracts turn-based file diffs from messages
useDiffData.tsDiff data handling
useDiffInIDE.tsIDE diff integration
useBlink.tsBlinking cursor animation
useElapsedTime.tsElapsed time display
useMemoryUsage.tsMemory usage monitoring
useTerminalSize.tsTerminal size tracking
useMinDisplayTime.tsMinimum display time for UI elements
useRenderPlaceholder.tsRender placeholder handling

Notification Hooks (notifs/)

16 notification-specific hooks:

HookPurpose
useAutoModeUnavailableNotification.tsAuto-mode availability
useCanSwitchToExistingSubscription.tsxSubscription switching
useDeprecationWarningNotification.tsxDeprecation warnings
useFastModeNotification.tsxFast mode
useIDEStatusIndicator.tsxIDE status
useInstallMessages.tsxInstallation messages
useLspInitializationNotification.tsxLSP init
useMcpConnectivityStatus.tsxMCP connectivity
useModelMigrationNotifications.tsxModel migration
useNpmDeprecationNotification.tsxNPM deprecation
usePluginAutoupdateNotification.tsxPlugin autoupdate
usePluginInstallationStatus.tsxPlugin installation
useRateLimitWarningNotification.tsxRate limit warnings
useSettingsErrors.tsxSettings errors
useStartupNotification.tsStartup notifications
useTeammateShutdownNotification.tsTeammate shutdown

Permission Tool Hooks (toolPermission/)

FilePurpose
PermissionContext.tsCreates permission context, queue operations
permissionLogging.tsPermission decision logging
handlers/Permission handler implementations (coordinator, interactive, swarm worker)

Miscellaneous Hooks

HookPurpose
useDeferredHookMessages.tsDeferred SessionStart hook messages (non-blocking)
useCommandQueue.tsSubscribes to unified command queue
useMailboxBridge.tsBridges mailbox polling to message submission
usePromptSuggestion.tsPrompt suggestions
usePrStatus.tsPR status tracking
useCopyOnSelect.tsCopy-on-select behavior
useExitOnCtrlCD.tsCtrl+C exit handling
useFileHistorySnapshotInit.tsFile history snapshot init
useIssueFlagBanner.tsIssue flag banner
useLspPluginRecommendation.tsxLSP plugin recommendations
useNotifyAfterTimeout.tsNotification after timeout
useOfficialMarketplaceNotification.tsxOfficial marketplace
usePluginRecommendationBase.tsxPlugin recommendation base
usePromptsFromClaudeInChrome.tsxChrome extension prompts
useSkillImprovementSurvey.tsSkill improvement survey
useSkillsChange.tsSkills change detection
useSwarmPermissionPoller.tsSwarm permission polling
useTeammateViewAutoExit.tsAuto-exit from teammate view
useTimeout.tsTimeout utility
useUpdateNotification.tsUpdate notification
useAwaySummary.tsAway/absence summary
useChromeExtensionNotification.tsxChrome extension notification
useClaudeCodeHintRecommendation.tsxHint recommendations
useAfterFirstRender.tsExecute logic after first render
useApiKeyVerification.tsAPI key verification

Files

PathPurpose
src/hooks/~70 top-level hook files
src/hooks/notifs/16 notification hooks
src/hooks/toolPermission/Permission orchestration