Add tmux pane management for background agent sessions (#1094)

* feat(config): add TmuxConfigSchema for tmux subagent pane management

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* feat(shared): add tmux module structure

* feat(shared/tmux): implement tmux pane utilities

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* test(tmux-subagent): add TmuxSessionManager tests (TDD RED)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* feat(tmux-subagent): implement TmuxSessionManager

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

* feat(integration): wire TmuxSessionManager with 500ms delay

- Task 5: Add 500ms delay in BackgroundManager after session creation
- Task 6: Wire TmuxSessionManager event handlers (session.created/deleted)
- Both changes integrate tmux pane management into plugin lifecycle

Co-authored-by: Sisyphus <ultrawork@oh-my-opencode>

---------

Co-authored-by: justsisyphus <justsisyphus@users.noreply.github.com>
Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Co-authored-by: Sisyphus <ultrawork@oh-my-opencode>
This commit is contained in:
YeonGyu-Kim
2026-01-25 15:34:10 +09:00
committed by GitHub
parent bccc943173
commit aead4aebd2
16 changed files with 893 additions and 39 deletions
+14 -3
View File
@@ -7,7 +7,8 @@ import type {
} from "./types"
import { log, getAgentToolRestrictions } from "../../shared"
import { ConcurrencyManager } from "./concurrency"
import type { BackgroundTaskConfig } from "../../config/schema"
import type { BackgroundTaskConfig, TmuxConfig } from "../../config/schema"
import { isInsideTmux } from "../../shared/tmux"
import { subagentSessions } from "../claude-code-session-state"
import { getTaskToastManager } from "../task-toast-manager"
@@ -68,12 +69,16 @@ export class BackgroundManager {
private concurrencyManager: ConcurrencyManager
private shutdownTriggered = false
private config?: BackgroundTaskConfig
private tmuxEnabled: boolean
private queuesByKey: Map<string, QueueItem[]> = new Map()
private processingKeys: Set<string> = new Set()
constructor(ctx: PluginInput, config?: BackgroundTaskConfig) {
constructor(
ctx: PluginInput,
config?: BackgroundTaskConfig,
tmuxConfig?: TmuxConfig
) {
this.tasks = new Map()
this.notifications = new Map()
this.pendingByParent = new Map()
@@ -81,6 +86,7 @@ export class BackgroundManager {
this.directory = ctx.directory
this.concurrencyManager = new ConcurrencyManager(config)
this.config = config
this.tmuxEnabled = tmuxConfig?.enabled ?? false
this.registerProcessCleanup()
}
@@ -222,6 +228,11 @@ export class BackgroundManager {
const sessionID = createResult.data.id
subagentSessions.add(sessionID)
// Wait for TmuxSessionManager to spawn pane via event hook
if (this.tmuxEnabled && isInsideTmux()) {
await new Promise(r => setTimeout(r, 500))
}
// Update task to running state
task.status = "running"
task.startedAt = new Date()
+2
View File
@@ -0,0 +1,2 @@
export * from "./manager"
export * from "./types"
+299
View File
@@ -0,0 +1,299 @@
import { describe, test, expect, mock, beforeEach } from 'bun:test'
import type { TmuxConfig } from '../../config/schema'
// Mock setup - tmux-utils functions
const mockSpawnTmuxPane = mock(async () => ({ success: true, paneId: '%mock' }))
const mockCloseTmuxPane = mock(async () => true)
const mockIsInsideTmux = mock(() => true)
mock.module('../../shared/tmux', () => ({
spawnTmuxPane: mockSpawnTmuxPane,
closeTmuxPane: mockCloseTmuxPane,
isInsideTmux: mockIsInsideTmux,
POLL_INTERVAL_BACKGROUND_MS: 2000,
SESSION_TIMEOUT_MS: 600000,
SESSION_MISSING_GRACE_MS: 6000,
}))
// Mock context helper
function createMockContext(overrides?: {
sessionStatusResult?: { data?: Record<string, { type: string }> }
}) {
return {
serverUrl: new URL('http://localhost:4096'),
client: {
session: {
status: mock(async () => overrides?.sessionStatusResult ?? { data: {} }),
},
},
} as any
}
describe('TmuxSessionManager', () => {
beforeEach(() => {
// Reset mocks before each test
mockSpawnTmuxPane.mockClear()
mockCloseTmuxPane.mockClear()
mockIsInsideTmux.mockClear()
})
describe('constructor', () => {
test('enabled when config.enabled=true and isInsideTmux=true', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
// #when
const manager = new TmuxSessionManager(ctx, config)
// #then
expect(manager).toBeDefined()
})
test('disabled when config.enabled=true but isInsideTmux=false', async () => {
// #given
mockIsInsideTmux.mockReturnValue(false)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
// #when
const manager = new TmuxSessionManager(ctx, config)
// #then
expect(manager).toBeDefined()
})
test('disabled when config.enabled=false', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: false,
layout: 'main-vertical',
main_pane_size: 60,
}
// #when
const manager = new TmuxSessionManager(ctx, config)
// #then
expect(manager).toBeDefined()
})
})
describe('onSessionCreated', () => {
test('spawns pane when session has parentID', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
const event = {
sessionID: 'ses_child',
parentID: 'ses_parent',
title: 'Background: Test Task',
}
// #when
await manager.onSessionCreated(event)
// #then
expect(mockSpawnTmuxPane).toHaveBeenCalledTimes(1)
expect(mockSpawnTmuxPane).toHaveBeenCalledWith(
'ses_child',
'Background: Test Task',
config,
'http://localhost:4096'
)
})
test('does NOT spawn pane when session has no parentID', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
const event = {
sessionID: 'ses_root',
parentID: undefined,
title: 'Root Session',
}
// #when
await manager.onSessionCreated(event)
// #then
expect(mockSpawnTmuxPane).toHaveBeenCalledTimes(0)
})
test('does NOT spawn pane when disabled', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: false,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
const event = {
sessionID: 'ses_child',
parentID: 'ses_parent',
title: 'Background: Test Task',
}
// #when
await manager.onSessionCreated(event)
// #then
expect(mockSpawnTmuxPane).toHaveBeenCalledTimes(0)
})
})
describe('onSessionDeleted', () => {
test('closes pane when tracked session is deleted', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
// First create a session (to track it)
await manager.onSessionCreated({
sessionID: 'ses_child',
parentID: 'ses_parent',
title: 'Background: Test Task',
})
// #when
await manager.onSessionDeleted({ sessionID: 'ses_child' })
// #then
expect(mockCloseTmuxPane).toHaveBeenCalledTimes(1)
})
test('does nothing when untracked session is deleted', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
// #when
await manager.onSessionDeleted({ sessionID: 'ses_unknown' })
// #then
expect(mockCloseTmuxPane).toHaveBeenCalledTimes(0)
})
})
describe('pollSessions', () => {
test('closes pane when session becomes idle', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
// Mock session.status to return idle session
const ctx = createMockContext({
sessionStatusResult: {
data: {
ses_child: { type: 'idle' },
},
},
})
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
// Create tracked session
await manager.onSessionCreated({
sessionID: 'ses_child',
parentID: 'ses_parent',
title: 'Background: Test Task',
})
mockCloseTmuxPane.mockClear() // Clear spawn call
// #when
await manager.pollSessions()
// #then
expect(mockCloseTmuxPane).toHaveBeenCalledTimes(1)
})
})
describe('cleanup', () => {
test('closes all tracked panes', async () => {
// #given
mockIsInsideTmux.mockReturnValue(true)
const { TmuxSessionManager } = await import('./manager')
const ctx = createMockContext()
const config: TmuxConfig = {
enabled: true,
layout: 'main-vertical',
main_pane_size: 60,
}
const manager = new TmuxSessionManager(ctx, config)
// Track multiple sessions
await manager.onSessionCreated({
sessionID: 'ses_1',
parentID: 'ses_parent',
title: 'Task 1',
})
await manager.onSessionCreated({
sessionID: 'ses_2',
parentID: 'ses_parent',
title: 'Task 2',
})
mockCloseTmuxPane.mockClear()
// #when
await manager.cleanup()
// #then
expect(mockCloseTmuxPane).toHaveBeenCalledTimes(2)
})
})
})
+127
View File
@@ -0,0 +1,127 @@
import type { PluginInput } from "@opencode-ai/plugin"
import type { TmuxConfig } from "../../config/schema"
import type { TrackedSession } from "./types"
import {
spawnTmuxPane,
closeTmuxPane,
isInsideTmux,
POLL_INTERVAL_BACKGROUND_MS,
SESSION_MISSING_GRACE_MS,
} from "../../shared/tmux"
export class TmuxSessionManager {
private enabled: boolean
private sessions: Map<string, TrackedSession>
private serverUrl: string
private config: TmuxConfig
private ctx: PluginInput
private pollingInterval: ReturnType<typeof setInterval> | null = null
constructor(ctx: PluginInput, tmuxConfig: TmuxConfig) {
this.ctx = ctx
this.config = tmuxConfig
this.sessions = new Map()
this.enabled = tmuxConfig.enabled && isInsideTmux()
const defaultPort = process.env.OPENCODE_PORT ?? "4096"
const urlString = ctx.serverUrl?.toString() ?? `http://localhost:${defaultPort}`
this.serverUrl = urlString.endsWith("/") ? urlString.slice(0, -1) : urlString
if (this.enabled) {
this.startPolling()
}
}
async onSessionCreated(event: {
sessionID: string
parentID?: string
title: string
}): Promise<void> {
if (!this.enabled) return
if (!event.parentID) return
const result = await spawnTmuxPane(
event.sessionID,
event.title,
this.config,
this.serverUrl
)
if (result.success && result.paneId) {
this.sessions.set(event.sessionID, {
sessionId: event.sessionID,
paneId: result.paneId,
description: event.title,
createdAt: new Date(),
lastSeenAt: new Date(),
})
}
}
async onSessionDeleted(event: { sessionID: string }): Promise<void> {
if (!this.enabled) return
const tracked = this.sessions.get(event.sessionID)
if (!tracked) return
await this.closeSession(event.sessionID)
}
async pollSessions(): Promise<void> {
if (!this.enabled) return
if (this.sessions.size === 0) return
try {
const statusResult = await this.ctx.client.session.status({ path: undefined })
const statuses = (statusResult.data ?? {}) as Record<string, { type: string }>
for (const [sessionId, tracked] of this.sessions.entries()) {
const status = statuses[sessionId]
if (!status) {
const missingSince = Date.now() - tracked.lastSeenAt.getTime()
if (missingSince > SESSION_MISSING_GRACE_MS) {
await this.closeSession(sessionId)
}
continue
}
tracked.lastSeenAt = new Date()
if (status.type === "idle") {
await this.closeSession(sessionId)
}
}
} catch {
// Ignore errors
}
}
async closeSession(sessionId: string): Promise<void> {
const tracked = this.sessions.get(sessionId)
if (!tracked) return
await closeTmuxPane(tracked.paneId)
this.sessions.delete(sessionId)
}
async cleanup(): Promise<void> {
if (this.pollingInterval) {
clearInterval(this.pollingInterval)
this.pollingInterval = null
}
for (const sessionId of Array.from(this.sessions.keys())) {
await this.closeSession(sessionId)
}
}
private startPolling(): void {
this.pollingInterval = setInterval(() => {
this.pollSessions().catch(() => {
// Ignore errors
})
}, POLL_INTERVAL_BACKGROUND_MS)
}
}
+7
View File
@@ -0,0 +1,7 @@
export interface TrackedSession {
sessionId: string
paneId: string
description: string
createdAt: Date
lastSeenAt: Date
}