Claude-Code 62 files · 4 subfolders
Copy to Workspace 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
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 (() => {
}, [])
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
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 BridgeThe most complex hook. Manages bidirectional WebSocket bridge between CLI REPL and claude.ai/mobile.
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 EngineEvery 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)
Bash classifier (speculative auto-approval)
Bridge permission callbacks (remote control)
Channel permission callbacks
useInboxPoller.ts — Swarm Communication BackbonePolls every 1s for unread teammate messages. Classifies 10+ message types:
Type Routing Permission requests ToolUseConfirmQueue Permission responses Back to requester Sandbox permissions Worker sandbox handler Shutdown requests Shutdown handler Plan approvals Plan mode handler Mode changes Mode switcher Team permission updates Team context Regular messages XML-wrapped turns
Idle → immediate submit
Busy → queue for later
useSwarmInitialization.tsInitializes 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
Load all plugins
Run delisting enforcement
Surface flagged-plugin notifications
Populate AppState.plugins with commands/agents/hooks/MCP/LSP counts
Shows notification directing user to /reload-plugins
Does NOT auto-refresh (deliberate design)
useQueueProcessor.ts — Command Execution PipelineProcesses the unified command queue. Fires when:
No query active
No local JSX UI blocking
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.tsMounts 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.tsSingleton 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.tsWatches 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):
Hook Transport Use Case useRemoteSession.tsWebSocket CCR (Claude Code Runtime) useDirectConnect.tsWebSocket Direct WebSocket connections useSSHSession.tsChild process SSH 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.tsManages Ctrl+B to background/foreground sessions:
Re-backgrounding foregrounded tasks
Syncing foregrounded task messages/state to main view
Abort controller handoff
useTeleportResume.tsxHandles 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.tsCore 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.tsFull 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 Hook Purpose 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
Abort running task
Pop command queue
Clear tool confirm queue
Also implements chat:killAgents with two-press confirmation (3s window).
useDoublePress.tsDouble-press detection utility:
Ctrl+C exit
Esc clear
Ctrl+D exit
useBackgroundTaskNavigation.tsShift+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 Hook Purpose 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 Hook Purpose 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 Hook Purpose 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.tsPerformance-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 Hook Purpose 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:
Hook Purpose 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/) File Purpose PermissionContext.tsCreates permission context, queue operations permissionLogging.tsPermission decision logging handlers/Permission handler implementations (coordinator, interactive, swarm worker)
Miscellaneous Hooks Hook Purpose 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 Path Purpose src/hooks/~70 top-level hook files src/hooks/notifs/16 notification hooks src/hooks/toolPermission/Permission orchestration