Files
claude-code/packages/@ant/ink/src/core/hit-test.ts
claude-code-best 09fc515edb feat: 远程群控 (#243)
* feat: restore pipe IPC, LAN pipes, monitor tool, and PR-package features

Core IPC system (UDS_INBOX):
- PipeServer/PipeClient with UDS + TCP dual transport, NDJSON protocol
- PipeRegistry: machineId-based role assignment, file locking
- Master/slave attach, prompt relay, permission forwarding
- Heartbeat lifecycle with parallel isPipeAlive probes
- Commands: /pipes, /attach, /detach, /send, /claim-main, /pipe-status

LAN Pipes (LAN_PIPES):
- UDP multicast beacon (224.0.71.67:7101) for zero-config LAN discovery
- PipeServer TCP listener, PipeClient TCP connect mode
- Heartbeat auto-attaches LAN peers via TCP
- Cross-machine attach allowed regardless of role
- /pipes shows [LAN] peers with role + hostname/IP
- SendMessageTool supports tcp: scheme with user consent

Architecture — extracted hooks from REPL.tsx (~830 lines → ~20 lines):
- usePipeIpc: lifecycle (bootstrap, handlers, heartbeat, cleanup)
- usePipeRelay: slave→master message relay via module singleton
- usePipePermissionForward: permission request/cancel forwarding
- usePipeRouter: selected pipe input routing with role+IP labels
- Shared ndjsonFramer.ts replaces 3 duplicate NDJSON parsers

Key fixes applied during development:
- Multicast binds to correct LAN interface (not WSL/Docker)
- Beacon ref stored as module singleton (not Zustand state mutation)
- Heartbeat preserves LAN peers in discoveredPipes and selectedPipes
- Disconnect handler calls removeSlaveClient (fixes listener leak)
- cleanupStaleEntries probes without lock, writes briefly under lock
- getMachineId uses async execFile (not blocking execSync)
- globalThis.__pipeSendToMaster replaced with setPipeRelay singleton
- M key only toggles route mode when selector panel is expanded
- User prompt displayed in message list on pipe broadcast
- Broadcast notifications show [role] + hostname/IP for LAN peers

Other restored features:
- Monitor tool: /monitor command, MonitorTool, MonitorMcpTask lifecycle
- Daemon supervisor and remoteControlServer command
- Tools: SnipTool, SleepTool, ListPeersTool, SendUserFileTool,
  WebBrowserTool, WorkflowTool, and 10+ stub→implementation rewrites
- Feature flags: UDS_INBOX, LAN_PIPES, MONITOR_TOOL, FORK_SUBAGENT,
  KAIROS, COORDINATOR_MODE, WORKFLOW_SCRIPTS, HISTORY_SNIP

Tests: 2190 pass / 0 fail (15 new: lanBeacon 7, peerAddress 8)

* fix: resolve merge conflicts and fix all tsc/test errors after main merge

- Export ToolResultBlockParam from Tool.ts (14 tool files fixed)
- Migrate ink imports from ../../ink.js to @anthropic/ink (7 files)
- Fix toolUseID → toolUseId typo in monitor.ts and MonitorTool.tsx
- Add fallback values for string|undefined type errors (8 locations)
- Fix AppState type in assistant.ts, add NewInstallWizard stubs
- Fix ParsedRepository.repo → .name in subscribe-pr.ts
- Fix AgentId/string type mismatch in BackgroundTasksDialog.tsx
- Fix PipeRelayFn return type in pipePermissionRelay.ts
- Use PipeMessage type in usePipeRelay.ts
- Fix lanBeacon.test.ts mock type assertions
- Create missing MouseActionEvent class for ink package
- Use ansi: color format instead of bare "green"/"red"
- Resolve theme.permission access via getTheme()

Result: 0 tsc errors, 2496 tests pass, 0 fail

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: 恢复 /poor 的说明

---------

Co-authored-by: unraid <local@unraid.local>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 23:22:55 +08:00

172 lines
5.2 KiB
TypeScript

import type { DOMElement } from './dom.js'
import { ClickEvent } from './events/click-event.js'
import type { EventHandlerProps } from './events/event-handlers.js'
import { MouseActionEvent } from './events/mouse-action-event.js'
import { nodeCache } from './node-cache.js'
/**
* Find the deepest DOM element whose rendered rect contains (col, row).
*
* Uses the nodeCache populated by renderNodeToOutput — rects are in screen
* coordinates with all offsets (including scrollTop translation) already
* applied. Children are traversed in reverse so later siblings (painted on
* top) win. Nodes not in nodeCache (not rendered this frame, or lacking a
* yogaNode) are skipped along with their subtrees.
*
* Returns the hit node even if it has no onClick — dispatchClick walks up
* via parentNode to find handlers.
*/
export function hitTest(
node: DOMElement,
col: number,
row: number,
): DOMElement | null {
const rect = nodeCache.get(node)
if (!rect) return null
if (
col < rect.x ||
col >= rect.x + rect.width ||
row < rect.y ||
row >= rect.y + rect.height
) {
return null
}
// Later siblings paint on top; reversed traversal returns topmost hit.
for (let i = node.childNodes.length - 1; i >= 0; i--) {
const child = node.childNodes[i]!
if (child.nodeName === '#text') continue
const hit = hitTest(child, col, row)
if (hit) return hit
}
return node
}
/**
* Hit-test the root at (col, row) and bubble a ClickEvent from the deepest
* containing node up through parentNode. Only nodes with an onClick handler
* fire. Stops when a handler calls stopImmediatePropagation(). Returns
* true if at least one onClick handler fired.
*/
export function dispatchClick(
root: DOMElement,
col: number,
row: number,
cellIsBlank = false,
): boolean {
let target: DOMElement | undefined = hitTest(root, col, row) ?? undefined
if (!target) return false
// Click-to-focus: find the closest focusable ancestor and focus it.
// root is always ink-root, which owns the FocusManager.
if (root.focusManager) {
let focusTarget: DOMElement | undefined = target
while (focusTarget) {
if (typeof focusTarget.attributes['tabIndex'] === 'number') {
root.focusManager.handleClickFocus(focusTarget)
break
}
focusTarget = focusTarget.parentNode
}
}
const event = new ClickEvent(col, row, cellIsBlank)
let handled = false
while (target) {
const handler = target._eventHandlers?.onClick as
| ((event: ClickEvent) => void)
| undefined
if (handler) {
handled = true
const rect = nodeCache.get(target)
if (rect) {
event.localCol = col - rect.x
event.localRow = row - rect.y
}
handler(event)
if (event.didStopImmediatePropagation()) return true
}
target = target.parentNode
}
return handled
}
/**
* Fire onMouseEnter/onMouseLeave as the pointer moves. Like DOM
* mouseenter/mouseleave: does NOT bubble — moving between children does
* not re-fire on the parent. Walks up from the hit node collecting every
* ancestor with a hover handler; diffs against the previous hovered set;
* fires leave on the nodes exited, enter on the nodes entered.
*
* Mutates `hovered` in place so the caller (App instance) can hold it
* across calls. Clears the set when the hit is null (cursor moved into a
* non-rendered gap or off the root rect).
*/
export function dispatchHover(
root: DOMElement,
col: number,
row: number,
hovered: Set<DOMElement>,
): void {
const next = new Set<DOMElement>()
let node: DOMElement | undefined = hitTest(root, col, row) ?? undefined
while (node) {
const h = node._eventHandlers as EventHandlerProps | undefined
if (h?.onMouseEnter || h?.onMouseLeave) next.add(node)
node = node.parentNode
}
for (const old of hovered) {
if (!next.has(old)) {
hovered.delete(old)
// Skip handlers on detached nodes (removed between mouse events)
if (old.parentNode) {
;(old._eventHandlers as EventHandlerProps | undefined)?.onMouseLeave?.()
}
}
}
for (const n of next) {
if (!hovered.has(n)) {
hovered.add(n)
;(n._eventHandlers as EventHandlerProps | undefined)?.onMouseEnter?.()
}
}
}
export function dispatchMouseAction(
root: DOMElement,
col: number,
row: number,
button: number,
type: 'mousedown' | 'mouseup' | 'mousedrag',
targetOverride?: DOMElement,
): DOMElement | null {
let target: DOMElement | undefined =
targetOverride ?? hitTest(root, col, row) ?? undefined
if (!target) return null
const propName =
type === 'mousedown'
? 'onMouseDown'
: type === 'mouseup'
? 'onMouseUp'
: 'onMouseDrag'
const event = new MouseActionEvent(type, col, row, button)
let handledBy: DOMElement | null = null
while (target) {
const handler = target._eventHandlers?.[propName] as
| ((event: MouseActionEvent) => void)
| undefined
if (handler) {
handledBy ??= target
event.prepareForTarget(target)
handler(event)
if (event.didStopImmediatePropagation()) {
return handledBy
}
}
target = target.parentNode as DOMElement | undefined
}
return handledBy
}