Compare commits

..

8 Commits

Author SHA1 Message Date
claude-code-best
2a5b263641 chore: 1.9.4 2026-04-24 10:50:53 +08:00
claude-code-best
f2dd5142b3 refactor: 解耦 BRIDGE_MODE 与 DAEMON,禁用 DAEMON 降低内存占用
- 从 DEFAULT_BUILD_FEATURES 注释掉 DAEMON(内存占用过高)
- remoteControlServer 命令门控从 feature('DAEMON') && feature('BRIDGE_MODE')
  改为仅 feature('BRIDGE_MODE'),bridge 不再依赖 daemon
- --daemon-worker 快速路径改为运行时检测,未启用时输出明确错误提示

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 10:01:05 +08:00
claude-code-best
4dcbaf1e66 fix: 修复 ACP 模式下 messageSelector require 失败导致 submitMessage 崩溃
ACP 模式不加载完整的 React/Ink UI 组件,导致 require('src/components/MessageSelector.js')
返回 undefined。添加 try-catch 和 optional chaining fallback。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 09:59:23 +08:00
claude-code-best
0b304730d8 docs: 为 DEFAULT_BUILD_FEATURES 每个 feature flag 添加功能注释
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 09:26:59 +08:00
claude-code-best
7a0dd3057e chore: 1.9.3 2026-04-23 23:21:43 +08:00
claude-code-best
ca1c87f460 fix: 修复 usePipeIpc 中 require 返回 undefined 导致启动崩溃
将 lazy require() 调用全部替换为静态 import,解决构建产物中
模块加载时序问题导致的 'undefined is not an object' 错误。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 23:21:38 +08:00
claude-code-best
fc7a85f5c7 chore: 1.9.2 2026-04-23 23:04:18 +08:00
claude-code-best
5bc12b00b2 chore: 更新版本流水线 2026-04-23 22:55:27 +08:00
8 changed files with 149 additions and 145 deletions

View File

@@ -4,6 +4,12 @@ on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
version:
description: '版本号 (例如: v1.9.0)'
required: true
type: string
permissions:
contents: write
@@ -15,11 +21,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
ref: ${{ github.event.inputs.version || github.ref }}
- uses: actions/setup-node@v6
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -28,10 +36,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Build
run: bun run build:vite
- name: Type check
run: bun run typecheck
@@ -46,13 +50,11 @@ jobs:
- name: Generate changelog
id: changelog
run: |
PREV_TAG=$(git tag --sort=-version:refname | head -2 | tail -1)
if [ "$PREV_TAG" = "$GITHUB_REF_NAME" ]; then
PREV_TAG=""
fi
VERSION="${{ github.event.inputs.version || github.ref_name }}"
PREV_TAG=$(git tag --sort=-version:refname | grep -v "^${VERSION#v}$" | head -1)
if [ -n "$PREV_TAG" ]; then
COMMITS=$(git log "${PREV_TAG}..HEAD" --pretty=format:"- %s (%h)" --no-merges)
COMMITS=$(git log "${PREV_TAG}..${VERSION}" --pretty=format:"- %s (%h)" --no-merges)
else
COMMITS=$(git log --pretty=format:"- %s (%h)" --no-merges -20)
fi
@@ -66,12 +68,12 @@ jobs:
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
name: ${{ github.ref_name }}
name: ${{ github.event.inputs.version || github.ref_name }}
body: |
## What's Changed
${{ steps.changelog.outputs.commits }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ github.ref_name }}^...${{ github.ref_name }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ github.event.inputs.version || github.ref_name }}^...${{ github.event.inputs.version || github.ref_name }}
draft: false
prerelease: ${{ contains(github.ref_name, 'rc') || contains(github.ref_name, 'beta') || contains(github.ref_name, 'alpha') }}
prerelease: ${{ contains(github.event.inputs.version || github.ref_name, 'rc') || contains(github.event.inputs.version || github.ref_name, 'beta') || contains(github.event.inputs.version || github.ref_name, 'alpha') }}

View File

