Files
claude-code/src/commands/subscribe-pr.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

175 lines
4.9 KiB
TypeScript

import * as fs from 'node:fs'
import * as path from 'node:path'
import type { Command, LocalCommandCall } from '../types/command.js'
import { detectCurrentRepositoryWithHost } from '../utils/detectRepository.js'
import { getClaudeConfigHomeDir } from '../utils/envUtils.js'
/**
* File-backed store for PR webhook subscriptions.
* Each subscription tracks the repo + PR number so the bridge layer
* (useReplBridge / webhookSanitizer) can filter inbound events.
*/
interface PRSubscription {
repo: string // "owner/repo"
prNumber: number
subscribedAt: string // ISO 8601
}
function getSubscriptionsFilePath(): string {
return path.join(getClaudeConfigHomeDir(), 'pr-subscriptions.json')
}
function readSubscriptions(): PRSubscription[] {
const filePath = getSubscriptionsFilePath()
try {
const raw = fs.readFileSync(filePath, 'utf-8')
return JSON.parse(raw) as PRSubscription[]
} catch {
return []
}
}
function writeSubscriptions(subs: PRSubscription[]): void {
const filePath = getSubscriptionsFilePath()
const dir = path.dirname(filePath)
fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(filePath, JSON.stringify(subs, null, 2), 'utf-8')
}
/**
* Parse a PR URL or number into { repo, prNumber }.
*
* Accepts:
* - Full URL: https://github.com/owner/repo/pull/123
* - Short ref: owner/repo#123
* - Bare number: 123 (uses the current git repository)
*/
async function parsePRArg(
arg: string,
): Promise<{ repo: string; prNumber: number } | { error: string }> {
const trimmed = arg.trim()
// Full GitHub PR URL
const urlMatch = trimmed.match(
/^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/(\d+)/,
)
if (urlMatch) {
return { repo: urlMatch[1]!, prNumber: parseInt(urlMatch[2]!, 10) }
}
// Short ref: owner/repo#123
const shortMatch = trimmed.match(/^([^/]+\/[^/]+)#(\d+)$/)
if (shortMatch) {
return { repo: shortMatch[1]!, prNumber: parseInt(shortMatch[2]!, 10) }
}
// Bare number — resolve repo from current git checkout
const numMatch = trimmed.match(/^#?(\d+)$/)
if (numMatch) {
const prNumber = parseInt(numMatch[1]!, 10)
const detected = await detectCurrentRepositoryWithHost()
if (!detected) {
return {
error:
'Could not detect the GitHub repository for the current directory. Provide a full PR URL instead.',
}
}
const repo = `${detected.owner}/${detected.name}`
return { repo, prNumber }
}
return {
error: `Unrecognised PR reference: "${trimmed}". Expected a PR URL, owner/repo#123, or a PR number.`,
}
}
const call: LocalCommandCall = async (args, _context) => {
const trimmed = args.trim()
// List current subscriptions
if (!trimmed || trimmed === '--list' || trimmed === 'list') {
const subs = readSubscriptions()
if (subs.length === 0) {
return {
type: 'text',
value:
'No active PR subscriptions. Usage: /subscribe-pr <pr-url-or-number>',
}
}
const lines = subs.map(
(s) => ` ${s.repo}#${s.prNumber} (since ${s.subscribedAt})`,
)
return {
type: 'text',
value: `Active PR subscriptions:\n${lines.join('\n')}`,
}
}
// Unsubscribe
if (trimmed.startsWith('--remove ') || trimmed.startsWith('remove ')) {
const rest = trimmed.replace(/^(--remove|remove)\s+/, '')
const parsed = await parsePRArg(rest)
if ('error' in parsed) {
return { type: 'text', value: parsed.error }
}
const subs = readSubscriptions()
const before = subs.length
const after = subs.filter(
(s) => !(s.repo === parsed.repo && s.prNumber === parsed.prNumber),
)
if (after.length === before) {
return {
type: 'text',
value: `No subscription found for ${parsed.repo}#${parsed.prNumber}.`,
}
}
writeSubscriptions(after)
return {
type: 'text',
value: `Unsubscribed from ${parsed.repo}#${parsed.prNumber}.`,
}
}
// Subscribe
const parsed = await parsePRArg(trimmed)
if ('error' in parsed) {
return { type: 'text', value: parsed.error }
}
const subs = readSubscriptions()
const existing = subs.find(
(s) => s.repo === parsed.repo && s.prNumber === parsed.prNumber,
)
if (existing) {
return {
type: 'text',
value: `Already subscribed to ${parsed.repo}#${parsed.prNumber} (since ${existing.subscribedAt}).`,
}
}
subs.push({
repo: parsed.repo,
prNumber: parsed.prNumber,
subscribedAt: new Date().toISOString(),
})
writeSubscriptions(subs)
return {
type: 'text',
value: `Subscribed to ${parsed.repo}#${parsed.prNumber}. You will receive notifications for comments, CI status, and reviews.`,
}
}
const subscribePr = {
type: 'local',
name: 'subscribe-pr',
aliases: ['watch-pr'],
description: 'Subscribe to GitHub PR activity (comments, CI, reviews)',
argumentHint: '<pr-url-or-number>',
supportsNonInteractive: false,
isHidden: true,
load: () => Promise.resolve({ call }),
} satisfies Command
export default subscribePr