test: run suite without split runner
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { describe, test, expect, beforeEach, afterEach, mock } from "bun:test"
|
||||
import { describe, test, expect, beforeEach, afterEach } from "bun:test"
|
||||
import {
|
||||
isInsideTmux,
|
||||
isServerRunning,
|
||||
@@ -9,15 +9,22 @@ import {
|
||||
applyLayout,
|
||||
} from "./tmux-utils"
|
||||
import { isInsideTmuxEnvironment } from "./tmux-utils/environment"
|
||||
import { createServerHealthStateForTesting } from "./tmux-utils/server-health"
|
||||
|
||||
function createFetchMock(responseFactory: () => Promise<Response>): typeof fetch & ReturnType<typeof mock> {
|
||||
const fetchMock = mock(async (_input: RequestInfo | URL, _init?: RequestInit) => responseFactory())
|
||||
function createFetchRecorder(responseFactory: () => Promise<Response>): typeof fetch & { calls: Array<[RequestInfo | URL, RequestInit | undefined]> } {
|
||||
const calls: Array<[RequestInfo | URL, RequestInit | undefined]> = []
|
||||
const fetchRecorder = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
|
||||
calls.push([input, init])
|
||||
return await responseFactory()
|
||||
}
|
||||
const preconnect = globalThis.fetch.preconnect?.bind(globalThis.fetch)
|
||||
return Object.assign(fetchMock, {
|
||||
return Object.assign(fetchRecorder, {
|
||||
calls,
|
||||
preconnect,
|
||||
}) as typeof fetch & ReturnType<typeof mock>
|
||||
}) as typeof fetch & { calls: Array<[RequestInfo | URL, RequestInit | undefined]> }
|
||||
}
|
||||
|
||||
|
||||
describe("isInsideTmux", () => {
|
||||
test("returns true when TMUX env is set", () => {
|
||||
// given
|
||||
@@ -62,22 +69,17 @@ describe("isInsideTmux", () => {
|
||||
})
|
||||
|
||||
describe("isServerRunning", () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
|
||||
beforeEach(() => {
|
||||
resetServerCheck()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
test("returns true when server responds OK", async () => {
|
||||
// given
|
||||
globalThis.fetch = createFetchMock(async () => new Response(null, { status: 200 }))
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||
|
||||
// when
|
||||
const result = await isServerRunning("http://localhost:4096")
|
||||
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then
|
||||
expect(result).toBe(true)
|
||||
@@ -85,12 +87,13 @@ describe("isServerRunning", () => {
|
||||
|
||||
test("returns false when server not reachable", async () => {
|
||||
// given
|
||||
globalThis.fetch = createFetchMock(async () => {
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => {
|
||||
throw new Error("ECONNREFUSED")
|
||||
})
|
||||
|
||||
// when
|
||||
const result = await isServerRunning("http://localhost:4096")
|
||||
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then
|
||||
expect(result).toBe(false)
|
||||
@@ -98,10 +101,11 @@ describe("isServerRunning", () => {
|
||||
|
||||
test("returns false when fetch returns not ok", async () => {
|
||||
// given
|
||||
globalThis.fetch = createFetchMock(async () => new Response(null, { status: 500 }))
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 500 }))
|
||||
|
||||
// when
|
||||
const result = await isServerRunning("http://localhost:4096")
|
||||
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then
|
||||
expect(result).toBe(false)
|
||||
@@ -109,43 +113,43 @@ describe("isServerRunning", () => {
|
||||
|
||||
test("caches successful result", async () => {
|
||||
// given
|
||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
||||
globalThis.fetch = fetchMock
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||
|
||||
// when
|
||||
await isServerRunning("http://localhost:4096")
|
||||
await isServerRunning("http://localhost:4096")
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then - should only call fetch once due to caching
|
||||
expect(fetchMock.mock.calls.length).toBe(1)
|
||||
expect(fetchMock.calls.length).toBe(1)
|
||||
})
|
||||
|
||||
test("does not cache failed result", async () => {
|
||||
// given
|
||||
const fetchMock = createFetchMock(async () => {
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => {
|
||||
throw new Error("ECONNREFUSED")
|
||||
})
|
||||
globalThis.fetch = fetchMock
|
||||
|
||||
// when
|
||||
await isServerRunning("http://localhost:4096")
|
||||
await isServerRunning("http://localhost:4096")
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then - should call fetch 4 times (2 attempts per call, 2 calls)
|
||||
expect(fetchMock.mock.calls.length).toBe(4)
|
||||
expect(fetchMock.calls.length).toBe(4)
|
||||
})
|
||||
|
||||
test("uses different cache for different URLs", async () => {
|
||||
// given
|
||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
||||
globalThis.fetch = fetchMock
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||
|
||||
// when
|
||||
await isServerRunning("http://localhost:4096")
|
||||
await isServerRunning("http://localhost:5000")
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
await isServerRunning("http://localhost:5000", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then - should call fetch twice for different URLs
|
||||
expect(fetchMock.mock.calls.length).toBe(2)
|
||||
expect(fetchMock.calls.length).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -157,25 +161,22 @@ describe("resetServerCheck", () => {
|
||||
|
||||
test("allows re-checking after reset", async () => {
|
||||
// given
|
||||
const originalFetch = globalThis.fetch
|
||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
||||
globalThis.fetch = fetchMock
|
||||
const state = createServerHealthStateForTesting()
|
||||
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||
|
||||
// when
|
||||
await isServerRunning("http://localhost:4096")
|
||||
resetServerCheck()
|
||||
await isServerRunning("http://localhost:4096")
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
state.serverAvailable = null
|
||||
state.serverCheckUrl = null
|
||||
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then - should call fetch twice after reset
|
||||
expect(fetchMock.mock.calls.length).toBe(2)
|
||||
expect(fetchMock.calls.length).toBe(2)
|
||||
|
||||
// cleanup
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
})
|
||||
|
||||
describe("markServerRunningInProcess", () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
const SERVER_RUNNING_KEY = Symbol.for("oh-my-opencode:server-running-in-process")
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -184,22 +185,21 @@ describe("markServerRunningInProcess", () => {
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
delete (globalThis as Record<symbol, boolean>)[SERVER_RUNNING_KEY]
|
||||
})
|
||||
|
||||
test("skips HTTP fetch when marked as running in-process", async () => {
|
||||
// given
|
||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
||||
globalThis.fetch = fetchMock
|
||||
markServerRunningInProcess()
|
||||
const state = createServerHealthStateForTesting()
|
||||
state.serverRunningInProcess = true
|
||||
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||
|
||||
// when
|
||||
const result = await isServerRunning("http://localhost:4096")
|
||||
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||
|
||||
// then
|
||||
expect(result).toBe(true)
|
||||
expect(fetchMock.mock.calls.length).toBe(0)
|
||||
expect(fetchMock.calls.length).toBe(0)
|
||||
})
|
||||
|
||||
test("uses globalThis so flag survives across module instances", () => {
|
||||
|
||||
@@ -3,6 +3,17 @@ let serverCheckUrl: string | null = null
|
||||
|
||||
const SERVER_RUNNING_KEY = Symbol.for("oh-my-opencode:server-running-in-process")
|
||||
|
||||
export type ServerHealthState = {
|
||||
serverAvailable: boolean | null
|
||||
serverCheckUrl: string | null
|
||||
serverRunningInProcess: boolean
|
||||
}
|
||||
|
||||
type IsServerRunningOptions = {
|
||||
fetchImplementation?: typeof fetch
|
||||
state?: ServerHealthState
|
||||
}
|
||||
|
||||
function delay(milliseconds: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||
}
|
||||
@@ -15,12 +26,25 @@ function isMarkedRunningInProcess(): boolean {
|
||||
return (globalThis as Record<symbol, boolean>)[SERVER_RUNNING_KEY] === true
|
||||
}
|
||||
|
||||
export async function isServerRunning(serverUrl: string): Promise<boolean> {
|
||||
if (isMarkedRunningInProcess()) {
|
||||
export function createServerHealthStateForTesting(): ServerHealthState {
|
||||
return {
|
||||
serverAvailable: null,
|
||||
serverCheckUrl: null,
|
||||
serverRunningInProcess: false,
|
||||
}
|
||||
}
|
||||
|
||||
export async function isServerRunning(serverUrl: string, options: IsServerRunningOptions = {}): Promise<boolean> {
|
||||
const fetchImplementation = options.fetchImplementation ?? fetch
|
||||
const state = options.state
|
||||
const markedRunning = state?.serverRunningInProcess ?? isMarkedRunningInProcess()
|
||||
if (markedRunning) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (serverCheckUrl === serverUrl && serverAvailable === true) {
|
||||
const cachedUrl = state?.serverCheckUrl ?? serverCheckUrl
|
||||
const cachedAvailable = state?.serverAvailable ?? serverAvailable
|
||||
if (cachedUrl === serverUrl && cachedAvailable === true) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -33,14 +57,19 @@ export async function isServerRunning(serverUrl: string): Promise<boolean> {
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs)
|
||||
|
||||
try {
|
||||
const response = await fetch(healthUrl, {
|
||||
const response = await fetchImplementation(healthUrl, {
|
||||
signal: controller.signal,
|
||||
}).catch(() => null)
|
||||
clearTimeout(timeout)
|
||||
|
||||
if (response?.ok) {
|
||||
serverCheckUrl = serverUrl
|
||||
serverAvailable = true
|
||||
if (state) {
|
||||
state.serverCheckUrl = serverUrl
|
||||
state.serverAvailable = true
|
||||
} else {
|
||||
serverCheckUrl = serverUrl
|
||||
serverAvailable = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { beforeEach, describe, expect, it, mock } from "bun:test"
|
||||
import { describe, expect, it } from "bun:test"
|
||||
|
||||
import type { TmuxConfig } from "../../../config/schema"
|
||||
import type { TmuxCommandResult } from "../runner"
|
||||
|
||||
const sessionSpawnSpecifier = import.meta.resolve("./session-spawn")
|
||||
import { spawnTmuxSession } from "./session-spawn"
|
||||
|
||||
const enabledTmuxConfig = {
|
||||
enabled: true,
|
||||
@@ -14,17 +13,7 @@ const enabledTmuxConfig = {
|
||||
isolation: "inline",
|
||||
} satisfies TmuxConfig
|
||||
|
||||
const runTmuxCommandMock = mock(async (): Promise<TmuxCommandResult> => ({
|
||||
success: true,
|
||||
output: "",
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
}))
|
||||
const isInsideTmuxMock = mock((): boolean => true)
|
||||
const isServerRunningMock = mock(async (): Promise<boolean> => true)
|
||||
const getTmuxPathMock = mock(async (): Promise<string | null> => "sh")
|
||||
const logMock = mock(() => undefined)
|
||||
type SpawnTmuxSessionDeps = NonNullable<Parameters<typeof spawnTmuxSession>[6]>
|
||||
|
||||
function toStringArray(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
@@ -38,83 +27,74 @@ function toStringArray(value: unknown): string[] {
|
||||
return items
|
||||
}
|
||||
|
||||
function getRunTmuxCommandCall(index: number): [string, string[]] {
|
||||
const call = Reflect.get(runTmuxCommandMock.mock.calls, index)
|
||||
const command = Reflect.get(call, 0)
|
||||
const args = Reflect.get(call, 1)
|
||||
if (!Array.isArray(call) || typeof command !== "string" || !Array.isArray(args)) {
|
||||
throw new Error(`Expected tmux runner call at index ${index}`)
|
||||
}
|
||||
|
||||
return [command, toStringArray(args)]
|
||||
function defaultTmuxCommandResults(): TmuxCommandResult[] {
|
||||
return [
|
||||
{ success: true, output: "120,40", stdout: "120,40", stderr: "", exitCode: 0 },
|
||||
{ success: false, output: "", stdout: "", stderr: "", exitCode: 1 },
|
||||
{ success: true, output: "%42", stdout: "%42", stderr: "", exitCode: 0 },
|
||||
{ success: true, output: "", stdout: "", stderr: "", exitCode: 0 },
|
||||
]
|
||||
}
|
||||
|
||||
function getSpawnCommand(): string {
|
||||
const newSessionCall = getRunTmuxCommandCall(2)
|
||||
const newSessionCommand = newSessionCall[1][newSessionCall[1].length - 1]
|
||||
if (newSessionCommand === undefined) {
|
||||
throw new Error("Expected new-session command")
|
||||
function createHarness() {
|
||||
const calls: Array<[string, string[]]> = []
|
||||
const logs: string[] = []
|
||||
const tmuxCommandResults = defaultTmuxCommandResults()
|
||||
const runTmuxCommand = async (command: string, args: string[]): Promise<TmuxCommandResult> => {
|
||||
calls.push([command, [...args]])
|
||||
const nextResult = tmuxCommandResults.shift()
|
||||
if (!nextResult) {
|
||||
throw new Error("No more tmux command results configured")
|
||||
}
|
||||
return nextResult
|
||||
}
|
||||
const deps: SpawnTmuxSessionDeps = {
|
||||
log: (message) => {
|
||||
logs.push(message)
|
||||
},
|
||||
runTmuxCommand,
|
||||
isInsideTmux: (): boolean => true,
|
||||
isServerRunning: async (): Promise<boolean> => true,
|
||||
getTmuxPath: async (): Promise<string | null> => "sh",
|
||||
}
|
||||
|
||||
return newSessionCommand
|
||||
}
|
||||
function getRunTmuxCommandCall(index: number): [string, string[]] {
|
||||
const call = calls[index]
|
||||
if (!call) {
|
||||
throw new Error(`Expected tmux runner call at index ${index}; logs: ${logs.join(", ")}`)
|
||||
}
|
||||
|
||||
function createDeps(): NonNullable<Parameters<typeof import("./session-spawn").spawnTmuxSession>[6]> {
|
||||
return {
|
||||
log: logMock,
|
||||
runTmuxCommand: runTmuxCommandMock,
|
||||
isInsideTmux: isInsideTmuxMock,
|
||||
isServerRunning: isServerRunningMock,
|
||||
getTmuxPath: getTmuxPathMock,
|
||||
return [call[0], toStringArray(call[1])]
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSpawnTmuxSession(): Promise<typeof import("./session-spawn").spawnTmuxSession> {
|
||||
const module = await import(`${sessionSpawnSpecifier}?test=${crypto.randomUUID()}`)
|
||||
return module.spawnTmuxSession
|
||||
function getSpawnCommand(): string {
|
||||
const newSessionCall = getRunTmuxCommandCall(2)
|
||||
const newSessionCommand = newSessionCall[1][newSessionCall[1].length - 1]
|
||||
if (newSessionCommand === undefined) {
|
||||
throw new Error("Expected new-session command")
|
||||
}
|
||||
|
||||
return newSessionCommand
|
||||
}
|
||||
|
||||
return { deps, getRunTmuxCommandCall, getSpawnCommand }
|
||||
}
|
||||
|
||||
describe("spawnTmuxSession runner integration", () => {
|
||||
beforeEach(() => {
|
||||
mock.restore()
|
||||
runTmuxCommandMock.mockClear()
|
||||
isInsideTmuxMock.mockClear()
|
||||
isServerRunningMock.mockClear()
|
||||
getTmuxPathMock.mockClear()
|
||||
logMock.mockClear()
|
||||
|
||||
const tmuxCommandResults: TmuxCommandResult[] = [
|
||||
{ success: true, output: "120,40", stdout: "120,40", stderr: "", exitCode: 0 },
|
||||
{ success: false, output: "", stdout: "", stderr: "", exitCode: 1 },
|
||||
{ success: true, output: "%42", stdout: "%42", stderr: "", exitCode: 0 },
|
||||
{ success: true, output: "", stdout: "", stderr: "", exitCode: 0 },
|
||||
]
|
||||
runTmuxCommandMock.mockImplementation(async (): Promise<TmuxCommandResult> => {
|
||||
const nextResult = tmuxCommandResults.shift()
|
||||
if (!nextResult) {
|
||||
throw new Error("No more tmux command results configured")
|
||||
}
|
||||
return nextResult
|
||||
})
|
||||
isInsideTmuxMock.mockReturnValue(true)
|
||||
isServerRunningMock.mockResolvedValue(true)
|
||||
getTmuxPathMock.mockResolvedValue("sh")
|
||||
})
|
||||
|
||||
it("#given source pane available #when spawnTmuxSession called #then delegates display, has-session, new-session, and select-pane to shared runner", async () => {
|
||||
// given
|
||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
||||
const harness = createHarness()
|
||||
const directory = "/tmp/omo-project/(session)"
|
||||
|
||||
// when
|
||||
const result = await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", directory, "%0", createDeps())
|
||||
const result = await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", directory, "%0", harness.deps)
|
||||
|
||||
// then
|
||||
const displayCall = getRunTmuxCommandCall(0)
|
||||
const hasSessionCall = getRunTmuxCommandCall(1)
|
||||
const newSessionCall = getRunTmuxCommandCall(2)
|
||||
const selectPaneCall = getRunTmuxCommandCall(3)
|
||||
expect(result).toEqual({ success: true, paneId: "%42" })
|
||||
const displayCall = harness.getRunTmuxCommandCall(0)
|
||||
const hasSessionCall = harness.getRunTmuxCommandCall(1)
|
||||
const newSessionCall = harness.getRunTmuxCommandCall(2)
|
||||
const selectPaneCall = harness.getRunTmuxCommandCall(3)
|
||||
expect(displayCall[1]).toEqual(["display", "-p", "-t", "%0", "#{window_width},#{window_height}"])
|
||||
expect(hasSessionCall[1][0]).toBe("has-session")
|
||||
expect(hasSessionCall[1][1]).toBe("-t")
|
||||
@@ -122,39 +102,39 @@ describe("spawnTmuxSession runner integration", () => {
|
||||
expect(newSessionCall[1].slice(0, 4)).toEqual(["new-session", "-d", "-s", newSessionCall[1][3]])
|
||||
expect(String(newSessionCall[1][3]).startsWith("omo-agents-")).toBe(true)
|
||||
expect(selectPaneCall[1]).toEqual(["select-pane", "-t", "%42", "-T", "omo-subagent-worker"])
|
||||
expect(getSpawnCommand()).toContain(` --dir '${directory}'`)
|
||||
expect(harness.getSpawnCommand()).toContain(` --dir '${directory}'`)
|
||||
})
|
||||
|
||||
it("#given directory with spaces #when spawnTmuxSession called #then wraps --dir value in single quotes", async () => {
|
||||
// given
|
||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
||||
const harness = createHarness()
|
||||
|
||||
// when
|
||||
await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path with spaces/here", "%0", createDeps())
|
||||
await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path with spaces/here", "%0", harness.deps)
|
||||
|
||||
// then
|
||||
expect(getSpawnCommand()).toContain("--dir '/path with spaces/here'")
|
||||
expect(harness.getSpawnCommand()).toContain("--dir '/path with spaces/here'")
|
||||
})
|
||||
|
||||
it("#given empty directory #when spawnTmuxSession called #then falls back to process cwd", async () => {
|
||||
// given
|
||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
||||
const harness = createHarness()
|
||||
|
||||
// when
|
||||
await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "", "%0", createDeps())
|
||||
await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "", "%0", harness.deps)
|
||||
|
||||
// then
|
||||
expect(getSpawnCommand()).toContain(`--dir '${process.cwd()}'`)
|
||||
expect(harness.getSpawnCommand()).toContain(`--dir '${process.cwd()}'`)
|
||||
})
|
||||
|
||||
it("#given directory with single quotes #when spawnTmuxSession called #then escapes the value with POSIX-safe single quoting", async () => {
|
||||
// given
|
||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
||||
const harness = createHarness()
|
||||
|
||||
// when
|
||||
await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path/with'quote", "%0", createDeps())
|
||||
await spawnTmuxSession("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path/with'quote", "%0", harness.deps)
|
||||
|
||||
// then
|
||||
expect(getSpawnCommand()).toContain("--dir '/path/with'\\''quote'")
|
||||
expect(harness.getSpawnCommand()).toContain("--dir '/path/with'\\''quote'")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { beforeEach, describe, expect, it, mock } from "bun:test"
|
||||
import { describe, expect, it } from "bun:test"
|
||||
|
||||
import type { TmuxConfig } from "../../../config/schema"
|
||||
import type { TmuxCommandResult } from "../runner"
|
||||
|
||||
const windowSpawnSpecifier = import.meta.resolve("./window-spawn")
|
||||
import { spawnTmuxWindow } from "./window-spawn"
|
||||
|
||||
const enabledTmuxConfig = {
|
||||
enabled: true,
|
||||
@@ -14,17 +13,7 @@ const enabledTmuxConfig = {
|
||||
isolation: "inline",
|
||||
} satisfies TmuxConfig
|
||||
|
||||
const runTmuxCommandMock = mock(async (): Promise<TmuxCommandResult> => ({
|
||||
success: true,
|
||||
output: "%42",
|
||||
stdout: "%42",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
}))
|
||||
const isInsideTmuxMock = mock((): boolean => true)
|
||||
const isServerRunningMock = mock(async (): Promise<boolean> => true)
|
||||
const getTmuxPathMock = mock(async (): Promise<string | null> => "sh")
|
||||
const logMock = mock(() => undefined)
|
||||
type SpawnTmuxWindowDeps = NonNullable<Parameters<typeof spawnTmuxWindow>[5]>
|
||||
|
||||
function toStringArray(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
@@ -38,114 +27,102 @@ function toStringArray(value: unknown): string[] {
|
||||
return items
|
||||
}
|
||||
|
||||
function getRunTmuxCommandCall(index: number): [string, string[]] {
|
||||
const call = Reflect.get(runTmuxCommandMock.mock.calls, index)
|
||||
const command = Reflect.get(call, 0)
|
||||
const args = Reflect.get(call, 1)
|
||||
if (!Array.isArray(call) || typeof command !== "string" || !Array.isArray(args)) {
|
||||
throw new Error(`Expected tmux runner call at index ${index}`)
|
||||
}
|
||||
|
||||
return [command, toStringArray(args)]
|
||||
function defaultTmuxCommandResults(): TmuxCommandResult[] {
|
||||
return [
|
||||
{ success: true, output: "%42", stdout: "%42", stderr: "", exitCode: 0 },
|
||||
{ success: true, output: "", stdout: "", stderr: "", exitCode: 0 },
|
||||
]
|
||||
}
|
||||
|
||||
function getNewWindowCommand(): string {
|
||||
const firstCall = getRunTmuxCommandCall(0)
|
||||
const newWindowCommand = firstCall[1][7]
|
||||
if (newWindowCommand === undefined) {
|
||||
throw new Error("Expected new-window command")
|
||||
function createHarness() {
|
||||
const calls: Array<[string, string[]]> = []
|
||||
const tmuxCommandResults = defaultTmuxCommandResults()
|
||||
const runTmuxCommand = async (command: string, args: string[]): Promise<TmuxCommandResult> => {
|
||||
calls.push([command, [...args]])
|
||||
const nextResult = tmuxCommandResults.shift()
|
||||
if (!nextResult) {
|
||||
throw new Error("No more tmux command results configured")
|
||||
}
|
||||
return nextResult
|
||||
}
|
||||
const deps: SpawnTmuxWindowDeps = {
|
||||
log: () => undefined,
|
||||
runTmuxCommand,
|
||||
isInsideTmux: (): boolean => true,
|
||||
isServerRunning: async (): Promise<boolean> => true,
|
||||
getTmuxPath: async (): Promise<string | null> => "sh",
|
||||
}
|
||||
|
||||
return newWindowCommand
|
||||
}
|
||||
function getRunTmuxCommandCall(index: number): [string, string[]] {
|
||||
const call = calls[index]
|
||||
if (!call) {
|
||||
throw new Error(`Expected tmux runner call at index ${index}`)
|
||||
}
|
||||
|
||||
function createDeps(): NonNullable<Parameters<typeof import("./window-spawn").spawnTmuxWindow>[5]> {
|
||||
return {
|
||||
log: logMock,
|
||||
runTmuxCommand: runTmuxCommandMock,
|
||||
isInsideTmux: isInsideTmuxMock,
|
||||
isServerRunning: isServerRunningMock,
|
||||
getTmuxPath: getTmuxPathMock,
|
||||
return [call[0], toStringArray(call[1])]
|
||||
}
|
||||
}
|
||||
|
||||
async function loadSpawnTmuxWindow(): Promise<typeof import("./window-spawn").spawnTmuxWindow> {
|
||||
const module = await import(`${windowSpawnSpecifier}?test=${crypto.randomUUID()}`)
|
||||
return module.spawnTmuxWindow
|
||||
function getNewWindowCommand(): string {
|
||||
const firstCall = getRunTmuxCommandCall(0)
|
||||
const newWindowCommand = firstCall[1][7]
|
||||
if (newWindowCommand === undefined) {
|
||||
throw new Error("Expected new-window command")
|
||||
}
|
||||
|
||||
return newWindowCommand
|
||||
}
|
||||
|
||||
return { deps, getRunTmuxCommandCall, getNewWindowCommand }
|
||||
}
|
||||
|
||||
describe("spawnTmuxWindow runner integration", () => {
|
||||
beforeEach(() => {
|
||||
mock.restore()
|
||||
runTmuxCommandMock.mockClear()
|
||||
isInsideTmuxMock.mockClear()
|
||||
isServerRunningMock.mockClear()
|
||||
getTmuxPathMock.mockClear()
|
||||
logMock.mockClear()
|
||||
|
||||
const tmuxCommandResults: TmuxCommandResult[] = [
|
||||
{ success: true, output: "%42", stdout: "%42", stderr: "", exitCode: 0 },
|
||||
{ success: true, output: "", stdout: "", stderr: "", exitCode: 0 },
|
||||
]
|
||||
runTmuxCommandMock.mockImplementation(async (): Promise<TmuxCommandResult> => {
|
||||
const nextResult = tmuxCommandResults.shift()
|
||||
if (!nextResult) {
|
||||
throw new Error("No more tmux command results configured")
|
||||
}
|
||||
return nextResult
|
||||
})
|
||||
isInsideTmuxMock.mockReturnValue(true)
|
||||
isServerRunningMock.mockResolvedValue(true)
|
||||
getTmuxPathMock.mockResolvedValue("sh")
|
||||
})
|
||||
|
||||
it("#given healthy tmux environment #when spawnTmuxWindow called #then delegates new-window and select-pane to shared runner", async () => {
|
||||
// given
|
||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
||||
const harness = createHarness()
|
||||
const directory = "/tmp/omo-project/(window)"
|
||||
|
||||
// when
|
||||
const result = await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", directory, createDeps())
|
||||
const result = await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", directory, harness.deps)
|
||||
|
||||
// then
|
||||
const firstCall = getRunTmuxCommandCall(0)
|
||||
const secondCall = getRunTmuxCommandCall(1)
|
||||
const firstCall = harness.getRunTmuxCommandCall(0)
|
||||
const secondCall = harness.getRunTmuxCommandCall(1)
|
||||
expect(result).toEqual({ success: true, paneId: "%42" })
|
||||
expect(firstCall[1].slice(0, 7)).toEqual(["new-window", "-d", "-n", "omo-agents", "-P", "-F", "#{pane_id}"])
|
||||
expect(secondCall[1]).toEqual(["select-pane", "-t", "%42", "-T", "omo-subagent-worker"])
|
||||
expect(getNewWindowCommand()).toContain(` --dir '${directory}'`)
|
||||
expect(harness.getNewWindowCommand()).toContain(` --dir '${directory}'`)
|
||||
})
|
||||
|
||||
it("#given directory with spaces #when spawnTmuxWindow called #then wraps --dir value in single quotes", async () => {
|
||||
// given
|
||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
||||
const harness = createHarness()
|
||||
|
||||
// when
|
||||
await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path with spaces/here", createDeps())
|
||||
await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path with spaces/here", harness.deps)
|
||||
|
||||
// then
|
||||
expect(getNewWindowCommand()).toContain("--dir '/path with spaces/here'")
|
||||
expect(harness.getNewWindowCommand()).toContain("--dir '/path with spaces/here'")
|
||||
})
|
||||
|
||||
it("#given empty directory #when spawnTmuxWindow called #then falls back to process cwd", async () => {
|
||||
// given
|
||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
||||
const harness = createHarness()
|
||||
|
||||
// when
|
||||
await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "", createDeps())
|
||||
await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "", harness.deps)
|
||||
|
||||
// then
|
||||
expect(getNewWindowCommand()).toContain(`--dir '${process.cwd()}'`)
|
||||
expect(harness.getNewWindowCommand()).toContain(`--dir '${process.cwd()}'`)
|
||||
})
|
||||
|
||||
it("#given directory with single quotes #when spawnTmuxWindow called #then escapes the value with POSIX-safe single quoting", async () => {
|
||||
// given
|
||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
||||
const harness = createHarness()
|
||||
|
||||
// when
|
||||
await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path/with'quote", createDeps())
|
||||
await spawnTmuxWindow("session-1", "worker", enabledTmuxConfig, "http://127.0.0.1:1234", "/path/with'quote", harness.deps)
|
||||
|
||||
// then
|
||||
expect(getNewWindowCommand()).toContain("--dir '/path/with'\\''quote'")
|
||||
expect(harness.getNewWindowCommand()).toContain("--dir '/path/with'\\''quote'")
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user