test: run suite without split runner

This commit is contained in:
YeonGyu-Kim
2026-05-15 16:26:57 +09:00
parent 150ccefa05
commit d8f52aae7f
34 changed files with 627 additions and 889 deletions
+1 -8
View File
@@ -1,13 +1,6 @@
import { describe, expect, mock, test } from "bun:test"
import { describe, expect, test } from "bun:test"
import { resolveModelPipeline } from "./model-resolution-pipeline"
// Force test-runner isolation: files that import mock.module are auto-detected
// by run-ci-tests.ts and executed in their own bun process so they cannot be
// contaminated by (or contaminate) mock.module calls in other test files.
mock.module("./logger", () => ({
log: () => {},
}))
describe("resolveModelPipeline", () => {
test("does not return unused explicit user config metadata in override result", () => {
// given
+20 -1
View File
@@ -1,10 +1,29 @@
import { log } from "./logger"
import { log as writeLog } from "./logger"
import * as connectedProvidersCache from "./connected-providers-cache"
import { fuzzyMatchModel } from "./model-availability"
import type { FallbackEntry } from "./model-requirements"
import { transformModelForProvider } from "./provider-model-id-transform"
import { normalizeModel } from "./model-normalization"
type LogImplementation = typeof writeLog
let logImplementationForTesting: LogImplementation | undefined
function log(message: string, data?: unknown): void {
const logImplementation = logImplementationForTesting ?? writeLog
if (arguments.length === 1) {
logImplementation(message)
return
}
logImplementation(message, data)
}
export function _setModelResolutionLogImplementationForTesting(
logImplementation: LogImplementation | undefined,
): void {
logImplementationForTesting = logImplementation
}
export type ModelResolutionRequest = {
intent?: {
uiSelectedModel?: string
+12 -14
View File
@@ -1,12 +1,11 @@
import { describe, expect, test, spyOn, beforeEach, afterEach, mock } from "bun:test"
// Isolate from other tests that mock.module the logger (CI cross-contamination fix)
mock.module("./logger", () => ({ log: (..._args: unknown[]) => {} }))
import { resolveModel, resolveModelWithFallback, type ModelResolutionInput, type ExtendedModelResolutionInput, type ModelResolutionResult, type ModelSource } from "./model-resolver"
import * as logger from "./logger"
import { _setModelResolutionLogImplementationForTesting } from "./model-resolution-pipeline"
import * as connectedProvidersCache from "./connected-providers-cache"
const logMock = mock(() => {})
describe("resolveModel", () => {
describe("priority chain", () => {
test("returns userModel when all three are set", () => {
@@ -107,14 +106,13 @@ describe("resolveModel", () => {
})
describe("resolveModelWithFallback", () => {
let logSpy: ReturnType<typeof spyOn>
beforeEach(() => {
logSpy = spyOn(logger, "log")
logMock.mockClear()
_setModelResolutionLogImplementationForTesting(logMock)
})
afterEach(() => {
logSpy.mockRestore()
_setModelResolutionLogImplementationForTesting(undefined)
})
describe("Step 1: UI Selection (highest priority)", () => {
@@ -136,7 +134,7 @@ describe("resolveModelWithFallback", () => {
// then
expect(result!.model).toBe("opencode/big-pickle")
expect(result!.source).toBe("override")
expect(logSpy).toHaveBeenCalledWith("Model resolved via UI selection", { model: "opencode/big-pickle" })
expect(logMock).toHaveBeenCalledWith("Model resolved via UI selection", { model: "opencode/big-pickle" })
})
test("UI selection takes priority over config override", () => {
@@ -170,7 +168,7 @@ describe("resolveModelWithFallback", () => {
// then
expect(result!.model).toBe("anthropic/claude-opus-4-7")
expect(logSpy).toHaveBeenCalledWith("Model resolved via config override", { model: "anthropic/claude-opus-4-7" })
expect(logMock).toHaveBeenCalledWith("Model resolved via config override", { model: "anthropic/claude-opus-4-7" })
})
test("empty string uiSelectedModel falls through to config override", () => {
@@ -208,7 +206,7 @@ describe("resolveModelWithFallback", () => {
// then
expect(result!.model).toBe("anthropic/claude-opus-4-7")
expect(result!.source).toBe("override")
expect(logSpy).toHaveBeenCalledWith("Model resolved via config override", { model: "anthropic/claude-opus-4-7" })
expect(logMock).toHaveBeenCalledWith("Model resolved via config override", { model: "anthropic/claude-opus-4-7" })
})
test("override takes priority even if model not in availableModels", () => {
@@ -284,7 +282,7 @@ describe("resolveModelWithFallback", () => {
// then
expect(result!.model).toBe("github-copilot/claude-opus-4-7-preview")
expect(result!.source).toBe("provider-fallback")
expect(logSpy).toHaveBeenCalledWith("Model resolved via fallback chain (availability confirmed)", {
expect(logMock).toHaveBeenCalledWith("Model resolved via fallback chain (availability confirmed)", {
provider: "github-copilot",
model: "claude-opus-4-7",
match: "github-copilot/claude-opus-4-7-preview",
@@ -410,7 +408,7 @@ describe("resolveModelWithFallback", () => {
// then - should find glm-5 from opencode via cross-provider fuzzy match
expect(result!.model).toBe("opencode/glm-5")
expect(result!.source).toBe("provider-fallback")
expect(logSpy).toHaveBeenCalledWith("Model resolved via fallback chain (cross-provider fuzzy match)", {
expect(logMock).toHaveBeenCalledWith("Model resolved via fallback chain (cross-provider fuzzy match)", {
model: "glm-5",
match: "opencode/glm-5",
variant: undefined,
@@ -490,7 +488,7 @@ describe("resolveModelWithFallback", () => {
// then
expect(result!.model).toBe("google/gemini-3.1-pro")
expect(result!.source).toBe("system-default")
expect(logSpy).toHaveBeenCalledWith("No available model found in fallback chain, falling through to system default")
expect(logMock).toHaveBeenCalledWith("No available model found in fallback chain, falling through to system default")
})
test("returns undefined when availableModels empty and no connected providers cache exists", () => {
+39 -26
View File
@@ -1,20 +1,25 @@
import { describe, it, expect, vi, beforeEach } from "bun:test"
import { getServerBaseUrl, patchPart, deletePart } from "./opencode-http-api"
import { describe, it, expect, mock, beforeEach } from "bun:test"
// Mock fetch globally
const mockFetch = vi.fn()
global.fetch = mockFetch
type OpencodeHttpApi = typeof import("./opencode-http-api")
// Mock log
vi.mock("./logger", () => ({
log: vi.fn(),
}))
const opencodeHttpApiSpecifier = import.meta.resolve("./opencode-http-api")
import { log } from "./logger"
const log = mock(() => {})
const getServerBasicAuthHeader = mock(() => "Basic b3BlbmNvZGU6dGVzdHBhc3N3b3Jk")
const fetchImplementation = mock(async (): Promise<Response> => new Response(null, { status: 200 }))
async function loadOpencodeHttpApi(): Promise<OpencodeHttpApi> {
const opencodeHttpApi = await import(`${opencodeHttpApiSpecifier}?test=${crypto.randomUUID()}`)
opencodeHttpApi._setFetchImplementationForTesting(fetchImplementation)
opencodeHttpApi._setLogImplementationForTesting(log)
opencodeHttpApi._setServerBasicAuthHeaderResolverForTesting(getServerBasicAuthHeader)
return opencodeHttpApi
}
describe("getServerBaseUrl", () => {
it("returns baseUrl from client._client.getConfig().baseUrl", () => {
it("returns baseUrl from client._client.getConfig().baseUrl", async () => {
// given
const { getServerBaseUrl } = await loadOpencodeHttpApi()
const mockClient = {
_client: {
getConfig: () => ({ baseUrl: "https://api.example.com" }),
@@ -28,8 +33,9 @@ describe("getServerBaseUrl", () => {
expect(result).toBe("https://api.example.com")
})
it("returns baseUrl from client.session._client.getConfig().baseUrl when first attempt fails", () => {
it("returns baseUrl from client.session._client.getConfig().baseUrl when first attempt fails", async () => {
// given
const { getServerBaseUrl } = await loadOpencodeHttpApi()
const mockClient = {
_client: {
getConfig: () => ({}),
@@ -48,8 +54,9 @@ describe("getServerBaseUrl", () => {
expect(result).toBe("https://session.example.com")
})
it("returns null for incompatible client", () => {
it("returns null for incompatible client", async () => {
// given
const { getServerBaseUrl } = await loadOpencodeHttpApi()
const mockClient = {}
// when
@@ -62,14 +69,16 @@ describe("getServerBaseUrl", () => {
describe("patchPart", () => {
beforeEach(() => {
vi.clearAllMocks()
mockFetch.mockResolvedValue({ ok: true })
process.env.OPENCODE_SERVER_PASSWORD = "testpassword"
process.env.OPENCODE_SERVER_USERNAME = "opencode"
log.mockClear()
getServerBasicAuthHeader.mockClear()
getServerBasicAuthHeader.mockReturnValue("Basic b3BlbmNvZGU6dGVzdHBhc3N3b3Jk")
fetchImplementation.mockClear()
fetchImplementation.mockResolvedValue(new Response(null, { status: 200 }))
})
it("constructs correct URL and sends PATCH with auth", async () => {
// given
const { patchPart } = await loadOpencodeHttpApi()
const mockClient = {
_client: {
getConfig: () => ({ baseUrl: "https://api.example.com" }),
@@ -85,7 +94,7 @@ describe("patchPart", () => {
// then
expect(result).toBe(true)
expect(mockFetch).toHaveBeenCalledWith(
expect(fetchImplementation).toHaveBeenCalledWith(
"https://api.example.com/session/ses123/message/msg456/part/part789",
expect.objectContaining({
method: "PATCH",
@@ -101,12 +110,13 @@ describe("patchPart", () => {
it("returns false on network error", async () => {
// given
const { patchPart } = await loadOpencodeHttpApi()
const mockClient = {
_client: {
getConfig: () => ({ baseUrl: "https://api.example.com" }),
},
}
mockFetch.mockRejectedValue(new Error("Network error"))
fetchImplementation.mockRejectedValue(new Error("Network error"))
// when
const result = await patchPart(mockClient, "ses123", "msg456", "part789", {})
@@ -122,14 +132,16 @@ describe("patchPart", () => {
describe("deletePart", () => {
beforeEach(() => {
vi.clearAllMocks()
mockFetch.mockResolvedValue({ ok: true })
process.env.OPENCODE_SERVER_PASSWORD = "testpassword"
process.env.OPENCODE_SERVER_USERNAME = "opencode"
log.mockClear()
getServerBasicAuthHeader.mockClear()
getServerBasicAuthHeader.mockReturnValue("Basic b3BlbmNvZGU6dGVzdHBhc3N3b3Jk")
fetchImplementation.mockClear()
fetchImplementation.mockResolvedValue(new Response(null, { status: 200 }))
})
it("constructs correct URL and sends DELETE", async () => {
// given
const { deletePart } = await loadOpencodeHttpApi()
const mockClient = {
_client: {
getConfig: () => ({ baseUrl: "https://api.example.com" }),
@@ -144,7 +156,7 @@ describe("deletePart", () => {
// then
expect(result).toBe(true)
expect(mockFetch).toHaveBeenCalledWith(
expect(fetchImplementation).toHaveBeenCalledWith(
"https://api.example.com/session/ses123/message/msg456/part/part789",
expect.objectContaining({
method: "DELETE",
@@ -158,12 +170,13 @@ describe("deletePart", () => {
it("returns false on non-ok response", async () => {
// given
const { deletePart } = await loadOpencodeHttpApi()
const mockClient = {
_client: {
getConfig: () => ({ baseUrl: "https://api.example.com" }),
},
}
mockFetch.mockResolvedValue({ ok: false, status: 404 })
fetchImplementation.mockResolvedValue(new Response(null, { status: 404 }))
// when
const result = await deletePart(mockClient, "ses123", "msg456", "part789")
@@ -175,4 +188,4 @@ describe("deletePart", () => {
url: "https://api.example.com/session/ses123/message/msg456/part/part789",
})
})
})
})
+48 -15
View File
@@ -1,8 +1,41 @@
import { getServerBasicAuthHeader } from "./opencode-server-auth"
import { log } from "./logger"
import { getServerBasicAuthHeader as resolveServerBasicAuthHeader } from "./opencode-server-auth"
import { log as writeLog } from "./logger"
import { isRecord } from "./record-type-guard"
type UnknownRecord = Record<string, unknown>
type FetchImplementation = typeof fetch
type LogImplementation = typeof writeLog
type ServerBasicAuthHeaderResolver = typeof resolveServerBasicAuthHeader
let fetchImplementationForTesting: FetchImplementation | undefined
let logImplementationForTesting: LogImplementation | undefined
let serverBasicAuthHeaderResolverForTesting: ServerBasicAuthHeaderResolver | undefined
function getFetchImplementation(): FetchImplementation {
return fetchImplementationForTesting ?? fetch
}
function getLogImplementation(): LogImplementation {
return logImplementationForTesting ?? writeLog
}
function getServerBasicAuthHeaderImplementation(): ServerBasicAuthHeaderResolver {
return serverBasicAuthHeaderResolverForTesting ?? resolveServerBasicAuthHeader
}
export function _setFetchImplementationForTesting(fetchImplementation: FetchImplementation | undefined): void {
fetchImplementationForTesting = fetchImplementation
}
export function _setLogImplementationForTesting(logImplementation: LogImplementation | undefined): void {
logImplementationForTesting = logImplementation
}
export function _setServerBasicAuthHeaderResolverForTesting(
resolver: ServerBasicAuthHeaderResolver | undefined,
): void {
serverBasicAuthHeaderResolverForTesting = resolver
}
function getInternalClient(client: unknown): UnknownRecord | null {
if (!isRecord(client)) {
@@ -61,20 +94,20 @@ export async function patchPart(
): Promise<boolean> {
const baseUrl = getServerBaseUrl(client)
if (!baseUrl) {
log("[opencode-http-api] Could not extract baseUrl from client")
getLogImplementation()("[opencode-http-api] Could not extract baseUrl from client")
return false
}
const auth = getServerBasicAuthHeader()
const auth = getServerBasicAuthHeaderImplementation()()
if (!auth) {
log("[opencode-http-api] No auth header available")
getLogImplementation()("[opencode-http-api] No auth header available")
return false
}
const url = `${baseUrl}/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}/part/${encodeURIComponent(partID)}`
try {
const response = await fetch(url, {
const response = await getFetchImplementation()(url, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
@@ -85,14 +118,14 @@ export async function patchPart(
})
if (!response.ok) {
log("[opencode-http-api] PATCH failed", { status: response.status, url })
getLogImplementation()("[opencode-http-api] PATCH failed", { status: response.status, url })
return false
}
return true
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
log("[opencode-http-api] PATCH error", { message, url })
getLogImplementation()("[opencode-http-api] PATCH error", { message, url })
return false
}
}
@@ -105,20 +138,20 @@ export async function deletePart(
): Promise<boolean> {
const baseUrl = getServerBaseUrl(client)
if (!baseUrl) {
log("[opencode-http-api] Could not extract baseUrl from client")
getLogImplementation()("[opencode-http-api] Could not extract baseUrl from client")
return false
}
const auth = getServerBasicAuthHeader()
const auth = getServerBasicAuthHeaderImplementation()()
if (!auth) {
log("[opencode-http-api] No auth header available")
getLogImplementation()("[opencode-http-api] No auth header available")
return false
}
const url = `${baseUrl}/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}/part/${encodeURIComponent(partID)}`
try {
const response = await fetch(url, {
const response = await getFetchImplementation()(url, {
method: "DELETE",
headers: {
"Authorization": auth,
@@ -127,14 +160,14 @@ export async function deletePart(
})
if (!response.ok) {
log("[opencode-http-api] DELETE failed", { status: response.status, url })
getLogImplementation()("[opencode-http-api] DELETE failed", { status: response.status, url })
return false
}
return true
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
log("[opencode-http-api] DELETE error", { message, url })
getLogImplementation()("[opencode-http-api] DELETE error", { message, url })
return false
}
}
}
+48 -48
View File
@@ -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", () => {
+35 -6
View File
@@ -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'")
})
})
+56 -79
View File
@@ -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'")
})
})