feat(tmux): add killTmuxSessionIfExists utility for explicit session teardown

Adds killTmuxSessionIfExists(sessionName), a best-effort no-op when the
named session is absent. Drains both stdio streams so it does not leak
pipe buffers the way closeTmuxPane historically did.

Also exports ISOLATED_SESSION_NAME ("omo-agents") from session-spawn so
callers can tear down the shared isolated session without hard-coding
the name in multiple places.
This commit is contained in:
YeonGyu-Kim
2026-04-18 19:31:22 +09:00
parent 2a99a524ea
commit de8a0167e6
5 changed files with 228 additions and 2 deletions
+2 -1
View File
@@ -10,6 +10,7 @@ export { spawnTmuxPane } from "./tmux-utils/pane-spawn"
export { closeTmuxPane } from "./tmux-utils/pane-close"
export { replaceTmuxPane } from "./tmux-utils/pane-replace"
export { spawnTmuxWindow } from "./tmux-utils/window-spawn"
export { spawnTmuxSession } from "./tmux-utils/session-spawn"
export { spawnTmuxSession, ISOLATED_SESSION_NAME } from "./tmux-utils/session-spawn"
export { killTmuxSessionIfExists } from "./tmux-utils/session-kill"
export { applyLayout, enforceMainPaneWidth } from "./tmux-utils/layout"
+1
View File
@@ -0,0 +1 @@
export { killTmuxSessionIfExists } from "./session-kill"
@@ -0,0 +1,173 @@
import { beforeEach, describe, expect, it, mock } from "bun:test"
type KillTmuxSessionIfExists = typeof import("./session-kill").killTmuxSessionIfExists
type SpawnCall = {
command: string[]
options: {
stdout?: string
stderr?: string
}
}
type FakeSubprocess = {
exited: Promise<number>
stdout: ReadableStream<Uint8Array>
stderr: ReadableStream<Uint8Array>
}
const spawnCalls: SpawnCall[] = []
const queuedProcesses: FakeSubprocess[] = []
function createStream(chunks: string[] = []): ReadableStream<Uint8Array> {
const textEncoder = new TextEncoder()
return new ReadableStream({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(textEncoder.encode(chunk))
}
controller.close()
},
})
}
function createProcess(exitCode: number, output: { stdout?: string[]; stderr?: string[] } = {}): FakeSubprocess {
return {
exited: Promise.resolve(exitCode),
stdout: createStream(output.stdout),
stderr: createStream(output.stderr),
}
}
const spawnMock = mock((command: string[], options: { stdout?: string; stderr?: string } = {}) => {
spawnCalls.push({ command, options })
const process = queuedProcesses.shift()
if (!process) {
throw new Error(`No fake subprocess configured for ${command.join(" ")}`)
}
return process
})
const isInsideTmuxMock = mock((): boolean => true)
const getTmuxPathMock = mock(async (): Promise<string | undefined> => "tmux")
const logMock = mock(() => undefined)
const sessionKillSpecifier = import.meta.resolve("./session-kill")
const environmentSpecifier = import.meta.resolve("./environment")
const loggerSpecifier = import.meta.resolve("../../logger")
const spawnProcessSpecifier = import.meta.resolve("./spawn-process")
const tmuxPathResolverSpecifier = import.meta.resolve("../../../tools/interactive-bash/tmux-path-resolver")
async function loadKillTmuxSessionIfExists(): Promise<typeof KillTmuxSessionIfExists> {
const module = await import(`${sessionKillSpecifier}?test=${crypto.randomUUID()}`)
return module.killTmuxSessionIfExists
}
function registerModuleMocks(): void {
mock.module(spawnProcessSpecifier, () => ({ spawn: spawnMock }))
mock.module(environmentSpecifier, () => ({ isInsideTmux: isInsideTmuxMock }))
mock.module(tmuxPathResolverSpecifier, () => ({ getTmuxPath: getTmuxPathMock }))
mock.module(loggerSpecifier, () => ({ log: logMock }))
}
describe("killTmuxSessionIfExists", () => {
beforeEach(() => {
registerModuleMocks()
spawnCalls.length = 0
queuedProcesses.length = 0
spawnMock.mockClear()
isInsideTmuxMock.mockClear()
getTmuxPathMock.mockClear()
logMock.mockClear()
isInsideTmuxMock.mockImplementation((): boolean => true)
getTmuxPathMock.mockImplementation(async (): Promise<string | undefined> => "tmux")
})
it("#given omo-agents session exists #when killTmuxSessionIfExists called #then kill-session invoked and returns true", async () => {
// given
const killTmuxSessionIfExists = await loadKillTmuxSessionIfExists()
queuedProcesses.push(createProcess(0), createProcess(0, { stdout: ["killed"], stderr: [] }))
// when
const result = await killTmuxSessionIfExists("omo-agents")
// then
expect(result).toBe(true)
expect(spawnCalls).toEqual([
{
command: ["tmux", "has-session", "-t", "omo-agents"],
options: { stdout: "ignore", stderr: "ignore" },
},
{
command: ["tmux", "kill-session", "-t", "omo-agents"],
options: { stdout: "pipe", stderr: "pipe" },
},
])
})
it("#given omo-agents session does NOT exist (has-session exits non-zero) #when killTmuxSessionIfExists called #then NO kill-session invocation and returns false", async () => {
// given
const killTmuxSessionIfExists = await loadKillTmuxSessionIfExists()
queuedProcesses.push(createProcess(1))
// when
const result = await killTmuxSessionIfExists("omo-agents")
// then
expect(result).toBe(false)
expect(spawnCalls).toEqual([
{
command: ["tmux", "has-session", "-t", "omo-agents"],
options: { stdout: "ignore", stderr: "ignore" },
},
])
})
it("#given not inside tmux #when killTmuxSessionIfExists called #then returns false without any spawn", async () => {
// given
const killTmuxSessionIfExists = await loadKillTmuxSessionIfExists()
isInsideTmuxMock.mockReturnValue(false)
// when
const result = await killTmuxSessionIfExists("omo-agents")
// then
expect(result).toBe(false)
expect(spawnCalls).toHaveLength(0)
expect(getTmuxPathMock).toHaveBeenCalledTimes(0)
})
it("#given tmux not found #when killTmuxSessionIfExists called #then returns false without spawn", async () => {
// given
const killTmuxSessionIfExists = await loadKillTmuxSessionIfExists()
getTmuxPathMock.mockResolvedValue(undefined)
// when
const result = await killTmuxSessionIfExists("omo-agents")
// then
expect(result).toBe(false)
expect(spawnCalls).toHaveLength(0)
})
it("#given kill-session itself fails (e.g., race between has-session and kill) #when killTmuxSessionIfExists called #then returns false but does not throw", async () => {
// given
const killTmuxSessionIfExists = await loadKillTmuxSessionIfExists()
queuedProcesses.push(
createProcess(0),
createProcess(1, { stdout: [], stderr: ["no session"] }),
)
// when
const result = await killTmuxSessionIfExists("omo-agents")
// then
expect(result).toBe(false)
expect(spawnCalls).toHaveLength(2)
})
})
@@ -0,0 +1,51 @@
async function readStream(stream: ReadableStream<Uint8Array> | null | undefined): Promise<string> {
return stream ? new Response(stream).text() : ""
}
export async function killTmuxSessionIfExists(sessionName: string): Promise<boolean> {
const [{ log }, { isInsideTmux }, { getTmuxPath }, { spawn }] = await Promise.all([
import("../../logger"),
import("./environment"),
import("../../../tools/interactive-bash/tmux-path-resolver"),
import("./spawn-process"),
])
if (!isInsideTmux()) {
log("[killTmuxSessionIfExists] SKIP: not inside tmux", { sessionName })
return false
}
const tmux = await getTmuxPath()
if (!tmux) {
log("[killTmuxSessionIfExists] SKIP: tmux not found", { sessionName })
return false
}
const hasSessionProcess = spawn([tmux, "has-session", "-t", sessionName], {
stdout: "ignore",
stderr: "ignore",
})
if ((await hasSessionProcess.exited) !== 0) {
log("[killTmuxSessionIfExists] SKIP: session not found", { sessionName })
return false
}
const killSessionProcess = spawn([tmux, "kill-session", "-t", sessionName], {
stdout: "pipe",
stderr: "pipe",
})
const [, stderr, exitCode] = await Promise.all([
readStream(killSessionProcess.stdout),
readStream(killSessionProcess.stderr),
killSessionProcess.exited,
])
if (exitCode !== 0) {
log("[killTmuxSessionIfExists] FAILED", { sessionName, exitCode, stderr: stderr.trim() })
return false
}
log("[killTmuxSessionIfExists] SUCCESS", { sessionName })
return true
}
+1 -1
View File
@@ -6,7 +6,7 @@ import { isInsideTmux } from "./environment"
import { isServerRunning } from "./server-health"
import { shellEscapeForDoubleQuotedCommand } from "../../shell-env"
const ISOLATED_SESSION_NAME = "omo-agents"
export const ISOLATED_SESSION_NAME = "omo-agents"
async function getWindowDimensions(
tmux: string,