@@ -1,6 +1,6 @@
{
"name": "claude-code-best",
"version": "1.9.1",
"version": "1.9.4",
"description": "Reverse-engineered Anthropic Claude Code CLI — interactive AI coding assistant in the terminal",
"type": "module",
"author": "claude-code-best <claude-code-best@proton.me>",
@@ -47,11 +47,10 @@
"build:bun": "bun run build.ts",
"dev": "bun run scripts/dev.ts",
"dev:inspect": "bun run scripts/dev-debug.ts",
"prepublishOnly": "bun run build",
"prepublishOnly": "bun run build:vite",
"lint": "biome lint src/",
"lint:fix": "biome lint --fix src/",
"format": "biome format --write src/",
"prepare": "git config core.hooksPath .githooks",
"test": "bun test",
"test:production": "bun run scripts/production-test.ts",
"test:production:offline": "bun run scripts/production-test.ts --offline",

View File

@@ -27,51 +27,49 @@ export function getMacroDefines(): Record<string, string> {
* - scripts/dev.ts (bun run dev)
*/
export const DEFAULT_BUILD_FEATURES = [
'BUDDY', 'TRANSCRIPT_CLASSIFIER', 'BRIDGE_MODE',
'AGENT_TRIGGERS_REMOTE',
'CHICAGO_MCP',
'VOICE_MODE',
'SHOT_STATS',
'PROMPT_CACHE_BREAK_DETECTION',
'TOKEN_BUDGET',
'BUDDY', // 陪伴宠物角色Squirtle Waddles
'TRANSCRIPT_CLASSIFIER', // 对话分类器,用于标注会话类型
'BRIDGE_MODE', // Remote Control / Bridge 模式,远程控制会话
'AGENT_TRIGGERS_REMOTE', // Agent 触发远程会话连接
'CHICAGO_MCP', // Chicago MCP 集成(内部代号)
'VOICE_MODE', // Push-to-Talk 语音输入模式
'SHOT_STATS', // 单次请求统计信息收集
'PROMPT_CACHE_BREAK_DETECTION', // 检测 prompt cache 是否被打破
'TOKEN_BUDGET', // Token 预算管理与控制
// P0: local features
'AGENT_TRIGGERS',
'ULTRATHINK',
'BUILTIN_EXPLORE_PLAN_AGENTS',
'LODESTONE',
// P1: API-dependent features
'EXTRACT_MEMORIES',
'VERIFICATION_AGENT',
'KAIROS_BRIEF',
'AWAY_SUMMARY',
'ULTRAPLAN',
// P2: daemon + remote control server
'DAEMON',
// ACP (Agent Client Protocol) agent mode
'ACP',
// PR-package restored features
'WORKFLOW_SCRIPTS',
'HISTORY_SNIP',
'CONTEXT_COLLAPSE',
'MONITOR_TOOL',
'FORK_SUBAGENT',
'UDS_INBOX',
'KAIROS',
'COORDINATOR_MODE',
'LAN_PIPES',
'BG_SESSIONS',
'TEMPLATES',
// 'REVIEW_ARTIFACT', // API 请求无响应,需进一步排查 schema 兼容性
'AGENT_TRIGGERS', // 本地 Agent 触发器(工具调用时启动子代理)
'ULTRATHINK', // 超深度思考模式,增加推理链长度
'BUILTIN_EXPLORE_PLAN_AGENTS', // 内置 Explore/Plan 子代理类型
'LODESTONE', // 上下文锚点,优化长对话的相关性检索
'EXTRACT_MEMORIES', // 自动从对话中提取并持久化记忆
'VERIFICATION_AGENT', // 验证代理,任务完成后自动校验结果
'KAIROS_BRIEF', // Kairos 定时摘要(定时汇报当前状态)
'AWAY_SUMMARY', // 离线摘要(用户离开后生成总结)
'ULTRAPLAN', // 超级规划模式,深度分析后生成实施计划
// 'DAEMON', // 守护进程模式,长驻 supervisor 管理后台 worker已禁用内存占用过高
'ACP', // ACP 代理协议,支持外部 agent 接入
'WORKFLOW_SCRIPTS', // 工作流脚本(.claude/workflows/ 中的 YAML/MD
'HISTORY_SNIP', // 历史消息裁剪,压缩上下文窗口
'CONTEXT_COLLAPSE', // 上下文折叠,自动压缩旧消息
'MONITOR_TOOL', // Monitor 工具,流式监控后台进程输出
'FORK_SUBAGENT', // Fork 子代理,在隔离上下文中并行执行任务
'UDS_INBOX', // Unix Domain Socket 收件箱,跨会话消息传递
'KAIROS', // Kairos 定时任务系统核心
'COORDINATOR_MODE', // 协调者模式,多代理团队任务调度
'LAN_PIPES', // 局域网管道LAN 设备间通信
'BG_SESSIONS', // 后台会话管理ps/logs/attach/kill
'TEMPLATES', // 模板任务new/list/reply 子命令)
// 'REVIEW_ARTIFACT', // 代码审查产物API 请求无响应,待排查 schema 兼容性)
// API content block types
'CONNECTOR_TEXT',
'CONNECTOR_TEXT', // Connector 文本块类型,扩展 API 内容格式
// Attribution tracking
'COMMIT_ATTRIBUTION',
'COMMIT_ATTRIBUTION', // Git 提交归属追踪(记录 AI 辅助贡献)
// Server mode (claude server / claude open)
'DIRECT_CONNECT',
'DIRECT_CONNECT', // 直连模式claude server / claude open
// Skill search
'EXPERIMENTAL_SKILL_SEARCH',
// P3: poor mode (disable extract_memories + prompt_suggestion)
'POOR',
// Team Memory (shared memory files between agent teammates)
'TEAMMEM',
'EXPERIMENTAL_SKILL_SEARCH', // 实验性技能搜索DiscoverSkills
// P3: poor mode
'POOR', // 穷鬼模式,跳过 extract_memories/prompt_suggestion 减少消耗
// Team Memory
'TEAMMEM', // 团队记忆,代理队友间共享记忆文件
]as const;

View File

@@ -86,9 +86,13 @@ import {
// Lazy: MessageSelector.tsx pulls React/ink; only needed for message filtering at query time
/* eslint-disable @typescript-eslint/no-require-imports */
const messageSelector =
(): typeof import('src/components/MessageSelector.js') =>
require('src/components/MessageSelector.js')
const messageSelector = (): typeof import('src/components/MessageSelector.js') | null => {
try {
return require('src/components/MessageSelector.js')
} catch {
return null
}
}
import {
localCommandOutputToSDKAssistantMessage,
@@ -466,12 +470,13 @@ export class QueryEngine {
}
// Filter messages that should be acknowledged after transcript
const _selector = messageSelector()
const replayableMessages = messagesFromUserInput.filter(
msg =>
(msg.type === 'user' &&
!msg.isMeta && // Skip synthetic caveat messages
!msg.toolUseResult && // Skip tool results (they'll be acked from query)
messageSelector().selectableUserMessagesFilter(msg)) || // Skip non-user-authored messages (task notifications, etc.)
(_selector?.selectableUserMessagesFilter(msg) ?? true)) || // Skip non-user-authored messages (task notifications, etc.)
(msg.type === 'system' && msg.subtype === 'compact_boundary'), // Always ack compact boundaries
)
const messagesToAck = replayUserMessages ? replayableMessages : []
@@ -643,8 +648,10 @@ export class QueryEngine {
}
if (fileHistoryEnabled() && persistSession) {
const _sel = messageSelector()
const _filter = _sel?.selectableUserMessagesFilter ?? ((_msg: unknown) => true)
messagesFromUserInput
.filter(messageSelector().selectableUserMessagesFilter)
.filter(_filter)
.forEach(message => {
void fileHistoryMakeSnapshot(
(updater: (prev: FileHistoryState) => FileHistoryState) => {

View File

@@ -75,7 +75,7 @@ const bridge = feature('BRIDGE_MODE')
? require('./commands/bridge/index.js').default
: null
const remoteControlServerCommand =
feature('DAEMON') && feature('BRIDGE_MODE')
feature('BRIDGE_MODE')
? require('./commands/remoteControlServer/index.js').default
: null
const voiceCommand = feature('VOICE_MODE')

View File

@@ -3,9 +3,14 @@ import { isBridgeEnabled } from '../../bridge/bridgeEnabled.js'
import type { Command } from '../../commands.js'
function isEnabled(): boolean {
if (!feature('DAEMON') || !feature('BRIDGE_MODE')) {
if (!feature('BRIDGE_MODE')) {
return false
}
if (feature('DAEMON')) {
return isBridgeEnabled()
}
// DAEMON feature disabled — still allow the command but warn at runtime
// that headless/daemon worker mode is unavailable.
return isBridgeEnabled()
}

View File

@@ -170,7 +170,12 @@ async function main(): Promise<void> {
// perf-sensitive. No enableConfigs(), no analytics sinks at this layer —
// workers are lean. If a worker kind needs configs/auth (assistant will),
// it calls them inside its run() fn.
if (feature('DAEMON') && (args[0] === '--daemon-worker' || args[0]?.startsWith('--daemon-worker='))) {
if (args[0] === '--daemon-worker' || args[0]?.startsWith('--daemon-worker=')) {
if (!feature('DAEMON')) {
console.error('Error: --daemon-worker requires DAEMON feature to be enabled. Set FEATURE_DAEMON=1 or add DAEMON to DEFAULT_BUILD_FEATURES.')
process.exitCode = 1
return
}
const kind = args[0] === '--daemon-worker' ? args[1] : args[0].split('=')[1]
const { runDaemonWorker } = await import('../daemon/workerRegistry.js')
await runDaemonWorker(kind)

View File

@@ -12,29 +12,19 @@
*/
import { feature } from 'bun:bundle'
import { useEffect } from 'react'
import * as pt from '../utils/pipeTransport.js'
import * as pr from '../utils/pipeRegistry.js'
import * as mm from './useMasterMonitor.js'
import { getSessionId as _getSessionId } from '../bootstrap/state.js'
import * as lb from '../utils/lanBeacon.js'
import * as pp from '../utils/pipePermissionRelay.js'
import * as osm from 'os'
import type {
PipeMessage,
PipeServer,
PipeIpcState,
} from '../utils/pipeTransport.js'
// Lazy-loaded module accessors (cached by Bun/Node require)
/* eslint-disable @typescript-eslint/no-require-imports */
const pt = () =>
require('../utils/pipeTransport.js') as typeof import('../utils/pipeTransport.js')
const pr = () =>
require('../utils/pipeRegistry.js') as typeof import('../utils/pipeRegistry.js')
const mm = () =>
require('./useMasterMonitor.js') as typeof import('./useMasterMonitor.js')
const bs = () =>
require('../bootstrap/state.js') as typeof import('../bootstrap/state.js')
const lb = () =>
require('../utils/lanBeacon.js') as typeof import('../utils/lanBeacon.js')
const pp = () =>
require('../utils/pipePermissionRelay.js') as typeof import('../utils/pipePermissionRelay.js')
const osm = () => require('os') as typeof import('os')
/* eslint-enable @typescript-eslint/no-require-imports */
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
@@ -54,9 +44,9 @@ export type UsePipeIpcOptions = {
// ---------------------------------------------------------------------------
function removeDeadSlave(slaveName: string, store: StoreApi): void {
mm().removeSlaveClient(slaveName)
mm.removeSlaveClient(slaveName)
store.setState((prev: any) => {
const pipeIpc = pt().getPipeIpc(prev)
const pipeIpc = pt.getPipeIpc(prev)
const { [slaveName]: _removed, ...remainingSlaves } = pipeIpc.slaves
return {
...prev,
@@ -108,7 +98,7 @@ function refreshDiscoveredPipes(
// Include LAN beacon peers so they aren't wiped out by heartbeat
let lanDiscovered: typeof freshDiscovered = []
if (feature('LAN_PIPES')) {
const beacon = lb().getLanBeacon()
const beacon = lb.getLanBeacon()
if (beacon) {
const localNames = new Set(freshDiscovered.map(p => p.pipeName))
localNames.add(pipeName)
@@ -131,7 +121,7 @@ function refreshDiscoveredPipes(
const allDiscovered = [...freshDiscovered, ...lanDiscovered]
// Only update state if the list actually changed
const prev = pt().getPipeIpc(store.getState())
const prev = pt.getPipeIpc(store.getState())
const prevNames = (prev.discoveredPipes ?? [])
.map((p: any) => p.pipeName)
.join(',')
@@ -139,7 +129,7 @@ function refreshDiscoveredPipes(
if (prevNames === newNames) return
store.setState((prev: any) => {
const pipeIpc = pt().getPipeIpc(prev)
const pipeIpc = pt.getPipeIpc(prev)
const aliveNames = new Set(allDiscovered.map(pipe => pipe.pipeName))
return {
...prev,
@@ -174,8 +164,8 @@ function registerMessageHandlers(
server.onMessage((msg: PipeMessage, reply) => {
if (msg.type !== 'attach_request') return
const state = store.getState()
const currentPipeState = pt().getPipeIpc(state)
if (pt().isPipeControlled(currentPipeState)) {
const currentPipeState = pt.getPipeIpc(state)
if (pt.isPipeControlled(currentPipeState)) {
reply({ type: 'attach_reject', data: 'Already controlled' })
return
}
@@ -192,7 +182,7 @@ function registerMessageHandlers(
const clients = Array.from((server as any).clients as Set<any>)
const masterSocket = clients[clients.length - 1]
pp().setPipeRelay((relayMsg: any) => {
pp.setPipeRelay((relayMsg: any) => {
if (masterSocket && !masterSocket.destroyed) {
relayMsg.from = relayMsg.from ?? pipeName
relayMsg.ts = relayMsg.ts ?? new Date().toISOString()
@@ -203,9 +193,9 @@ function registerMessageHandlers(
store.setState((prev: any) => ({
...prev,
pipeIpc: {
...pt().getPipeIpc(prev),
...pt.getPipeIpc(prev),
role: 'sub',
displayRole: pt().getPipeDisplayRole(pt().getPipeIpc(prev)),
displayRole: pt.getPipeDisplayRole(pt.getPipeIpc(prev)),
attachedBy: msg.from ?? 'unknown',
},
}))
@@ -230,8 +220,7 @@ function registerMessageHandlers(
server.onMessage((msg: PipeMessage, _reply) => {
if (msg.type !== 'permission_response' && msg.type !== 'permission_cancel')
return
const { resolvePipePermissionResponse, cancelPipePermissionRequest } =
require('../utils/pipePermissionRelay.js') as typeof import('../utils/pipePermissionRelay.js')
const { resolvePipePermissionResponse, cancelPipePermissionRequest } = pp
try {
const payload = msg.data ? JSON.parse(msg.data) : undefined
@@ -249,28 +238,27 @@ function registerMessageHandlers(
// Handle relay mute/unmute from master
server.onMessage((msg: PipeMessage, _reply) => {
if (msg.type === 'relay_mute') {
pp().setRelayMuted(true)
pp.setRelayMuted(true)
} else if (msg.type === 'relay_unmute') {
pp().setRelayMuted(false)
pp.setRelayMuted(false)
}
})
// Handle detach
server.onMessage((msg: PipeMessage, _reply) => {
if (msg.type !== 'detach') return
const { clearPendingPipePermissions } =
require('../utils/pipePermissionRelay.js') as typeof import('../utils/pipePermissionRelay.js')
const { clearPendingPipePermissions } = pp
clearPendingPipePermissions('Pipe detached before permission was resolved.')
pp().setPipeRelay(null)
pp.setPipeRelay(null)
store.setState((prev: any) => ({
...prev,
pipeIpc: (() => {
const pipeIpc = pt().getPipeIpc(prev)
const pipeIpc = pt.getPipeIpc(prev)
const nextRole = pipeIpc.subIndex != null ? 'sub' : 'main'
const nextPipeState = { ...pipeIpc, role: nextRole, attachedBy: null }
return {
...nextPipeState,
displayRole: pt().getPipeDisplayRole(nextPipeState as PipeIpcState),
displayRole: pt.getPipeDisplayRole(nextPipeState as PipeIpcState),
}
})(),
}))
@@ -289,11 +277,11 @@ function runMainHeartbeat(
): void {
void (async () => {
try {
await pr().cleanupStaleEntries()
const aliveSubs = await pr().getAliveSubs()
await pr.cleanupStaleEntries()
const aliveSubs = await pr.getAliveSubs()
refreshDiscoveredPipes(pipeName, aliveSubs, store)
const connectedSlaves = mm().getAllSlaveClients()
const connectedSlaves = mm.getAllSlaveClients()
const aliveSubNames = new Set(aliveSubs.map(sub => sub.pipeName))
// Build unified attach target list: local subs + LAN peers
@@ -307,7 +295,7 @@ function runMainHeartbeat(
// Add LAN peers as attach targets
if (feature('LAN_PIPES')) {
const beacon = lb().getLanBeacon()
const beacon = lb.getLanBeacon()
if (beacon) {
const localNames = new Set(attachTargets.map(t => t.pipeName))
localNames.add(pipeName)
@@ -323,7 +311,7 @@ function runMainHeartbeat(
}
}
const currentPipeState = pt().getPipeIpc(store.getState())
const currentPipeState = pt.getPipeIpc(store.getState())
for (const target of attachTargets) {
if (target.pipeName === pipeName) continue
@@ -331,7 +319,7 @@ function runMainHeartbeat(
try {
const myName = currentPipeState.serverName ?? pipeName
const client = await pt().connectToPipe(
const client = await pt.connectToPipe(
target.pipeName,
myName,
3000,
@@ -362,7 +350,7 @@ function runMainHeartbeat(
})
if (attached && !disposed.current) {
mm().addSlaveClient(target.pipeName, client)
mm.addSlaveClient(target.pipeName, client)
client.on('disconnect', () => {
removeDeadSlave(target.pipeName, store)
@@ -371,11 +359,11 @@ function runMainHeartbeat(
store.setState((prev: any) => ({
...prev,
pipeIpc: {
...pt().getPipeIpc(prev),
...pt.getPipeIpc(prev),
role: 'master',
displayRole: 'master',
slaves: {
...pt().getPipeIpc(prev).slaves,
...pt.getPipeIpc(prev).slaves,
[target.pipeName]: {
name: target.pipeName,
connectedAt: new Date().toISOString(),
@@ -395,7 +383,7 @@ function runMainHeartbeat(
// Clean up slaves that are no longer alive
let lanPeerNames: Set<string> | null = null
if (feature('LAN_PIPES')) {
const beacon = lb().getLanBeacon()
const beacon = lb.getLanBeacon()
if (beacon) {
lanPeerNames = new Set(beacon.getPeers().keys())
}
@@ -422,28 +410,28 @@ function runSubHeartbeat(
): void {
void (async () => {
try {
const mainAlive = await pr().isMainAlive()
const mainAlive = await pr.isMainAlive()
if (!mainAlive && !disposed.current) {
const registry = await pr().readRegistry()
const isSameMachine = pr().isMainMachine(machineId, registry)
const registry = await pr.readRegistry()
const isSameMachine = pr.isMainMachine(machineId, registry)
if (isSameMachine) {
await pr().registerAsMain(entry)
await pr.registerAsMain(entry)
} else {
await pr().revertToIndependent(pipeName)
await pr.revertToIndependent(pipeName)
}
store.setState((prev: any) => ({
...prev,
pipeIpc: {
...pt().getPipeIpc(prev),
...pt.getPipeIpc(prev),
role: 'main',
subIndex: null,
displayRole: 'main',
attachedBy: null,
},
}))
pp().setPipeRelay(null)
pp.setPipeRelay(null)
}
} catch {
// Heartbeat check error — non-fatal
@@ -462,7 +450,9 @@ export function usePipeIpc({
if (!feature('UDS_INBOX')) return
useEffect(() => {
const pipeName = `cli-${bs().getSessionId().slice(0, 8)}`
const sessionId = _getSessionId()
if (!sessionId) return
const pipeName = `cli-${sessionId.slice(0, 8)}`
const disposed = { current: false }
let heartbeatTimer: ReturnType<typeof setInterval> | null = null
let heartbeatBusy = false
@@ -471,11 +461,11 @@ export function usePipeIpc({
void (async () => {
try {
// --- Phase 1: Role determination ---
const machId = await pr().getMachineId()
const mac = pr().getMacAddress()
const localIp = pt().getLocalIp()
const host = osm().hostname()
const roleResult = await pr().determineRole(machId)
const machId = await pr.getMachineId()
const mac = pr.getMacAddress()
const localIp = pt.getLocalIp()
const host = osm.hostname()
const roleResult = await pr.determineRole(machId)
const entry = {
id: pipeName,
@@ -493,29 +483,29 @@ export function usePipeIpc({
let displayRole = 'main'
if (roleResult.role === 'main' || roleResult.role === 'main-recover') {
await pr().registerAsMain(entry)
await pr.registerAsMain(entry)
} else {
subIndex = roleResult.subIndex
await pr().registerAsSub(entry, subIndex)
await pr.registerAsSub(entry, subIndex)
initialRole = 'sub'
displayRole = `sub-${subIndex}`
}
// --- Phase 2: Server creation ---
const server = await pt().createPipeServer(
const server = await pt.createPipeServer(
pipeName,
feature('LAN_PIPES') ? { enableTcp: true, tcpPort: 0 } : undefined,
)
pipeServer = server
if (disposed.current) {
await server.close()
await pr().unregister(pipeName)
await pr.unregister(pipeName)
return
}
// --- Phase 3: LAN beacon ---
if (feature('LAN_PIPES') && server.tcpAddress) {
const beacon = new (lb().LanBeacon)({
const beacon = new (lb.LanBeacon)({
pipeName,
machineId: machId,
hostname: host,
@@ -524,7 +514,7 @@ export function usePipeIpc({
role: initialRole,
})
beacon.start()
lb().setLanBeacon(beacon)
lb.setLanBeacon(beacon)
const entryWithTcp = {
...entry,
@@ -532,9 +522,9 @@ export function usePipeIpc({
lanVisible: true,
}
if (initialRole === 'main') {
await pr().registerAsMain(entryWithTcp)
await pr.registerAsMain(entryWithTcp)
} else if (subIndex != null) {
await pr().registerAsSub(entryWithTcp, subIndex)
await pr.registerAsSub(entryWithTcp, subIndex)
}
}
@@ -542,7 +532,7 @@ export function usePipeIpc({
store.setState((prev: any) => ({
...prev,
pipeIpc: {
...pt().getPipeIpc(prev),
...pt.getPipeIpc(prev),
serverName: pipeName,
role: initialRole,
subIndex,
@@ -570,7 +560,7 @@ export function usePipeIpc({
if (disposed.current || heartbeatBusy) return
heartbeatBusy = true
const currentPipeState = pt().getPipeIpc(store.getState())
const currentPipeState = pt.getPipeIpc(store.getState())
if (
currentPipeState.role === 'main' ||
@@ -600,7 +590,7 @@ export function usePipeIpc({
}
// Send detach to all slaves
const allClients = mm().getAllSlaveClients()
const allClients = mm.getAllSlaveClients()
for (const [name, client] of allClients.entries()) {
try {
client.send({ type: 'detach' })
@@ -610,23 +600,21 @@ export function usePipeIpc({
}
// Stop LAN beacon
const beacon = lb().getLanBeacon()
const beacon = lb.getLanBeacon()
if (beacon) {
try {
beacon.stop()
} catch {}
lb().setLanBeacon(null)
lb.setLanBeacon(null)
}
// Unregister + close server
void pr()
.unregister(pipeName)
.catch(() => {})
pr.unregister(pipeName).catch(() => {})
if (pipeServer) {
void pipeServer.close().catch(() => {})
pipeServer = null
}
pp().setPipeRelay(null)
pp.setPipeRelay(null)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
}