File size: 12,983 Bytes
064bfd6 9086e0a 064bfd6 9086e0a 064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | import type { AgentColorName } from '../../../tools/AgentTool/agentColorManager.js'
import { logForDebugging } from '../../../utils/debug.js'
import { execFileNoThrow } from '../../../utils/execFileNoThrow.js'
import { IT2_COMMAND, isInITerm2, isIt2CliAvailable } from './detection.js'
import { registerITermBackend } from './registry.js'
import type { CreatePaneResult, PaneBackend, PaneId, PaneSpawnOptions } from './types.js'
// Track session IDs for teammates
const teammateSessionIds: string[] = []
// Track whether the first pane has been used
let firstPaneUsed = false
// Lock mechanism to prevent race conditions when spawning teammates in parallel
let paneCreationLock: Promise<void> = Promise.resolve()
/**
* Acquires a lock for pane creation, ensuring sequential execution.
* Returns a release function that must be called when done.
*/
function acquirePaneCreationLock(): Promise<() => void> {
let release: () => void
const newLock = new Promise<void>(resolve => {
release = resolve
})
const previousLock = paneCreationLock
paneCreationLock = newLock
return previousLock.then(() => release!)
}
/**
* Runs an it2 CLI command and returns the result.
*/
function runIt2(
args: string[],
): Promise<{ stdout: string; stderr: string; code: number }> {
return execFileNoThrow(IT2_COMMAND, args)
}
/**
* Parses the session ID from `it2 session split` output.
* Format: "Created new pane: <session-id>"
*
* NOTE: This UUID is only valid when splitting from a specific session
* using the -s flag. When splitting from the "active" session, the UUID
* may not be accessible if the split happened in a different window.
*/
function parseSplitOutput(output: string): string {
const match = output.match(/Created new pane:\s*(.+)/)
if (match && match[1]) {
return match[1].trim()
}
return ''
}
/**
* Gets the leader's session ID from ITERM_SESSION_ID env var.
* Format: "wXtYpZ:UUID" - we extract the UUID part after the colon.
* Returns null if not in iTerm2 or env var not set.
*/
function getLeaderSessionId(): string | null {
const itermSessionId = process.env.ITERM_SESSION_ID
if (!itermSessionId) {
return null
}
const colonIndex = itermSessionId.indexOf(':')
if (colonIndex === -1) {
return null
}
return itermSessionId.slice(colonIndex + 1)
}
/**
* ITermBackend implements pane management using iTerm2's native split panes
* via the it2 CLI tool.
*/
export class ITermBackend implements PaneBackend {
readonly type = 'iterm2' as const
readonly displayName = 'iTerm2'
readonly supportsHideShow = false
/**
* Checks if iTerm2 backend is available (in iTerm2 with it2 CLI installed).
*/
async isAvailable(): Promise<boolean> {
const inITerm2 = isInITerm2()
logForDebugging(`[ITermBackend] isAvailable check: inITerm2=${inITerm2}`)
if (!inITerm2) {
logForDebugging('[ITermBackend] isAvailable: false (not in iTerm2)')
return false
}
const it2Available = await isIt2CliAvailable()
logForDebugging(
`[ITermBackend] isAvailable: ${it2Available} (it2 CLI ${it2Available ? 'found' : 'not found'})`,
)
return it2Available
}
/**
* Checks if we're currently running inside iTerm2.
*/
async isRunningInside(): Promise<boolean> {
const result = isInITerm2()
logForDebugging(`[ITermBackend] isRunningInside: ${result}`)
return result
}
/**
* Creates a new teammate pane in the swarm view.
* Uses a lock to prevent race conditions when multiple teammates are spawned in parallel.
*/
async createTeammatePaneInSwarmView(
name: string,
color: AgentColorName,
_spawnOptions?: PaneSpawnOptions,
): Promise<CreatePaneResult> {
logForDebugging(
`[ITermBackend] createTeammatePaneInSwarmView called for ${name} with color ${color}`,
)
const releaseLock = await acquirePaneCreationLock()
try {
// Layout: Leader on left, teammates stacked vertically on the right
// - First teammate: vertical split (-v) from leader's session
// - Subsequent teammates: horizontal split from last teammate's session
//
// We explicitly target the session to split from using -s flag to ensure
// correct layout even if user clicks on different panes.
//
// At-fault recovery: If a targeted teammate session is dead (user closed
// the pane via Cmd+W / X, or process crashed), prune it and retry with
// the next-to-last. Cheaper than a proactive 'it2 session list' on every spawn.
// Bounded at O(N+1) iterations: each continue shrinks teammateSessionIds by 1;
// when empty → firstPaneUsed resets → next iteration has no target → throws.
// eslint-disable-next-line no-constant-condition
while (true) {
const isFirstTeammate = !firstPaneUsed
logForDebugging(
`[ITermBackend] Creating pane: isFirstTeammate=${isFirstTeammate}, existingPanes=${teammateSessionIds.length}`,
)
let splitArgs: string[]
let targetedTeammateId: string | undefined
if (isFirstTeammate) {
// Split from leader's session (extracted from ITERM_SESSION_ID env var)
const leaderSessionId = getLeaderSessionId()
if (leaderSessionId) {
splitArgs = ['session', 'split', '-v', '-s', leaderSessionId]
logForDebugging(
`[ITermBackend] First split from leader session: ${leaderSessionId}`,
)
} else {
// Fallback to active session if we can't get leader's ID
splitArgs = ['session', 'split', '-v']
logForDebugging(
'[ITermBackend] First split from active session (no leader ID)',
)
}
} else {
// Split from the last teammate's session to stack vertically
targetedTeammateId = teammateSessionIds[teammateSessionIds.length - 1]
if (targetedTeammateId) {
splitArgs = ['session', 'split', '-s', targetedTeammateId]
logForDebugging(
`[ITermBackend] Subsequent split from teammate session: ${targetedTeammateId}`,
)
} else {
// Fallback to active session
splitArgs = ['session', 'split']
logForDebugging(
'[ITermBackend] Subsequent split from active session (no teammate ID)',
)
}
}
const splitResult = await runIt2(splitArgs)
if (splitResult.code !== 0) {
// If we targeted a teammate session, confirm it's actually dead before
// pruning — 'session list' distinguishes dead-target from systemic
// failure (Python API off, it2 removed, transient socket error).
// Pruning on systemic failure would drain all live IDs → state corrupted.
if (targetedTeammateId) {
const listResult = await runIt2(['session', 'list'])
if (
listResult.code === 0 &&
!listResult.stdout.includes(targetedTeammateId)
) {
// Confirmed dead — prune and retry with next-to-last (or leader).
logForDebugging(
`[ITermBackend] Split failed targeting dead session ${targetedTeammateId}, pruning and retrying: ${splitResult.stderr}`,
)
const idx = teammateSessionIds.indexOf(targetedTeammateId)
if (idx !== -1) {
teammateSessionIds.splice(idx, 1)
}
if (teammateSessionIds.length === 0) {
firstPaneUsed = false
}
continue
}
// Target is alive or we can't tell — don't corrupt state, surface the error.
}
throw new Error(
`Failed to create iTerm2 split pane: ${splitResult.stderr}`,
)
}
if (isFirstTeammate) {
firstPaneUsed = true
}
// Parse the session ID from split output
// This works because we're splitting from a specific session (-s flag),
// so the new pane is in the same window and the UUID is valid.
const paneId = parseSplitOutput(splitResult.stdout)
if (!paneId) {
throw new Error(
`Failed to parse session ID from split output: ${splitResult.stdout}`,
)
}
logForDebugging(
`[ITermBackend] Created teammate pane for ${name}: ${paneId}`,
)
teammateSessionIds.push(paneId)
// Set pane color and title
// Skip color and title for now - each it2 call is slow (Python process + API)
// The pane is functional without these cosmetic features
// TODO: Consider batching these or making them async/fire-and-forget
return { paneId, isFirstTeammate }
}
} finally {
releaseLock()
}
}
/**
* Sends a command to a specific pane.
*/
async sendCommandToPane(
paneId: PaneId,
command: string,
_useExternalSession?: boolean,
): Promise<void> {
// Use it2 session run to execute command (adds newline automatically)
// Always use -s flag to target specific session - this ensures the command
// goes to the right pane even if user switches windows
const args = paneId
? ['session', 'run', '-s', paneId, command]
: ['session', 'run', command]
const result = await runIt2(args)
if (result.code !== 0) {
throw new Error(
`Failed to send command to iTerm2 pane ${paneId}: ${result.stderr}`,
)
}
}
/**
* No-op for iTerm2 - tab colors would require escape sequences but we skip
* them for performance (each it2 call is slow).
*/
async setPaneBorderColor(
_paneId: PaneId,
_color: AgentColorName,
_useExternalSession?: boolean,
): Promise<void> {
// Skip for performance - each it2 call spawns a Python process
}
/**
* No-op for iTerm2 - titles would require escape sequences but we skip
* them for performance (each it2 call is slow).
*/
async setPaneTitle(
_paneId: PaneId,
_name: string,
_color: AgentColorName,
_useExternalSession?: boolean,
): Promise<void> {
// Skip for performance - each it2 call spawns a Python process
}
/**
* No-op for iTerm2 - pane titles are shown in tabs automatically.
*/
async enablePaneBorderStatus(
_windowTarget?: string,
_useExternalSession?: boolean,
): Promise<void> {
// iTerm2 doesn't have the concept of pane border status like tmux
// Titles are shown in tabs automatically
}
/**
* No-op for iTerm2 - pane balancing is handled automatically.
*/
async rebalancePanes(
_windowTarget: string,
_hasLeader: boolean,
): Promise<void> {
// iTerm2 handles pane balancing automatically
logForDebugging(
'[ITermBackend] Pane rebalancing not implemented for iTerm2',
)
}
/**
* Kills/closes a specific pane using the it2 CLI.
* Also removes the pane from tracked session IDs so subsequent spawns
* don't try to split from a dead session.
*/
async killPane(
paneId: PaneId,
_useExternalSession?: boolean,
): Promise<boolean> {
// -f (force) is required: without it, iTerm2 respects the "Confirm before
// closing" preference and either shows a dialog or refuses when the session
// still has a running process (the shell always is). tmux kill-pane has no
// such prompt, which is why this was only broken for iTerm2.
const result = await runIt2(['session', 'close', '-f', '-s', paneId])
// Clean up module state regardless of close result — even if the pane is
// already gone (e.g., user closed it manually), removing the stale ID is correct.
const idx = teammateSessionIds.indexOf(paneId)
if (idx !== -1) {
teammateSessionIds.splice(idx, 1)
}
if (teammateSessionIds.length === 0) {
firstPaneUsed = false
}
return result.code === 0
}
/**
* Stub for hiding a pane - not supported in iTerm2 backend.
* iTerm2 doesn't have a direct equivalent to tmux's break-pane.
*/
async hidePane(
_paneId: PaneId,
_useExternalSession?: boolean,
): Promise<boolean> {
logForDebugging('[ITermBackend] hidePane not supported in iTerm2')
return false
}
/**
* Stub for showing a hidden pane - not supported in iTerm2 backend.
* iTerm2 doesn't have a direct equivalent to tmux's join-pane.
*/
async showPane(
_paneId: PaneId,
_targetWindowOrPane: string,
_useExternalSession?: boolean,
): Promise<boolean> {
logForDebugging('[ITermBackend] showPane not supported in iTerm2')
return false
}
}
// Register the backend with the registry when this module is imported.
// This side effect is intentional - the registry needs backends to self-register to avoid circular dependencies.
// eslint-disable-next-line custom-rules/no-top-level-side-effects
registerITermBackend(ITermBackend)
|