test: run suite without split runner
This commit is contained in:
+17
-60
@@ -32,70 +32,27 @@ jobs:
|
|||||||
echo "PR targets '${BASE_REF}' branch - OK"
|
echo "PR targets '${BASE_REF}' branch - OK"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
test-isolated:
|
|
||||||
name: Isolated tests (${{ matrix.shard }})
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
shard: [0, 1, 2, 3]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: oven-sh/setup-bun@v2
|
|
||||||
with:
|
|
||||||
bun-version: "1.3.12"
|
|
||||||
|
|
||||||
- uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.bun/install/cache
|
|
||||||
key: ${{ runner.os }}-bun-1.3.12-${{ hashFiles('bun.lock') }}
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
env:
|
|
||||||
BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/napi"
|
|
||||||
|
|
||||||
- name: Run isolated tests
|
|
||||||
run: bun run script/run-ci-tests.ts --phase=isolated --shard-count=4 --shard-index=${{ matrix.shard }}
|
|
||||||
|
|
||||||
test-shared:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: oven-sh/setup-bun@v2
|
|
||||||
with:
|
|
||||||
bun-version: "1.3.12"
|
|
||||||
|
|
||||||
- uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.bun/install/cache
|
|
||||||
key: ${{ runner.os }}-bun-1.3.12-${{ hashFiles('bun.lock') }}
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: bun install --frozen-lockfile
|
|
||||||
env:
|
|
||||||
BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/napi"
|
|
||||||
|
|
||||||
- name: Run shared tests
|
|
||||||
run: bun run script/run-ci-tests.ts --phase=shared
|
|
||||||
|
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [test-isolated, test-shared]
|
|
||||||
if: ${{ always() }}
|
|
||||||
steps:
|
steps:
|
||||||
- name: Verify test shards passed
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: oven-sh/setup-bun@v2
|
||||||
|
with:
|
||||||
|
bun-version: "1.3.12"
|
||||||
|
|
||||||
|
- uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.bun/install/cache
|
||||||
|
key: ${{ runner.os }}-bun-1.3.12-${{ hashFiles('bun.lock') }}
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
env:
|
env:
|
||||||
ISOLATED_RESULT: ${{ needs.test-isolated.result }}
|
BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/napi"
|
||||||
SHARED_RESULT: ${{ needs.test-shared.result }}
|
|
||||||
run: |
|
- name: Run tests
|
||||||
if [ "$ISOLATED_RESULT" != "success" ] || [ "$SHARED_RESULT" != "success" ]; then
|
run: bun test
|
||||||
echo "::error::test-isolated=${ISOLATED_RESULT}, test-shared=${SHARED_RESULT}"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "All test shards passed"
|
|
||||||
|
|
||||||
typecheck:
|
typecheck:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ jobs:
|
|||||||
BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/napi"
|
BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/napi"
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: bun run script/run-ci-tests.ts
|
run: bun test
|
||||||
|
|
||||||
typecheck:
|
typecheck:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ Schema autocomplete: `"$schema": "https://raw.githubusercontent.com/code-yeongyu
|
|||||||
- **Runtime:** Bun only (1.3.11 in CI). Never npm/yarn/pnpm.
|
- **Runtime:** Bun only (1.3.11 in CI). Never npm/yarn/pnpm.
|
||||||
- **TypeScript:** strict mode, ESNext, bundler moduleResolution, `bun-types` (never `@types/node`).
|
- **TypeScript:** strict mode, ESNext, bundler moduleResolution, `bun-types` (never `@types/node`).
|
||||||
- **Tests:** Bun test (`bun:test`), co-located `*.test.ts`, given/when/then style — nested `describe` with `#given`/`#when`/`#then` prefixes, or inline `// given` / `// when` / `// then` comments. Never Arrange-Act-Assert comments.
|
- **Tests:** Bun test (`bun:test`), co-located `*.test.ts`, given/when/then style — nested `describe` with `#given`/`#when`/`#then` prefixes, or inline `// given` / `// when` / `// then` comments. Never Arrange-Act-Assert comments.
|
||||||
- **CI test split:** `script/run-ci-tests.ts` auto-detects `mock.module()` and isolates those tests in separate processes.
|
- **CI tests:** plain `bun test` runs the root Bun suite in one process; no sharding or split isolation runner.
|
||||||
- **Test setup:** `test-setup.ts` preloaded via `bunfig.toml` resets session/cache state between tests.
|
- **Test setup:** `test-setup.ts` preloaded via `bunfig.toml` resets session/cache state between tests.
|
||||||
- **Factory pattern:** `createXXX()` for all tools, hooks, agents.
|
- **Factory pattern:** `createXXX()` for all tools, hooks, agents.
|
||||||
- **File naming:** kebab-case for files and directories.
|
- **File naming:** kebab-case for files and directories.
|
||||||
@@ -216,7 +216,7 @@ Schema autocomplete: `"$schema": "https://raw.githubusercontent.com/code-yeongyu
|
|||||||
## COMMANDS
|
## COMMANDS
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bun test # Bun test suite (auto-split mock-heavy tests via script/run-ci-tests.ts)
|
bun test # Root Bun test suite in one process
|
||||||
bun run build # Build plugin (ESM bundle + .d.ts + cli bundle + schema generation)
|
bun run build # Build plugin (ESM bundle + .d.ts + cli bundle + schema generation)
|
||||||
bun run build:all # Build + 11 platform binaries
|
bun run build:all # Build + 11 platform binaries
|
||||||
bun run build:schema # Regenerate assets/oh-my-opencode.schema.json
|
bun run build:schema # Regenerate assets/oh-my-opencode.schema.json
|
||||||
@@ -233,7 +233,7 @@ bunx oh-my-opencode mcp-oauth login <server-url> # Tier-3 MCP OAuth (PKCE + DCR
|
|||||||
|
|
||||||
| Workflow | Trigger | Purpose |
|
| Workflow | Trigger | Purpose |
|
||||||
|----------|---------|---------|
|
|----------|---------|---------|
|
||||||
| `ci.yml` | push/PR to master/dev | Tests (split: mock-heavy isolated + batch), typecheck, build, schema auto-commit |
|
| `ci.yml` | push/PR to master/dev | Tests, typecheck, build, schema auto-commit |
|
||||||
| `publish.yml` | manual dispatch | Version bump, dual npm publish (`oh-my-opencode` + `oh-my-openagent`), platform binaries, GitHub release |
|
| `publish.yml` | manual dispatch | Version bump, dual npm publish (`oh-my-opencode` + `oh-my-openagent`), platform binaries, GitHub release |
|
||||||
| `publish-platform.yml` | called by publish.yml | 11 platform binaries via `bun compile` (darwin/linux/windows) |
|
| `publish-platform.yml` | called by publish.yml | 11 platform binaries via `bun compile` (darwin/linux/windows) |
|
||||||
| `sisyphus-agent.yml` | @mention or manual dispatch | AI agent handles issues/PRs |
|
| `sisyphus-agent.yml` | @mention or manual dispatch | AI agent handles issues/PRs |
|
||||||
@@ -252,7 +252,7 @@ bunx oh-my-opencode mcp-oauth login <server-url> # Tier-3 MCP OAuth (PKCE + DCR
|
|||||||
- **Two fallback systems:** `model-fallback` (proactive, chat.params, hardcoded chains) vs `runtime-fallback` (reactive, session.error, configurable per-category/agent).
|
- **Two fallback systems:** `model-fallback` (proactive, chat.params, hardcoded chains) vs `runtime-fallback` (reactive, session.error, configurable per-category/agent).
|
||||||
- **Config migration:** idempotent via `_migrations` tracking, atomic writes with timestamped backups.
|
- **Config migration:** idempotent via `_migrations` tracking, atomic writes with timestamped backups.
|
||||||
- **Build:** `bun build` (ESM) + `tsc --emitDeclarationOnly`, externals: `@ast-grep/napi`, `zod`.
|
- **Build:** `bun build` (ESM) + `tsc --emitDeclarationOnly`, externals: `@ast-grep/napi`, `zod`.
|
||||||
- **CI test isolation:** `script/run-ci-tests.ts` auto-isolates files using `mock.module()` (plus `src/openclaw/__tests__/reply-listener-discord.test.ts`) — they run in separate processes.
|
- **CI tests:** root tests run through plain `bun test`; `web/**` has its own package-level CI workflow.
|
||||||
- **122 barrel `index.ts` files** establish module boundaries.
|
- **122 barrel `index.ts` files** establish module boundaries.
|
||||||
- **Architecture rules** enforced via `.sisyphus/rules/modular-code-enforcement.md` (when present in workspace).
|
- **Architecture rules** enforced via `.sisyphus/rules/modular-code-enforcement.md` (when present in workspace).
|
||||||
- **Windows builds:** run on `windows-latest` (not cross-compiled) to avoid Bun segfaults.
|
- **Windows builds:** run on `windows-latest` (not cross-compiled) to avoid Bun segfaults.
|
||||||
|
|||||||
@@ -1,2 +1,3 @@
|
|||||||
[test]
|
[test]
|
||||||
preload = ["./test-setup.ts"]
|
preload = ["./test-setup.ts"]
|
||||||
|
pathIgnorePatterns = ["web/**"]
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@
|
|||||||
"test:model-capabilities": "bun test src/shared/model-capability-aliases.test.ts src/shared/model-capability-guardrails.test.ts src/shared/model-capabilities.test.ts src/cli/doctor/checks/model-resolution.test.ts --bail",
|
"test:model-capabilities": "bun test src/shared/model-capability-aliases.test.ts src/shared/model-capability-guardrails.test.ts src/shared/model-capabilities.test.ts src/cli/doctor/checks/model-resolution.test.ts --bail",
|
||||||
"typecheck": "tsgo --noEmit",
|
"typecheck": "tsgo --noEmit",
|
||||||
"typecheck:script": "tsgo --noEmit -p script/tsconfig.json",
|
"typecheck:script": "tsgo --noEmit -p script/tsconfig.json",
|
||||||
"test": "bun run script/run-ci-tests.ts"
|
"test": "bun test"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"opencode",
|
"opencode",
|
||||||
|
|||||||
@@ -7,18 +7,13 @@ const workflowChecks = [
|
|||||||
{
|
{
|
||||||
path: new URL("../.github/workflows/ci.yml", import.meta.url),
|
path: new URL("../.github/workflows/ci.yml", import.meta.url),
|
||||||
testRuns: [
|
testRuns: [
|
||||||
"run: bun run script/run-ci-tests.ts --phase=isolated --shard-count=4 --shard-index=${{ matrix.shard }}",
|
"run: bun test",
|
||||||
"run: bun run script/run-ci-tests.ts --phase=shared",
|
|
||||||
"if: ${{ always() }}",
|
|
||||||
"ISOLATED_RESULT: ${{ needs.test-isolated.result }}",
|
|
||||||
"SHARED_RESULT: ${{ needs.test-shared.result }}",
|
|
||||||
"echo \"::error::test-isolated=${ISOLATED_RESULT}, test-shared=${SHARED_RESULT}\"",
|
|
||||||
"run: bun test src/shared/dist-bundle-bun-globals.test.ts",
|
"run: bun test src/shared/dist-bundle-bun-globals.test.ts",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: new URL("../.github/workflows/publish.yml", import.meta.url),
|
path: new URL("../.github/workflows/publish.yml", import.meta.url),
|
||||||
testRuns: ["run: bun run script/run-ci-tests.ts"],
|
testRuns: ["run: bun test"],
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
|
||||||
import { selectCiTestTargets } from "./run-ci-tests"
|
|
||||||
|
|
||||||
describe("test script isolation", () => {
|
|
||||||
test("#given mock.module tests in the suite #then bun run test uses the isolated CI runner", async () => {
|
|
||||||
//#given
|
|
||||||
const packageJson = await Bun.file("package.json").json()
|
|
||||||
|
|
||||||
//#then
|
|
||||||
expect(packageJson.scripts.test).toBe("bun run script/run-ci-tests.ts")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("#given isolated test shards #when selecting targets #then shards are deterministic and complete", () => {
|
|
||||||
// given
|
|
||||||
const ciTestPlan = {
|
|
||||||
isolatedModuleMockFiles: [],
|
|
||||||
isolatedTestTargets: ["a.test.ts", "b.test.ts", "c.test.ts", "d.test.ts", "e.test.ts"],
|
|
||||||
sharedTestFiles: ["shared.test.ts"],
|
|
||||||
}
|
|
||||||
|
|
||||||
// when
|
|
||||||
const shardOne = selectCiTestTargets(ciTestPlan, { phase: "isolated", shardCount: 2, shardIndex: 0 })
|
|
||||||
const shardTwo = selectCiTestTargets(ciTestPlan, { phase: "isolated", shardCount: 2, shardIndex: 1 })
|
|
||||||
|
|
||||||
// then
|
|
||||||
expect(shardOne).toEqual({ isolatedTestTargets: ["a.test.ts", "c.test.ts", "e.test.ts"], sharedTestFiles: [] })
|
|
||||||
expect(shardTwo).toEqual({ isolatedTestTargets: ["b.test.ts", "d.test.ts"], sharedTestFiles: [] })
|
|
||||||
expect([...shardOne.isolatedTestTargets, ...shardTwo.isolatedTestTargets].sort()).toEqual(ciTestPlan.isolatedTestTargets)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("#given shared phase #when selecting targets #then only shared tests run", () => {
|
|
||||||
// given
|
|
||||||
const ciTestPlan = {
|
|
||||||
isolatedModuleMockFiles: [],
|
|
||||||
isolatedTestTargets: ["isolated.test.ts"],
|
|
||||||
sharedTestFiles: ["shared.test.ts"],
|
|
||||||
}
|
|
||||||
|
|
||||||
// when
|
|
||||||
const selectedTargets = selectCiTestTargets(ciTestPlan, { phase: "shared", shardCount: 1, shardIndex: 0 })
|
|
||||||
|
|
||||||
// then
|
|
||||||
expect(selectedTargets).toEqual({ isolatedTestTargets: [], sharedTestFiles: ["shared.test.ts"] })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,253 +0,0 @@
|
|||||||
/// <reference types="bun-types" />
|
|
||||||
|
|
||||||
type CiTestPlan = {
|
|
||||||
isolatedTestTargets: string[]
|
|
||||||
isolatedModuleMockFiles: string[]
|
|
||||||
sharedTestFiles: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
type CiTestPhase = "all" | "isolated" | "shared"
|
|
||||||
|
|
||||||
type CiTestRunOptions = {
|
|
||||||
phase: CiTestPhase
|
|
||||||
shardCount: number
|
|
||||||
shardIndex: number
|
|
||||||
}
|
|
||||||
|
|
||||||
type CiTestTargetSelection = {
|
|
||||||
isolatedTestTargets: string[]
|
|
||||||
sharedTestFiles: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
const TEST_ROOTS = ["bin", "script", "src"] as const
|
|
||||||
const MODULE_MOCK_PATTERN = "mock.module("
|
|
||||||
const ALWAYS_ISOLATED_TEST_FILES = [
|
|
||||||
"src/features/team-mode/team-mailbox/ack.test.ts",
|
|
||||||
"src/features/team-mode/team-mailbox/send.test.ts",
|
|
||||||
"src/features/team-mode/team-runtime/shutdown.test.ts",
|
|
||||||
"src/features/team-mode/team-runtime/status.test.ts",
|
|
||||||
"src/features/team-mode/team-state-store/resume.test.ts",
|
|
||||||
"src/features/team-mode/team-state-store/store.test.ts",
|
|
||||||
"src/features/boulder-state/storage.test.ts",
|
|
||||||
"src/hooks/anthropic-context-window-limit-recovery/aggressive-truncation-strategy.test.ts",
|
|
||||||
"src/hooks/session-notification-input-needed.test.ts",
|
|
||||||
"src/hooks/session-notification-sender.test.ts",
|
|
||||||
"src/hooks/session-notification.test.ts",
|
|
||||||
"src/openclaw/__tests__/reply-listener-discord.test.ts",
|
|
||||||
"src/tools/background-task/create-background-output.blocking.test.ts",
|
|
||||||
"src/tools/background-task/tools.test.ts",
|
|
||||||
"src/tools/interactive-bash/tmux-path-resolver.test.ts",
|
|
||||||
"src/tools/task/task-list.test.ts",
|
|
||||||
] as const
|
|
||||||
|
|
||||||
async function collectTestFiles(rootDirectory: string): Promise<string[]> {
|
|
||||||
const testFiles: string[] = []
|
|
||||||
|
|
||||||
for (const testRoot of TEST_ROOTS) {
|
|
||||||
const glob = new Bun.Glob("**/*.test.ts")
|
|
||||||
|
|
||||||
for await (const testFile of glob.scan({ cwd: `${rootDirectory}/${testRoot}` })) {
|
|
||||||
testFiles.push(`${testRoot}/${testFile}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return testFiles.sort((left, right) => left.localeCompare(right))
|
|
||||||
}
|
|
||||||
|
|
||||||
async function usesModuleMock(rootDirectory: string, testFile: string): Promise<boolean> {
|
|
||||||
const testContents = await Bun.file(`${rootDirectory}/${testFile}`).text()
|
|
||||||
return testContents.includes(MODULE_MOCK_PATTERN)
|
|
||||||
}
|
|
||||||
|
|
||||||
function toIsolatedTarget(testFile: string): string {
|
|
||||||
return testFile
|
|
||||||
}
|
|
||||||
|
|
||||||
function isCoveredByTarget(testFile: string, isolatedTarget: string): boolean {
|
|
||||||
return testFile === isolatedTarget || testFile.startsWith(`${isolatedTarget}/`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function collapseNestedTargets(isolatedTargets: string[]): string[] {
|
|
||||||
return isolatedTargets.filter((isolatedTarget) => {
|
|
||||||
return !isolatedTargets.some((otherTarget) => {
|
|
||||||
return otherTarget !== isolatedTarget && isolatedTarget.startsWith(`${otherTarget}/`)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function readFlagValue(args: string[], flagName: string): string | null {
|
|
||||||
const prefix = `${flagName}=`
|
|
||||||
const flag = args.find((arg) => arg.startsWith(prefix))
|
|
||||||
|
|
||||||
return flag?.slice(prefix.length) ?? null
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePhase(rawPhase: string | null): CiTestPhase {
|
|
||||||
if (rawPhase === null) {
|
|
||||||
return "all"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rawPhase === "all" || rawPhase === "isolated" || rawPhase === "shared") {
|
|
||||||
return rawPhase
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Invalid --phase value: ${rawPhase}. Expected all, isolated, or shared.`)
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePositiveIntegerFlag(args: string[], flagName: string, defaultValue: number): number {
|
|
||||||
const rawValue = readFlagValue(args, flagName)
|
|
||||||
if (rawValue === null) {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsedValue = Number(rawValue)
|
|
||||||
if (!Number.isInteger(parsedValue) || parsedValue < 1) {
|
|
||||||
throw new Error(`Invalid ${flagName} value: ${rawValue}. Expected a positive integer.`)
|
|
||||||
}
|
|
||||||
|
|
||||||
return parsedValue
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseNonNegativeIntegerFlag(args: string[], flagName: string, defaultValue: number): number {
|
|
||||||
const rawValue = readFlagValue(args, flagName)
|
|
||||||
if (rawValue === null) {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsedValue = Number(rawValue)
|
|
||||||
if (!Number.isInteger(parsedValue) || parsedValue < 0) {
|
|
||||||
throw new Error(`Invalid ${flagName} value: ${rawValue}. Expected a non-negative integer.`)
|
|
||||||
}
|
|
||||||
|
|
||||||
return parsedValue
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseCiTestRunOptions(args: string[]): CiTestRunOptions {
|
|
||||||
const phase = parsePhase(readFlagValue(args, "--phase"))
|
|
||||||
const shardCount = parsePositiveIntegerFlag(args, "--shard-count", 1)
|
|
||||||
const shardIndex = parseNonNegativeIntegerFlag(args, "--shard-index", 0)
|
|
||||||
|
|
||||||
if (shardIndex >= shardCount) {
|
|
||||||
throw new Error(`Invalid --shard-index value: ${shardIndex}. Expected a value less than --shard-count ${shardCount}.`)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shardCount > 1 && phase !== "isolated") {
|
|
||||||
throw new Error("Test sharding is only supported with --phase=isolated.")
|
|
||||||
}
|
|
||||||
|
|
||||||
return { phase, shardCount, shardIndex }
|
|
||||||
}
|
|
||||||
|
|
||||||
function selectShard(testTargets: string[], shardCount: number, shardIndex: number): string[] {
|
|
||||||
if (shardCount === 1) {
|
|
||||||
return testTargets
|
|
||||||
}
|
|
||||||
|
|
||||||
return testTargets.filter((_, index) => index % shardCount === shardIndex)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function selectCiTestTargets(ciTestPlan: CiTestPlan, options: CiTestRunOptions): CiTestTargetSelection {
|
|
||||||
const isolatedTestTargets = options.phase === "shared"
|
|
||||||
? []
|
|
||||||
: selectShard(ciTestPlan.isolatedTestTargets, options.shardCount, options.shardIndex)
|
|
||||||
const sharedTestFiles = options.phase === "isolated" ? [] : ciTestPlan.sharedTestFiles
|
|
||||||
|
|
||||||
return { isolatedTestTargets, sharedTestFiles }
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createCiTestPlan(rootDirectory: string = process.cwd()): Promise<CiTestPlan> {
|
|
||||||
const allTestFiles = await collectTestFiles(rootDirectory)
|
|
||||||
const isolatedModuleMockFiles: string[] = []
|
|
||||||
|
|
||||||
for (const testFile of allTestFiles) {
|
|
||||||
if (await usesModuleMock(rootDirectory, testFile)) {
|
|
||||||
isolatedModuleMockFiles.push(testFile)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const isolatedTestFiles = Array.from(
|
|
||||||
new Set([...isolatedModuleMockFiles, ...ALWAYS_ISOLATED_TEST_FILES.filter((testFile) => allTestFiles.includes(testFile))]),
|
|
||||||
)
|
|
||||||
const isolatedTestTargets = collapseNestedTargets(
|
|
||||||
isolatedTestFiles.map((testFile) => toIsolatedTarget(testFile)).sort((left, right) =>
|
|
||||||
left.localeCompare(right),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
const sharedTestFiles = allTestFiles.filter((testFile) => {
|
|
||||||
return !isolatedTestTargets.some((isolatedTarget) => isCoveredByTarget(testFile, isolatedTarget))
|
|
||||||
})
|
|
||||||
|
|
||||||
return {
|
|
||||||
isolatedTestTargets,
|
|
||||||
isolatedModuleMockFiles,
|
|
||||||
sharedTestFiles,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function runBunTest(testFiles: string[], label: string): Promise<void> {
|
|
||||||
if (testFiles.length === 0) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`::group::${label}`)
|
|
||||||
|
|
||||||
const args = testFiles.map((testFile) => {
|
|
||||||
if (testFile.includes("/") && !testFile.endsWith(".test.ts")) {
|
|
||||||
return [testFile, "!_auc-*/**/*.test.ts"]
|
|
||||||
}
|
|
||||||
|
|
||||||
return testFile
|
|
||||||
}).flat()
|
|
||||||
|
|
||||||
const command = ["bun", "test", ...args]
|
|
||||||
const spawnedProcess = Bun.spawn(command, {
|
|
||||||
cwd: process.cwd(),
|
|
||||||
stdin: "inherit",
|
|
||||||
stdout: "inherit",
|
|
||||||
stderr: "inherit",
|
|
||||||
})
|
|
||||||
const exitCode = await spawnedProcess.exited
|
|
||||||
console.log("::endgroup::")
|
|
||||||
|
|
||||||
if (exitCode !== 0) {
|
|
||||||
throw new Error(`Command failed: ${command.join(" ")}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main(): Promise<void> {
|
|
||||||
const options = parseCiTestRunOptions(process.argv.slice(2))
|
|
||||||
const ciTestPlan = await createCiTestPlan()
|
|
||||||
const selectedTargets = selectCiTestTargets(ciTestPlan, options)
|
|
||||||
|
|
||||||
console.log(
|
|
||||||
`Detected ${ciTestPlan.isolatedModuleMockFiles.length} mock.module() test files, ${ciTestPlan.isolatedTestTargets.length} isolated targets, and ${ciTestPlan.sharedTestFiles.length} shared test files.`,
|
|
||||||
)
|
|
||||||
|
|
||||||
if (options.phase === "isolated" && options.shardCount > 1) {
|
|
||||||
console.log(
|
|
||||||
`Running isolated test shard ${options.shardIndex + 1}/${options.shardCount} with ${selectedTargets.isolatedTestTargets.length} targets.`,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const isolatedTestTarget of selectedTargets.isolatedTestTargets) {
|
|
||||||
await runBunTest([isolatedTestTarget], `Isolated ${isolatedTestTarget}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
await runBunTest(selectedTargets.sharedTestFiles, "Shared Bun test suite")
|
|
||||||
}
|
|
||||||
|
|
||||||
export const moduleMockPattern = MODULE_MOCK_PATTERN
|
|
||||||
export const testRoots = TEST_ROOTS
|
|
||||||
|
|
||||||
if (process.argv.includes("--print-plan")) {
|
|
||||||
const ciTestPlan = await createCiTestPlan()
|
|
||||||
console.log(JSON.stringify(ciTestPlan, null, 2))
|
|
||||||
} else if (import.meta.main) {
|
|
||||||
try {
|
|
||||||
await main()
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error)
|
|
||||||
console.error(message)
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,5 +11,5 @@
|
|||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"noEmit": true
|
"noEmit": true
|
||||||
},
|
},
|
||||||
"include": ["./publish-workflow.test.ts", "./run-ci-tests.ts"]
|
"include": ["./publish-workflow.test.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { describe, it, expect, mock, spyOn, beforeEach, afterEach, afterAll } from "bun:test"
|
import { describe, it, expect, mock, spyOn, beforeEach, afterEach } from "bun:test"
|
||||||
import type { RunResult } from "./types"
|
import type { RunResult } from "./types"
|
||||||
import { createJsonOutputManager } from "./json-output"
|
import { createJsonOutputManager } from "./json-output"
|
||||||
import { resolveSession } from "./session-resolver"
|
import { resolveSession } from "./session-resolver"
|
||||||
import { executeOnCompleteHook } from "./on-complete-hook"
|
import { executeOnCompleteHook } from "./on-complete-hook"
|
||||||
import * as spawnWithWindowsHideModule from "../../shared/spawn-with-windows-hide"
|
import * as spawnWithWindowsHideModule from "../../shared/spawn-with-windows-hide"
|
||||||
import type { OpencodeClient } from "./types"
|
import type { OpencodeClient } from "./types"
|
||||||
import * as originalSdk from "@opencode-ai/sdk"
|
import { createServerConnectionWithDeps, type ServerConnectionDeps, type ServerConnectionOptions } from "./server-connection"
|
||||||
import * as originalPortUtils from "../../shared/port-utils"
|
|
||||||
import { unsafeTestValue } from "../../../test-support/unsafe-test-value"
|
import { unsafeTestValue } from "../../../test-support/unsafe-test-value"
|
||||||
|
|
||||||
|
type TestClient = { session: Record<string, unknown> }
|
||||||
const mockServerClose = mock(() => {})
|
const mockServerClose = mock(() => {})
|
||||||
const mockCreateOpencode = mock(() =>
|
const mockCreateOpencode = mock(() =>
|
||||||
Promise.resolve({
|
Promise.resolve({
|
||||||
@@ -19,25 +19,23 @@ const mockCreateOpencode = mock(() =>
|
|||||||
const mockCreateOpencodeClient = mock(() => ({ session: {} }))
|
const mockCreateOpencodeClient = mock(() => ({ session: {} }))
|
||||||
const mockIsPortAvailable = mock(() => Promise.resolve(true))
|
const mockIsPortAvailable = mock(() => Promise.resolve(true))
|
||||||
const mockGetAvailableServerPort = mock(() => Promise.resolve({ port: 9999, wasAutoSelected: false }))
|
const mockGetAvailableServerPort = mock(() => Promise.resolve({ port: 9999, wasAutoSelected: false }))
|
||||||
|
const mockWithWorkingOpencodePath = mock((startServer: () => Promise<unknown>) => startServer())
|
||||||
|
const mockInjectServerAuthIntoClient = mock(() => {})
|
||||||
|
|
||||||
mock.module("@opencode-ai/sdk", () => ({
|
function createDeps(): ServerConnectionDeps<TestClient> {
|
||||||
createOpencode: mockCreateOpencode,
|
return {
|
||||||
createOpencodeClient: mockCreateOpencodeClient,
|
createOpencode: mockCreateOpencode,
|
||||||
}))
|
createOpencodeClient: mockCreateOpencodeClient,
|
||||||
|
isPortAvailable: mockIsPortAvailable,
|
||||||
|
getAvailableServerPort: mockGetAvailableServerPort,
|
||||||
|
withWorkingOpencodePath: mockWithWorkingOpencodePath,
|
||||||
|
injectServerAuthIntoClient: mockInjectServerAuthIntoClient,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
mock.module("../../shared/port-utils", () => ({
|
async function createServerConnection(options: ServerConnectionOptions) {
|
||||||
isPortAvailable: mockIsPortAvailable,
|
return await createServerConnectionWithDeps(options, createDeps())
|
||||||
getAvailableServerPort: mockGetAvailableServerPort,
|
}
|
||||||
DEFAULT_SERVER_PORT: 4096,
|
|
||||||
}))
|
|
||||||
|
|
||||||
afterAll(() => {
|
|
||||||
mock.module("@opencode-ai/sdk", () => originalSdk)
|
|
||||||
mock.module("../../shared/port-utils", () => originalPortUtils)
|
|
||||||
mock.restore()
|
|
||||||
})
|
|
||||||
|
|
||||||
const { createServerConnection } = await import("./server-connection")
|
|
||||||
|
|
||||||
interface MockWriteStream {
|
interface MockWriteStream {
|
||||||
write: (chunk: string) => boolean
|
write: (chunk: string) => boolean
|
||||||
@@ -312,6 +310,10 @@ describe("integration: server connection", () => {
|
|||||||
mockCreateOpencode.mockClear()
|
mockCreateOpencode.mockClear()
|
||||||
mockCreateOpencodeClient.mockClear()
|
mockCreateOpencodeClient.mockClear()
|
||||||
mockServerClose.mockClear()
|
mockServerClose.mockClear()
|
||||||
|
mockIsPortAvailable.mockClear()
|
||||||
|
mockGetAvailableServerPort.mockClear()
|
||||||
|
mockWithWorkingOpencodePath.mockClear()
|
||||||
|
mockInjectServerAuthIntoClient.mockClear()
|
||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
import { describe, it, expect, mock, beforeEach, afterEach, afterAll } from "bun:test"
|
import { describe, it, expect, mock, beforeEach, afterEach } from "bun:test"
|
||||||
|
import { createServerConnectionWithDeps, type ServerConnectionDeps, type ServerConnectionOptions } from "./server-connection"
|
||||||
import * as originalSdk from "@opencode-ai/sdk"
|
|
||||||
import * as originalPortUtils from "../../shared/port-utils"
|
|
||||||
import * as originalBinaryResolver from "./opencode-binary-resolver"
|
|
||||||
import * as originalServerAuth from "../../shared/opencode-server-auth"
|
|
||||||
|
|
||||||
const originalConsole = globalThis.console
|
const originalConsole = globalThis.console
|
||||||
|
type TestClient = { session: Record<string, unknown>, baseUrl?: string }
|
||||||
|
|
||||||
const mockServerClose = mock(() => {})
|
const mockServerClose = mock(() => {})
|
||||||
const mockCreateOpencode = mock(() =>
|
const mockCreateOpencode = mock(() =>
|
||||||
@@ -24,34 +21,20 @@ const mockConsoleLog = mock(() => {})
|
|||||||
const mockWithWorkingOpencodePath = mock((startServer: () => Promise<unknown>) => startServer())
|
const mockWithWorkingOpencodePath = mock((startServer: () => Promise<unknown>) => startServer())
|
||||||
const mockInjectServerAuthIntoClient = mock(() => {})
|
const mockInjectServerAuthIntoClient = mock(() => {})
|
||||||
|
|
||||||
mock.module("@opencode-ai/sdk", () => ({
|
function createDeps(): ServerConnectionDeps<TestClient> {
|
||||||
createOpencode: mockCreateOpencode,
|
return {
|
||||||
createOpencodeClient: mockCreateOpencodeClient,
|
createOpencode: mockCreateOpencode,
|
||||||
}))
|
createOpencodeClient: mockCreateOpencodeClient,
|
||||||
|
isPortAvailable: mockIsPortAvailable,
|
||||||
|
getAvailableServerPort: mockGetAvailableServerPort,
|
||||||
|
withWorkingOpencodePath: mockWithWorkingOpencodePath,
|
||||||
|
injectServerAuthIntoClient: mockInjectServerAuthIntoClient,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
mock.module("../../shared/port-utils", () => ({
|
async function createServerConnection(options: ServerConnectionOptions) {
|
||||||
isPortAvailable: mockIsPortAvailable,
|
return await createServerConnectionWithDeps(options, createDeps())
|
||||||
getAvailableServerPort: mockGetAvailableServerPort,
|
}
|
||||||
DEFAULT_SERVER_PORT: 4096,
|
|
||||||
}))
|
|
||||||
|
|
||||||
mock.module("./opencode-binary-resolver", () => ({
|
|
||||||
withWorkingOpencodePath: mockWithWorkingOpencodePath,
|
|
||||||
}))
|
|
||||||
|
|
||||||
mock.module("../../shared/opencode-server-auth", () => ({
|
|
||||||
injectServerAuthIntoClient: mockInjectServerAuthIntoClient,
|
|
||||||
}))
|
|
||||||
|
|
||||||
afterAll(() => {
|
|
||||||
mock.module("@opencode-ai/sdk", () => originalSdk)
|
|
||||||
mock.module("../../shared/port-utils", () => originalPortUtils)
|
|
||||||
mock.module("./opencode-binary-resolver", () => originalBinaryResolver)
|
|
||||||
mock.module("../../shared/opencode-server-auth", () => originalServerAuth)
|
|
||||||
mock.restore()
|
|
||||||
})
|
|
||||||
|
|
||||||
const { createServerConnection } = await import("./server-connection")
|
|
||||||
|
|
||||||
describe("createServerConnection", () => {
|
describe("createServerConnection", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createOpencode, createOpencodeClient } from "@opencode-ai/sdk"
|
import { createOpencode as createOpencodeSdk, createOpencodeClient as createOpencodeClientSdk } from "@opencode-ai/sdk"
|
||||||
import pc from "picocolors"
|
import pc from "picocolors"
|
||||||
import type { ServerConnection } from "./types"
|
import type { ServerConnection } from "./types"
|
||||||
import { injectServerAuthIntoClient } from "../../shared/opencode-server-auth"
|
import { injectServerAuthIntoClient } from "../../shared/opencode-server-auth"
|
||||||
@@ -7,6 +7,40 @@ import { withWorkingOpencodePath } from "./opencode-binary-resolver"
|
|||||||
|
|
||||||
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]", "0.0.0.0"])
|
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]", "0.0.0.0"])
|
||||||
|
|
||||||
|
export type ServerConnectionOptions = {
|
||||||
|
port?: number
|
||||||
|
attach?: string
|
||||||
|
signal: AbortSignal
|
||||||
|
}
|
||||||
|
|
||||||
|
type OpencodeServer<TClient> = {
|
||||||
|
client: TClient
|
||||||
|
server: {
|
||||||
|
url: string
|
||||||
|
close: () => void
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ServerConnectionDeps<TClient> = {
|
||||||
|
createOpencode: (options: { signal: AbortSignal, port: number, hostname: string }) => Promise<OpencodeServer<TClient>>
|
||||||
|
createOpencodeClient: (options: { baseUrl: string }) => TClient
|
||||||
|
injectServerAuthIntoClient: (client: TClient) => void
|
||||||
|
isPortAvailable: (port: number, hostname?: string) => Promise<boolean>
|
||||||
|
getAvailableServerPort: (preferredPort?: number, hostname?: string) => Promise<{ port: number, wasAutoSelected: boolean }>
|
||||||
|
withWorkingOpencodePath: (
|
||||||
|
startServer: () => Promise<OpencodeServer<TClient>>,
|
||||||
|
) => Promise<OpencodeServer<TClient>>
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultDeps: ServerConnectionDeps<ServerConnection["client"]> = {
|
||||||
|
createOpencode: createOpencodeSdk,
|
||||||
|
createOpencodeClient: createOpencodeClientSdk,
|
||||||
|
injectServerAuthIntoClient,
|
||||||
|
isPortAvailable,
|
||||||
|
getAvailableServerPort,
|
||||||
|
withWorkingOpencodePath,
|
||||||
|
}
|
||||||
|
|
||||||
function isLoopbackAttachUrl(url: string): boolean {
|
function isLoopbackAttachUrl(url: string): boolean {
|
||||||
try {
|
try {
|
||||||
const parsed = new URL(url)
|
const parsed = new URL(url)
|
||||||
@@ -32,28 +66,30 @@ function isPortRangeExhausted(error: unknown): boolean {
|
|||||||
return error.message.includes("No available port found in range")
|
return error.message.includes("No available port found in range")
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startServer(options: { signal: AbortSignal, port: number }): Promise<ServerConnection> {
|
async function startServer<TClient>(
|
||||||
|
options: { signal: AbortSignal, port: number },
|
||||||
|
deps: ServerConnectionDeps<TClient>,
|
||||||
|
): Promise<{ client: TClient, cleanup: () => void }> {
|
||||||
const { signal, port } = options
|
const { signal, port } = options
|
||||||
const { client, server } = await withWorkingOpencodePath(() =>
|
const { client, server } = await deps.withWorkingOpencodePath(() =>
|
||||||
createOpencode({ signal, port, hostname: "127.0.0.1" }),
|
deps.createOpencode({ signal, port, hostname: "127.0.0.1" }),
|
||||||
)
|
)
|
||||||
|
|
||||||
console.log(pc.dim("Server listening at"), pc.cyan(server.url))
|
console.log(pc.dim("Server listening at"), pc.cyan(server.url))
|
||||||
return { client, cleanup: () => server.close() }
|
return { client, cleanup: () => server.close() }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createServerConnection(options: {
|
export async function createServerConnectionWithDeps<TClient>(
|
||||||
port?: number
|
options: ServerConnectionOptions,
|
||||||
attach?: string
|
deps: ServerConnectionDeps<TClient>,
|
||||||
signal: AbortSignal
|
): Promise<{ client: TClient, cleanup: () => void }> {
|
||||||
}): Promise<ServerConnection> {
|
|
||||||
const { port, attach, signal } = options
|
const { port, attach, signal } = options
|
||||||
|
|
||||||
if (attach !== undefined) {
|
if (attach !== undefined) {
|
||||||
console.log(pc.dim("Attaching to existing server at"), pc.cyan(attach))
|
console.log(pc.dim("Attaching to existing server at"), pc.cyan(attach))
|
||||||
const client = createOpencodeClient({ baseUrl: attach })
|
const client = deps.createOpencodeClient({ baseUrl: attach })
|
||||||
if (isLoopbackAttachUrl(attach)) {
|
if (isLoopbackAttachUrl(attach)) {
|
||||||
injectServerAuthIntoClient(client)
|
deps.injectServerAuthIntoClient(client)
|
||||||
}
|
}
|
||||||
return { client, cleanup: () => {} }
|
return { client, cleanup: () => {} }
|
||||||
}
|
}
|
||||||
@@ -63,39 +99,39 @@ export async function createServerConnection(options: {
|
|||||||
throw new Error("Port must be between 1 and 65535")
|
throw new Error("Port must be between 1 and 65535")
|
||||||
}
|
}
|
||||||
|
|
||||||
const available = await isPortAvailable(port, "127.0.0.1")
|
const available = await deps.isPortAvailable(port, "127.0.0.1")
|
||||||
|
|
||||||
if (available) {
|
if (available) {
|
||||||
console.log(pc.dim("Starting server on port"), pc.cyan(port.toString()))
|
console.log(pc.dim("Starting server on port"), pc.cyan(port.toString()))
|
||||||
try {
|
try {
|
||||||
return await startServer({ signal, port })
|
return await startServer({ signal, port }, deps)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isPortStartFailure(error, port)) {
|
if (!isPortStartFailure(error, port)) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
const stillAvailable = await isPortAvailable(port, "127.0.0.1")
|
const stillAvailable = await deps.isPortAvailable(port, "127.0.0.1")
|
||||||
if (stillAvailable) {
|
if (stillAvailable) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(pc.dim("Port"), pc.cyan(port.toString()), pc.dim("became occupied, attaching to existing server"))
|
console.log(pc.dim("Port"), pc.cyan(port.toString()), pc.dim("became occupied, attaching to existing server"))
|
||||||
const client = createOpencodeClient({ baseUrl: `http://127.0.0.1:${port}` })
|
const client = deps.createOpencodeClient({ baseUrl: `http://127.0.0.1:${port}` })
|
||||||
injectServerAuthIntoClient(client)
|
deps.injectServerAuthIntoClient(client)
|
||||||
return { client, cleanup: () => {} }
|
return { client, cleanup: () => {} }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(pc.dim("Port"), pc.cyan(port.toString()), pc.dim("is occupied, attaching to existing server"))
|
console.log(pc.dim("Port"), pc.cyan(port.toString()), pc.dim("is occupied, attaching to existing server"))
|
||||||
const client = createOpencodeClient({ baseUrl: `http://127.0.0.1:${port}` })
|
const client = deps.createOpencodeClient({ baseUrl: `http://127.0.0.1:${port}` })
|
||||||
injectServerAuthIntoClient(client)
|
deps.injectServerAuthIntoClient(client)
|
||||||
return { client, cleanup: () => {} }
|
return { client, cleanup: () => {} }
|
||||||
}
|
}
|
||||||
|
|
||||||
let selectedPort: number
|
let selectedPort: number
|
||||||
let wasAutoSelected: boolean
|
let wasAutoSelected: boolean
|
||||||
try {
|
try {
|
||||||
const selected = await getAvailableServerPort(DEFAULT_SERVER_PORT, "127.0.0.1")
|
const selected = await deps.getAvailableServerPort(DEFAULT_SERVER_PORT, "127.0.0.1")
|
||||||
selectedPort = selected.port
|
selectedPort = selected.port
|
||||||
wasAutoSelected = selected.wasAutoSelected
|
wasAutoSelected = selected.wasAutoSelected
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -103,14 +139,14 @@ export async function createServerConnection(options: {
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultPortIsAvailable = await isPortAvailable(DEFAULT_SERVER_PORT, "127.0.0.1")
|
const defaultPortIsAvailable = await deps.isPortAvailable(DEFAULT_SERVER_PORT, "127.0.0.1")
|
||||||
if (defaultPortIsAvailable) {
|
if (defaultPortIsAvailable) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(pc.dim("Port range exhausted, attaching to existing server on"), pc.cyan(DEFAULT_SERVER_PORT.toString()))
|
console.log(pc.dim("Port range exhausted, attaching to existing server on"), pc.cyan(DEFAULT_SERVER_PORT.toString()))
|
||||||
const client = createOpencodeClient({ baseUrl: `http://127.0.0.1:${DEFAULT_SERVER_PORT}` })
|
const client = deps.createOpencodeClient({ baseUrl: `http://127.0.0.1:${DEFAULT_SERVER_PORT}` })
|
||||||
injectServerAuthIntoClient(client)
|
deps.injectServerAuthIntoClient(client)
|
||||||
return { client, cleanup: () => {} }
|
return { client, cleanup: () => {} }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,14 +157,18 @@ export async function createServerConnection(options: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await startServer({ signal, port: selectedPort })
|
return await startServer({ signal, port: selectedPort }, deps)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!isPortStartFailure(error, selectedPort)) {
|
if (!isPortStartFailure(error, selectedPort)) {
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
const { port: retryPort } = await getAvailableServerPort(selectedPort + 1, "127.0.0.1")
|
const { port: retryPort } = await deps.getAvailableServerPort(selectedPort + 1, "127.0.0.1")
|
||||||
console.log(pc.dim("Retrying server start on port"), pc.cyan(retryPort.toString()))
|
console.log(pc.dim("Retrying server start on port"), pc.cyan(retryPort.toString()))
|
||||||
return await startServer({ signal, port: retryPort })
|
return await startServer({ signal, port: retryPort }, deps)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function createServerConnection(options: ServerConnectionOptions): Promise<ServerConnection> {
|
||||||
|
return await createServerConnectionWithDeps(options, defaultDeps)
|
||||||
|
}
|
||||||
|
|||||||
@@ -5179,7 +5179,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
|||||||
{
|
{
|
||||||
info: {
|
info: {
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
time: { created: Date.now() },
|
time: { created: 2_000 },
|
||||||
},
|
},
|
||||||
parts: [{ type: "text", text: "wake was already accepted" }],
|
parts: [{ type: "text", text: "wake was already accepted" }],
|
||||||
},
|
},
|
||||||
@@ -5214,7 +5214,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
|||||||
if (!wake) {
|
if (!wake) {
|
||||||
throw new Error("Missing dispatched parent wake")
|
throw new Error("Missing dispatched parent wake")
|
||||||
}
|
}
|
||||||
wake.dispatchedAt = Date.now() - 1_000
|
wake.dispatchedAt = 1_000
|
||||||
|
|
||||||
//#when
|
//#when
|
||||||
manager.handleEvent({
|
manager.handleEvent({
|
||||||
|
|||||||
@@ -3,11 +3,6 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
|||||||
import { tmpdir } from "node:os"
|
import { tmpdir } from "node:os"
|
||||||
import { join } from "node:path"
|
import { join } from "node:path"
|
||||||
|
|
||||||
// NOTE: Do NOT import discoverInstalledPlugins at top level.
|
|
||||||
// loader.test.ts in the same directory mocks "./discovery" with name: "demo",
|
|
||||||
// and when run-ci-tests.ts groups this directory together, that mock leaks.
|
|
||||||
// Dynamic import inside each test avoids the contamination.
|
|
||||||
|
|
||||||
const originalClaudePluginsHome = process.env.CLAUDE_PLUGINS_HOME
|
const originalClaudePluginsHome = process.env.CLAUDE_PLUGINS_HOME
|
||||||
const temporaryDirectories: string[] = []
|
const temporaryDirectories: string[] = []
|
||||||
const originalCwd = process.cwd()
|
const originalCwd = process.cwd()
|
||||||
|
|||||||
@@ -1,95 +1,70 @@
|
|||||||
/// <reference types="bun-types" />
|
import { describe, expect, mock, test } from "bun:test"
|
||||||
|
import type { TmuxCommandResult } from "../../../shared/tmux"
|
||||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
|
||||||
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
|
|
||||||
import { tmpdir } from "node:os"
|
|
||||||
import path from "node:path"
|
|
||||||
|
|
||||||
import { resolveCallerTmuxSession } from "./resolve-caller-tmux-session"
|
import { resolveCallerTmuxSession } from "./resolve-caller-tmux-session"
|
||||||
|
|
||||||
type TmuxStub = {
|
type TmuxCall = {
|
||||||
tmuxPath: string
|
tmuxPath: string
|
||||||
logPath: string
|
args: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
const temporaryDirectories: string[] = []
|
function tmuxResult(output: string, exitCode: number = 0): TmuxCommandResult {
|
||||||
|
return {
|
||||||
function shellSingleQuote(value: string): string {
|
success: exitCode === 0,
|
||||||
return `'${value.split("'").join(`'"'"'`)}'`
|
output,
|
||||||
}
|
stdout: output,
|
||||||
|
stderr: "",
|
||||||
async function createTmuxStub(options: { stdout: string; windowStdout?: string; exitCode: number }): Promise<TmuxStub> {
|
exitCode,
|
||||||
const directory = await mkdtemp(path.join(tmpdir(), "resolve-caller-tmux-session-"))
|
|
||||||
temporaryDirectories.push(directory)
|
|
||||||
|
|
||||||
const logPath = path.join(directory, "tmux.log")
|
|
||||||
const tmuxPath = path.join(directory, "tmux")
|
|
||||||
const script = [
|
|
||||||
"#!/bin/sh",
|
|
||||||
`printf '%s\\n' \"$@\" >> ${shellSingleQuote(logPath)}`,
|
|
||||||
`case "$*" in *'#{session_name}:#{window_index}'*) printf '%s' ${shellSingleQuote(options.windowStdout ?? options.stdout)} ;; *) printf '%s' ${shellSingleQuote(options.stdout)} ;; esac`,
|
|
||||||
`exit ${options.exitCode}`,
|
|
||||||
].join("\n")
|
|
||||||
|
|
||||||
await writeFile(tmuxPath, script)
|
|
||||||
await chmod(tmuxPath, 0o755)
|
|
||||||
|
|
||||||
return { tmuxPath, logPath }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readLogLines(logPath: string): Promise<string[]> {
|
|
||||||
try {
|
|
||||||
const content = await readFile(logPath, "utf8")
|
|
||||||
return content.split("\n").filter((line) => line.length > 0)
|
|
||||||
} catch {
|
|
||||||
return []
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
beforeEach(() => {
|
function createRunCommandMock(results: TmuxCommandResult[]) {
|
||||||
delete process.env.TMUX_PANE
|
const calls: TmuxCall[] = []
|
||||||
})
|
const runCommand = mock(async (tmuxPath: string, args: string[]): Promise<TmuxCommandResult> => {
|
||||||
|
calls.push({ tmuxPath, args })
|
||||||
|
return results.shift() ?? tmuxResult("", 1)
|
||||||
|
})
|
||||||
|
|
||||||
afterEach(async () => {
|
return { calls, runCommand }
|
||||||
await Promise.all(temporaryDirectories.splice(0).map(async (directory) => rm(directory, { recursive: true, force: true })))
|
}
|
||||||
})
|
|
||||||
|
|
||||||
describe("resolveCallerTmuxSession", () => {
|
describe("resolveCallerTmuxSession", () => {
|
||||||
test("#given TMUX_PANE unset #when resolve runs #then returns null and makes no tmux calls", async () => {
|
test("#given TMUX_PANE unset #when resolve runs #then returns null and makes no tmux calls", async () => {
|
||||||
// given
|
// given
|
||||||
const stub = await createTmuxStub({ stdout: "$7", exitCode: 0 })
|
const { calls, runCommand } = createRunCommandMock([tmuxResult("$7")])
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await resolveCallerTmuxSession(stub.tmuxPath)
|
const result = await resolveCallerTmuxSession("tmux", "", runCommand)
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBeNull()
|
expect(result).toBeNull()
|
||||||
expect(await readLogLines(stub.logPath)).toHaveLength(0)
|
expect(calls).toHaveLength(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("#given TMUX_PANE=%42 and display returns session and window #when resolve runs #then returns caller tmux target", async () => {
|
test("#given TMUX_PANE=%42 and display returns session and window #when resolve runs #then returns caller tmux target", async () => {
|
||||||
// given
|
// given
|
||||||
process.env.TMUX_PANE = "%42"
|
const { calls, runCommand } = createRunCommandMock([
|
||||||
const stub = await createTmuxStub({ stdout: "$7", windowStdout: "test-session:0", exitCode: 0 })
|
tmuxResult("$7"),
|
||||||
|
tmuxResult("test-session:0"),
|
||||||
|
])
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await resolveCallerTmuxSession(stub.tmuxPath)
|
const result = await resolveCallerTmuxSession("tmux", "%42", runCommand)
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toEqual({ sessionId: "$7", paneId: "%42", windowTarget: "test-session:0" })
|
expect(result).toEqual({ sessionId: "$7", paneId: "%42", windowTarget: "test-session:0" })
|
||||||
expect(await readLogLines(stub.logPath)).toEqual([
|
expect(calls).toEqual([
|
||||||
"display", "-p", "-F", "#{session_id}", "-t", "%42",
|
{ tmuxPath: "tmux", args: ["display", "-p", "-F", "#{session_id}", "-t", "%42"] },
|
||||||
"display", "-p", "-F", "#{session_name}:#{window_index}", "-t", "%42",
|
{ tmuxPath: "tmux", args: ["display", "-p", "-F", "#{session_name}:#{window_index}", "-t", "%42"] },
|
||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
test("#given TMUX_PANE=%42 and display returns 'garbage' #when resolve runs #then returns null", async () => {
|
test("#given TMUX_PANE=%42 and display returns 'garbage' #when resolve runs #then returns null", async () => {
|
||||||
// given
|
// given
|
||||||
process.env.TMUX_PANE = "%42"
|
const { runCommand } = createRunCommandMock([tmuxResult("garbage")])
|
||||||
const stub = await createTmuxStub({ stdout: "garbage", exitCode: 0 })
|
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await resolveCallerTmuxSession(stub.tmuxPath)
|
const result = await resolveCallerTmuxSession("tmux", "%42", runCommand)
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBeNull()
|
expect(result).toBeNull()
|
||||||
@@ -97,11 +72,10 @@ describe("resolveCallerTmuxSession", () => {
|
|||||||
|
|
||||||
test("#given TMUX_PANE=%42 and display exits non-success #when resolve runs #then returns null", async () => {
|
test("#given TMUX_PANE=%42 and display exits non-success #when resolve runs #then returns null", async () => {
|
||||||
// given
|
// given
|
||||||
process.env.TMUX_PANE = "%42"
|
const { runCommand } = createRunCommandMock([tmuxResult("$7", 1)])
|
||||||
const stub = await createTmuxStub({ stdout: "$7", exitCode: 1 })
|
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await resolveCallerTmuxSession(stub.tmuxPath)
|
const result = await resolveCallerTmuxSession("tmux", "%42", runCommand)
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBeNull()
|
expect(result).toBeNull()
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { runTmuxCommand } from "../../../shared/tmux"
|
import { runTmuxCommand } from "../../../shared/tmux"
|
||||||
|
import type { TmuxCommandResult } from "../../../shared/tmux"
|
||||||
|
|
||||||
type ResolvedCallerTmuxSession = {
|
type ResolvedCallerTmuxSession = {
|
||||||
sessionId: string
|
sessionId: string
|
||||||
@@ -6,16 +7,21 @@ type ResolvedCallerTmuxSession = {
|
|||||||
windowTarget: string
|
windowTarget: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RunTmuxCommand = (tmuxPath: string, args: string[]) => Promise<TmuxCommandResult>
|
||||||
|
|
||||||
const TMUX_SESSION_ID_PATTERN = /^\$[0-9]+$/
|
const TMUX_SESSION_ID_PATTERN = /^\$[0-9]+$/
|
||||||
const TMUX_WINDOW_TARGET_PATTERN = /^[^:]+:[0-9]+$/
|
const TMUX_WINDOW_TARGET_PATTERN = /^[^:]+:[0-9]+$/
|
||||||
|
|
||||||
export async function resolveCallerTmuxSession(tmuxPath: string): Promise<ResolvedCallerTmuxSession | null> {
|
export async function resolveCallerTmuxSession(
|
||||||
const callerPaneId = process.env.TMUX_PANE
|
tmuxPath: string,
|
||||||
|
callerPaneId: string | undefined = process.env.TMUX_PANE,
|
||||||
|
runCommand: RunTmuxCommand = runTmuxCommand,
|
||||||
|
): Promise<ResolvedCallerTmuxSession | null> {
|
||||||
if (!callerPaneId) {
|
if (!callerPaneId) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionResult = await runTmuxCommand(tmuxPath, ["display", "-p", "-F", "#{session_id}", "-t", callerPaneId])
|
const sessionResult = await runCommand(tmuxPath, ["display", "-p", "-F", "#{session_id}", "-t", callerPaneId])
|
||||||
if (!sessionResult.success) {
|
if (!sessionResult.success) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -25,7 +31,7 @@ export async function resolveCallerTmuxSession(tmuxPath: string): Promise<Resolv
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
const windowResult = await runTmuxCommand(tmuxPath, ["display", "-p", "-F", "#{session_name}:#{window_index}", "-t", callerPaneId])
|
const windowResult = await runCommand(tmuxPath, ["display", "-p", "-F", "#{session_name}:#{window_index}", "-t", callerPaneId])
|
||||||
if (!windowResult.success) {
|
if (!windowResult.success) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
/// <reference path="../../../bun-test.d.ts" />
|
/// <reference path="../../../bun-test.d.ts" />
|
||||||
import { describe, test, expect, mock, beforeEach, spyOn, afterAll } from 'bun:test'
|
import { describe, test, expect, mock, beforeEach, spyOn, afterAll, afterEach } from 'bun:test'
|
||||||
import type { TmuxConfig } from '../../config/schema'
|
import type { TmuxConfig } from '../../config/schema'
|
||||||
import type { WindowState, PaneAction } from './types'
|
import type { WindowState, PaneAction } from './types'
|
||||||
import type { ActionResult, ExecuteContext } from './action-executor'
|
import type { ActionResult, ExecuteContext } from './action-executor'
|
||||||
import type { TmuxSessionManager as TmuxSessionManagerType, TmuxUtilDeps } from './manager'
|
import type { TmuxSessionManager as TmuxSessionManagerType, TmuxUtilDeps } from './manager'
|
||||||
import * as sharedModule from '../../shared'
|
import * as sharedModule from '../../shared'
|
||||||
|
import * as sharedTmuxOriginal from '../../shared/tmux'
|
||||||
|
|
||||||
|
const sharedTmuxSnapshot = { ...sharedTmuxOriginal }
|
||||||
|
|
||||||
type ExecuteActionsResult = {
|
type ExecuteActionsResult = {
|
||||||
success: boolean
|
success: boolean
|
||||||
@@ -131,6 +134,11 @@ function registerModuleMocks(): void {
|
|||||||
|
|
||||||
afterAll(() => { mock.restore() })
|
afterAll(() => { mock.restore() })
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
mock.restore()
|
||||||
|
mock.module('../../shared/tmux', () => sharedTmuxSnapshot)
|
||||||
|
})
|
||||||
|
|
||||||
const trackedSessions = new Set<string>()
|
const trackedSessions = new Set<string>()
|
||||||
const readySessions = new Set<string>()
|
const readySessions = new Set<string>()
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
/// <reference path="../../../bun-test.d.ts" />
|
/// <reference path="../../../bun-test.d.ts" />
|
||||||
import { beforeEach, describe, expect, mock, test, afterAll } from "bun:test"
|
import { afterEach, beforeEach, describe, expect, mock, test, afterAll } from "bun:test"
|
||||||
import type { TmuxConfig } from "../../config/schema"
|
import type { TmuxConfig } from "../../config/schema"
|
||||||
import type { ActionResult, ExecuteContext, ExecuteActionsResult } from "./action-executor"
|
import type { ActionResult, ExecuteContext, ExecuteActionsResult } from "./action-executor"
|
||||||
import type { TmuxUtilDeps } from "./manager"
|
import type { TmuxUtilDeps } from "./manager"
|
||||||
import type { TrackedSession, WindowState } from "./types"
|
import type { TrackedSession, WindowState } from "./types"
|
||||||
|
import * as sharedTmuxOriginal from "../../shared/tmux"
|
||||||
|
|
||||||
|
const sharedTmuxSnapshot = { ...sharedTmuxOriginal }
|
||||||
|
|
||||||
const mockQueryWindowState = mock<(paneId: string) => Promise<WindowState | null>>(async () => ({
|
const mockQueryWindowState = mock<(paneId: string) => Promise<WindowState | null>>(async () => ({
|
||||||
windowWidth: 220,
|
windowWidth: 220,
|
||||||
@@ -53,6 +56,11 @@ function registerModuleMocks(): void {
|
|||||||
|
|
||||||
afterAll(() => { mock.restore() })
|
afterAll(() => { mock.restore() })
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
mock.restore()
|
||||||
|
mock.module("../../shared/tmux", () => sharedTmuxSnapshot)
|
||||||
|
})
|
||||||
|
|
||||||
const mockTmuxDeps: TmuxUtilDeps = {
|
const mockTmuxDeps: TmuxUtilDeps = {
|
||||||
isInsideTmux: mockIsInsideTmux,
|
isInsideTmux: mockIsInsideTmux,
|
||||||
getCurrentPaneId: mockGetCurrentPaneId,
|
getCurrentPaneId: mockGetCurrentPaneId,
|
||||||
|
|||||||
+1
-1
@@ -142,6 +142,6 @@ hooks/
|
|||||||
## NOTES
|
## NOTES
|
||||||
|
|
||||||
- **Tier order matters within a phase:** within Session tier the registration order in `create-session-hooks.ts` determines invocation order — earlier hooks see un-mutated input, later hooks see accumulated output.
|
- **Tier order matters within a phase:** within Session tier the registration order in `create-session-hooks.ts` determines invocation order — earlier hooks see un-mutated input, later hooks see accumulated output.
|
||||||
- **Mock files** (`zauc-mocks-*`, `zauc-sync-mocks`) are NOT hooks. They are placed inside `src/hooks/` purely so `bun:test` discovers them in the right order — auto-isolated by `script/run-ci-tests.ts` because they use `mock.module()`.
|
- **Mock files** (`zauc-mocks-*`, `zauc-sync-mocks`) are NOT hooks. They are placed inside `src/hooks/` purely so `bun:test` discovers them with the hook test fixtures.
|
||||||
- **`atlasHook` vs `todoContinuationEnforcer`:** atlas handles boulder/ralph/subagent sessions, todoContinuationEnforcer handles the main Sisyphus session. Both fire on `session.idle` but check session type first.
|
- **`atlasHook` vs `todoContinuationEnforcer`:** atlas handles boulder/ralph/subagent sessions, todoContinuationEnforcer handles the main Sisyphus session. Both fire on `session.idle` but check session type first.
|
||||||
- **`runtime-fallback` vs `model-fallback`:** runtime-fallback is reactive (after error); model-fallback is proactive (chat.params). They operate independently.
|
- **`runtime-fallback` vs `model-fallback`:** runtime-fallback is reactive (after error); model-fallback is proactive (chat.params). They operate independently.
|
||||||
|
|||||||
@@ -76,7 +76,3 @@ initializeOpenClaw(config)
|
|||||||
- **Authorized users**: Inbound replies filtered by allowed user ID list
|
- **Authorized users**: Inbound replies filtered by allowed user ID list
|
||||||
- **Token redaction**: Secrets masked in logs and error messages
|
- **Token redaction**: Secrets masked in logs and error messages
|
||||||
- **Rate limiting**: Reply injection throttled per pane
|
- **Rate limiting**: Reply injection throttled per pane
|
||||||
|
|
||||||
## TESTING NOTE
|
|
||||||
|
|
||||||
`reply-listener-discord.test.ts` is **always isolated** in CI (listed in `ALWAYS_ISOLATED_TEST_FILES` of `script/run-ci-tests.ts`). Reason: mocks `globalThis.fetch` for Discord API simulation — needs process isolation to avoid interference with shared test batch.
|
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import * as openclawRuntimeDispatch from "../openclaw/runtime-dispatch"
|
|||||||
import { _resetForTesting, setMainSession, subagentSessions } from "../features/claude-code-session-state"
|
import { _resetForTesting, setMainSession, subagentSessions } from "../features/claude-code-session-state"
|
||||||
import { clearPendingModelFallback, createModelFallbackHook } from "../hooks/model-fallback/hook"
|
import { clearPendingModelFallback, createModelFallbackHook } from "../hooks/model-fallback/hook"
|
||||||
import { getSessionPromptParams, setSessionPromptParams } from "../shared/session-prompt-params-state"
|
import { getSessionPromptParams, setSessionPromptParams } from "../shared/session-prompt-params-state"
|
||||||
|
import * as sharedTmuxOriginal from "../shared/tmux"
|
||||||
|
|
||||||
|
const sharedTmuxSnapshot = { ...sharedTmuxOriginal }
|
||||||
|
|
||||||
type EventInput = { event: { type: string; properties?: unknown } }
|
type EventInput = { event: { type: string; properties?: unknown } }
|
||||||
type EventHandlerArgs = Parameters<typeof createEventHandler>[0]
|
type EventHandlerArgs = Parameters<typeof createEventHandler>[0]
|
||||||
@@ -135,6 +138,7 @@ async function flushMicrotasks(turns: number = 5): Promise<void> {
|
|||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
mock.restore()
|
mock.restore()
|
||||||
|
mock.module("../shared/tmux", () => sharedTmuxSnapshot)
|
||||||
_resetForTesting()
|
_resetForTesting()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -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"
|
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", () => {
|
describe("resolveModelPipeline", () => {
|
||||||
test("does not return unused explicit user config metadata in override result", () => {
|
test("does not return unused explicit user config metadata in override result", () => {
|
||||||
// given
|
// given
|
||||||
|
|||||||
@@ -1,10 +1,29 @@
|
|||||||
import { log } from "./logger"
|
import { log as writeLog } from "./logger"
|
||||||
import * as connectedProvidersCache from "./connected-providers-cache"
|
import * as connectedProvidersCache from "./connected-providers-cache"
|
||||||
import { fuzzyMatchModel } from "./model-availability"
|
import { fuzzyMatchModel } from "./model-availability"
|
||||||
import type { FallbackEntry } from "./model-requirements"
|
import type { FallbackEntry } from "./model-requirements"
|
||||||
import { transformModelForProvider } from "./provider-model-id-transform"
|
import { transformModelForProvider } from "./provider-model-id-transform"
|
||||||
import { normalizeModel } from "./model-normalization"
|
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 = {
|
export type ModelResolutionRequest = {
|
||||||
intent?: {
|
intent?: {
|
||||||
uiSelectedModel?: string
|
uiSelectedModel?: string
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { describe, expect, test, spyOn, beforeEach, afterEach, mock } from "bun:test"
|
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 { 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"
|
import * as connectedProvidersCache from "./connected-providers-cache"
|
||||||
|
|
||||||
|
const logMock = mock(() => {})
|
||||||
|
|
||||||
describe("resolveModel", () => {
|
describe("resolveModel", () => {
|
||||||
describe("priority chain", () => {
|
describe("priority chain", () => {
|
||||||
test("returns userModel when all three are set", () => {
|
test("returns userModel when all three are set", () => {
|
||||||
@@ -107,14 +106,13 @@ describe("resolveModel", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe("resolveModelWithFallback", () => {
|
describe("resolveModelWithFallback", () => {
|
||||||
let logSpy: ReturnType<typeof spyOn>
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
logSpy = spyOn(logger, "log")
|
logMock.mockClear()
|
||||||
|
_setModelResolutionLogImplementationForTesting(logMock)
|
||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
logSpy.mockRestore()
|
_setModelResolutionLogImplementationForTesting(undefined)
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("Step 1: UI Selection (highest priority)", () => {
|
describe("Step 1: UI Selection (highest priority)", () => {
|
||||||
@@ -136,7 +134,7 @@ describe("resolveModelWithFallback", () => {
|
|||||||
// then
|
// then
|
||||||
expect(result!.model).toBe("opencode/big-pickle")
|
expect(result!.model).toBe("opencode/big-pickle")
|
||||||
expect(result!.source).toBe("override")
|
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", () => {
|
test("UI selection takes priority over config override", () => {
|
||||||
@@ -170,7 +168,7 @@ describe("resolveModelWithFallback", () => {
|
|||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result!.model).toBe("anthropic/claude-opus-4-7")
|
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", () => {
|
test("empty string uiSelectedModel falls through to config override", () => {
|
||||||
@@ -208,7 +206,7 @@ describe("resolveModelWithFallback", () => {
|
|||||||
// then
|
// then
|
||||||
expect(result!.model).toBe("anthropic/claude-opus-4-7")
|
expect(result!.model).toBe("anthropic/claude-opus-4-7")
|
||||||
expect(result!.source).toBe("override")
|
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", () => {
|
test("override takes priority even if model not in availableModels", () => {
|
||||||
@@ -284,7 +282,7 @@ describe("resolveModelWithFallback", () => {
|
|||||||
// then
|
// then
|
||||||
expect(result!.model).toBe("github-copilot/claude-opus-4-7-preview")
|
expect(result!.model).toBe("github-copilot/claude-opus-4-7-preview")
|
||||||
expect(result!.source).toBe("provider-fallback")
|
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",
|
provider: "github-copilot",
|
||||||
model: "claude-opus-4-7",
|
model: "claude-opus-4-7",
|
||||||
match: "github-copilot/claude-opus-4-7-preview",
|
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
|
// then - should find glm-5 from opencode via cross-provider fuzzy match
|
||||||
expect(result!.model).toBe("opencode/glm-5")
|
expect(result!.model).toBe("opencode/glm-5")
|
||||||
expect(result!.source).toBe("provider-fallback")
|
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",
|
model: "glm-5",
|
||||||
match: "opencode/glm-5",
|
match: "opencode/glm-5",
|
||||||
variant: undefined,
|
variant: undefined,
|
||||||
@@ -490,7 +488,7 @@ describe("resolveModelWithFallback", () => {
|
|||||||
// then
|
// then
|
||||||
expect(result!.model).toBe("google/gemini-3.1-pro")
|
expect(result!.model).toBe("google/gemini-3.1-pro")
|
||||||
expect(result!.source).toBe("system-default")
|
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", () => {
|
test("returns undefined when availableModels empty and no connected providers cache exists", () => {
|
||||||
|
|||||||
@@ -1,20 +1,25 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from "bun:test"
|
import { describe, it, expect, mock, beforeEach } from "bun:test"
|
||||||
import { getServerBaseUrl, patchPart, deletePart } from "./opencode-http-api"
|
|
||||||
|
|
||||||
// Mock fetch globally
|
type OpencodeHttpApi = typeof import("./opencode-http-api")
|
||||||
const mockFetch = vi.fn()
|
|
||||||
global.fetch = mockFetch
|
|
||||||
|
|
||||||
// Mock log
|
const opencodeHttpApiSpecifier = import.meta.resolve("./opencode-http-api")
|
||||||
vi.mock("./logger", () => ({
|
|
||||||
log: vi.fn(),
|
|
||||||
}))
|
|
||||||
|
|
||||||
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", () => {
|
describe("getServerBaseUrl", () => {
|
||||||
it("returns baseUrl from client._client.getConfig().baseUrl", () => {
|
it("returns baseUrl from client._client.getConfig().baseUrl", async () => {
|
||||||
// given
|
// given
|
||||||
|
const { getServerBaseUrl } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
_client: {
|
_client: {
|
||||||
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
||||||
@@ -28,8 +33,9 @@ describe("getServerBaseUrl", () => {
|
|||||||
expect(result).toBe("https://api.example.com")
|
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
|
// given
|
||||||
|
const { getServerBaseUrl } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
_client: {
|
_client: {
|
||||||
getConfig: () => ({}),
|
getConfig: () => ({}),
|
||||||
@@ -48,8 +54,9 @@ describe("getServerBaseUrl", () => {
|
|||||||
expect(result).toBe("https://session.example.com")
|
expect(result).toBe("https://session.example.com")
|
||||||
})
|
})
|
||||||
|
|
||||||
it("returns null for incompatible client", () => {
|
it("returns null for incompatible client", async () => {
|
||||||
// given
|
// given
|
||||||
|
const { getServerBaseUrl } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {}
|
const mockClient = {}
|
||||||
|
|
||||||
// when
|
// when
|
||||||
@@ -62,14 +69,16 @@ describe("getServerBaseUrl", () => {
|
|||||||
|
|
||||||
describe("patchPart", () => {
|
describe("patchPart", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
log.mockClear()
|
||||||
mockFetch.mockResolvedValue({ ok: true })
|
getServerBasicAuthHeader.mockClear()
|
||||||
process.env.OPENCODE_SERVER_PASSWORD = "testpassword"
|
getServerBasicAuthHeader.mockReturnValue("Basic b3BlbmNvZGU6dGVzdHBhc3N3b3Jk")
|
||||||
process.env.OPENCODE_SERVER_USERNAME = "opencode"
|
fetchImplementation.mockClear()
|
||||||
|
fetchImplementation.mockResolvedValue(new Response(null, { status: 200 }))
|
||||||
})
|
})
|
||||||
|
|
||||||
it("constructs correct URL and sends PATCH with auth", async () => {
|
it("constructs correct URL and sends PATCH with auth", async () => {
|
||||||
// given
|
// given
|
||||||
|
const { patchPart } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
_client: {
|
_client: {
|
||||||
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
||||||
@@ -85,7 +94,7 @@ describe("patchPart", () => {
|
|||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBe(true)
|
expect(result).toBe(true)
|
||||||
expect(mockFetch).toHaveBeenCalledWith(
|
expect(fetchImplementation).toHaveBeenCalledWith(
|
||||||
"https://api.example.com/session/ses123/message/msg456/part/part789",
|
"https://api.example.com/session/ses123/message/msg456/part/part789",
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
@@ -101,12 +110,13 @@ describe("patchPart", () => {
|
|||||||
|
|
||||||
it("returns false on network error", async () => {
|
it("returns false on network error", async () => {
|
||||||
// given
|
// given
|
||||||
|
const { patchPart } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
_client: {
|
_client: {
|
||||||
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
mockFetch.mockRejectedValue(new Error("Network error"))
|
fetchImplementation.mockRejectedValue(new Error("Network error"))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await patchPart(mockClient, "ses123", "msg456", "part789", {})
|
const result = await patchPart(mockClient, "ses123", "msg456", "part789", {})
|
||||||
@@ -122,14 +132,16 @@ describe("patchPart", () => {
|
|||||||
|
|
||||||
describe("deletePart", () => {
|
describe("deletePart", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
log.mockClear()
|
||||||
mockFetch.mockResolvedValue({ ok: true })
|
getServerBasicAuthHeader.mockClear()
|
||||||
process.env.OPENCODE_SERVER_PASSWORD = "testpassword"
|
getServerBasicAuthHeader.mockReturnValue("Basic b3BlbmNvZGU6dGVzdHBhc3N3b3Jk")
|
||||||
process.env.OPENCODE_SERVER_USERNAME = "opencode"
|
fetchImplementation.mockClear()
|
||||||
|
fetchImplementation.mockResolvedValue(new Response(null, { status: 200 }))
|
||||||
})
|
})
|
||||||
|
|
||||||
it("constructs correct URL and sends DELETE", async () => {
|
it("constructs correct URL and sends DELETE", async () => {
|
||||||
// given
|
// given
|
||||||
|
const { deletePart } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
_client: {
|
_client: {
|
||||||
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
||||||
@@ -144,7 +156,7 @@ describe("deletePart", () => {
|
|||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBe(true)
|
expect(result).toBe(true)
|
||||||
expect(mockFetch).toHaveBeenCalledWith(
|
expect(fetchImplementation).toHaveBeenCalledWith(
|
||||||
"https://api.example.com/session/ses123/message/msg456/part/part789",
|
"https://api.example.com/session/ses123/message/msg456/part/part789",
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
@@ -158,12 +170,13 @@ describe("deletePart", () => {
|
|||||||
|
|
||||||
it("returns false on non-ok response", async () => {
|
it("returns false on non-ok response", async () => {
|
||||||
// given
|
// given
|
||||||
|
const { deletePart } = await loadOpencodeHttpApi()
|
||||||
const mockClient = {
|
const mockClient = {
|
||||||
_client: {
|
_client: {
|
||||||
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
getConfig: () => ({ baseUrl: "https://api.example.com" }),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
mockFetch.mockResolvedValue({ ok: false, status: 404 })
|
fetchImplementation.mockResolvedValue(new Response(null, { status: 404 }))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await deletePart(mockClient, "ses123", "msg456", "part789")
|
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",
|
url: "https://api.example.com/session/ses123/message/msg456/part/part789",
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,8 +1,41 @@
|
|||||||
import { getServerBasicAuthHeader } from "./opencode-server-auth"
|
import { getServerBasicAuthHeader as resolveServerBasicAuthHeader } from "./opencode-server-auth"
|
||||||
import { log } from "./logger"
|
import { log as writeLog } from "./logger"
|
||||||
import { isRecord } from "./record-type-guard"
|
import { isRecord } from "./record-type-guard"
|
||||||
|
|
||||||
type UnknownRecord = Record<string, unknown>
|
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 {
|
function getInternalClient(client: unknown): UnknownRecord | null {
|
||||||
if (!isRecord(client)) {
|
if (!isRecord(client)) {
|
||||||
@@ -61,20 +94,20 @@ export async function patchPart(
|
|||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const baseUrl = getServerBaseUrl(client)
|
const baseUrl = getServerBaseUrl(client)
|
||||||
if (!baseUrl) {
|
if (!baseUrl) {
|
||||||
log("[opencode-http-api] Could not extract baseUrl from client")
|
getLogImplementation()("[opencode-http-api] Could not extract baseUrl from client")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
const auth = getServerBasicAuthHeader()
|
const auth = getServerBasicAuthHeaderImplementation()()
|
||||||
if (!auth) {
|
if (!auth) {
|
||||||
log("[opencode-http-api] No auth header available")
|
getLogImplementation()("[opencode-http-api] No auth header available")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = `${baseUrl}/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}/part/${encodeURIComponent(partID)}`
|
const url = `${baseUrl}/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}/part/${encodeURIComponent(partID)}`
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {
|
const response = await getFetchImplementation()(url, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -85,14 +118,14 @@ export async function patchPart(
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
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 false
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(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
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,20 +138,20 @@ export async function deletePart(
|
|||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const baseUrl = getServerBaseUrl(client)
|
const baseUrl = getServerBaseUrl(client)
|
||||||
if (!baseUrl) {
|
if (!baseUrl) {
|
||||||
log("[opencode-http-api] Could not extract baseUrl from client")
|
getLogImplementation()("[opencode-http-api] Could not extract baseUrl from client")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
const auth = getServerBasicAuthHeader()
|
const auth = getServerBasicAuthHeaderImplementation()()
|
||||||
if (!auth) {
|
if (!auth) {
|
||||||
log("[opencode-http-api] No auth header available")
|
getLogImplementation()("[opencode-http-api] No auth header available")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = `${baseUrl}/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}/part/${encodeURIComponent(partID)}`
|
const url = `${baseUrl}/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}/part/${encodeURIComponent(partID)}`
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {
|
const response = await getFetchImplementation()(url, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
"Authorization": auth,
|
"Authorization": auth,
|
||||||
@@ -127,14 +160,14 @@ export async function deletePart(
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (!response.ok) {
|
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 false
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(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
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, test, expect, beforeEach, afterEach, mock } from "bun:test"
|
import { describe, test, expect, beforeEach, afterEach } from "bun:test"
|
||||||
import {
|
import {
|
||||||
isInsideTmux,
|
isInsideTmux,
|
||||||
isServerRunning,
|
isServerRunning,
|
||||||
@@ -9,15 +9,22 @@ import {
|
|||||||
applyLayout,
|
applyLayout,
|
||||||
} from "./tmux-utils"
|
} from "./tmux-utils"
|
||||||
import { isInsideTmuxEnvironment } from "./tmux-utils/environment"
|
import { isInsideTmuxEnvironment } from "./tmux-utils/environment"
|
||||||
|
import { createServerHealthStateForTesting } from "./tmux-utils/server-health"
|
||||||
|
|
||||||
function createFetchMock(responseFactory: () => Promise<Response>): typeof fetch & ReturnType<typeof mock> {
|
function createFetchRecorder(responseFactory: () => Promise<Response>): typeof fetch & { calls: Array<[RequestInfo | URL, RequestInit | undefined]> } {
|
||||||
const fetchMock = mock(async (_input: RequestInfo | URL, _init?: RequestInit) => responseFactory())
|
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)
|
const preconnect = globalThis.fetch.preconnect?.bind(globalThis.fetch)
|
||||||
return Object.assign(fetchMock, {
|
return Object.assign(fetchRecorder, {
|
||||||
|
calls,
|
||||||
preconnect,
|
preconnect,
|
||||||
}) as typeof fetch & ReturnType<typeof mock>
|
}) as typeof fetch & { calls: Array<[RequestInfo | URL, RequestInit | undefined]> }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
describe("isInsideTmux", () => {
|
describe("isInsideTmux", () => {
|
||||||
test("returns true when TMUX env is set", () => {
|
test("returns true when TMUX env is set", () => {
|
||||||
// given
|
// given
|
||||||
@@ -62,22 +69,17 @@ describe("isInsideTmux", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe("isServerRunning", () => {
|
describe("isServerRunning", () => {
|
||||||
const originalFetch = globalThis.fetch
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
resetServerCheck()
|
resetServerCheck()
|
||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
globalThis.fetch = originalFetch
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns true when server responds OK", async () => {
|
test("returns true when server responds OK", async () => {
|
||||||
// given
|
// given
|
||||||
globalThis.fetch = createFetchMock(async () => new Response(null, { status: 200 }))
|
const state = createServerHealthStateForTesting()
|
||||||
|
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await isServerRunning("http://localhost:4096")
|
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBe(true)
|
expect(result).toBe(true)
|
||||||
@@ -85,12 +87,13 @@ describe("isServerRunning", () => {
|
|||||||
|
|
||||||
test("returns false when server not reachable", async () => {
|
test("returns false when server not reachable", async () => {
|
||||||
// given
|
// given
|
||||||
globalThis.fetch = createFetchMock(async () => {
|
const state = createServerHealthStateForTesting()
|
||||||
|
const fetchMock = createFetchRecorder(async () => {
|
||||||
throw new Error("ECONNREFUSED")
|
throw new Error("ECONNREFUSED")
|
||||||
})
|
})
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await isServerRunning("http://localhost:4096")
|
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBe(false)
|
expect(result).toBe(false)
|
||||||
@@ -98,10 +101,11 @@ describe("isServerRunning", () => {
|
|||||||
|
|
||||||
test("returns false when fetch returns not ok", async () => {
|
test("returns false when fetch returns not ok", async () => {
|
||||||
// given
|
// given
|
||||||
globalThis.fetch = createFetchMock(async () => new Response(null, { status: 500 }))
|
const state = createServerHealthStateForTesting()
|
||||||
|
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 500 }))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await isServerRunning("http://localhost:4096")
|
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBe(false)
|
expect(result).toBe(false)
|
||||||
@@ -109,43 +113,43 @@ describe("isServerRunning", () => {
|
|||||||
|
|
||||||
test("caches successful result", async () => {
|
test("caches successful result", async () => {
|
||||||
// given
|
// given
|
||||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
const state = createServerHealthStateForTesting()
|
||||||
globalThis.fetch = fetchMock
|
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
await isServerRunning("http://localhost:4096")
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
await isServerRunning("http://localhost:4096")
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then - should only call fetch once due to caching
|
// 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 () => {
|
test("does not cache failed result", async () => {
|
||||||
// given
|
// given
|
||||||
const fetchMock = createFetchMock(async () => {
|
const state = createServerHealthStateForTesting()
|
||||||
|
const fetchMock = createFetchRecorder(async () => {
|
||||||
throw new Error("ECONNREFUSED")
|
throw new Error("ECONNREFUSED")
|
||||||
})
|
})
|
||||||
globalThis.fetch = fetchMock
|
|
||||||
|
|
||||||
// when
|
// when
|
||||||
await isServerRunning("http://localhost:4096")
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
await isServerRunning("http://localhost:4096")
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then - should call fetch 4 times (2 attempts per call, 2 calls)
|
// 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 () => {
|
test("uses different cache for different URLs", async () => {
|
||||||
// given
|
// given
|
||||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
const state = createServerHealthStateForTesting()
|
||||||
globalThis.fetch = fetchMock
|
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
await isServerRunning("http://localhost:4096")
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
await isServerRunning("http://localhost:5000")
|
await isServerRunning("http://localhost:5000", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then - should call fetch twice for different URLs
|
// 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 () => {
|
test("allows re-checking after reset", async () => {
|
||||||
// given
|
// given
|
||||||
const originalFetch = globalThis.fetch
|
const state = createServerHealthStateForTesting()
|
||||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||||
globalThis.fetch = fetchMock
|
|
||||||
|
|
||||||
// when
|
// when
|
||||||
await isServerRunning("http://localhost:4096")
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
resetServerCheck()
|
state.serverAvailable = null
|
||||||
await isServerRunning("http://localhost:4096")
|
state.serverCheckUrl = null
|
||||||
|
await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then - should call fetch twice after reset
|
// 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", () => {
|
describe("markServerRunningInProcess", () => {
|
||||||
const originalFetch = globalThis.fetch
|
|
||||||
const SERVER_RUNNING_KEY = Symbol.for("oh-my-opencode:server-running-in-process")
|
const SERVER_RUNNING_KEY = Symbol.for("oh-my-opencode:server-running-in-process")
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -184,22 +185,21 @@ describe("markServerRunningInProcess", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
globalThis.fetch = originalFetch
|
|
||||||
delete (globalThis as Record<symbol, boolean>)[SERVER_RUNNING_KEY]
|
delete (globalThis as Record<symbol, boolean>)[SERVER_RUNNING_KEY]
|
||||||
})
|
})
|
||||||
|
|
||||||
test("skips HTTP fetch when marked as running in-process", async () => {
|
test("skips HTTP fetch when marked as running in-process", async () => {
|
||||||
// given
|
// given
|
||||||
const fetchMock = createFetchMock(async () => new Response(null, { status: 200 }))
|
const state = createServerHealthStateForTesting()
|
||||||
globalThis.fetch = fetchMock
|
state.serverRunningInProcess = true
|
||||||
markServerRunningInProcess()
|
const fetchMock = createFetchRecorder(async () => new Response(null, { status: 200 }))
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const result = await isServerRunning("http://localhost:4096")
|
const result = await isServerRunning("http://localhost:4096", { fetchImplementation: fetchMock, state })
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(result).toBe(true)
|
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", () => {
|
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")
|
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> {
|
function delay(milliseconds: number): Promise<void> {
|
||||||
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
||||||
}
|
}
|
||||||
@@ -15,12 +26,25 @@ function isMarkedRunningInProcess(): boolean {
|
|||||||
return (globalThis as Record<symbol, boolean>)[SERVER_RUNNING_KEY] === true
|
return (globalThis as Record<symbol, boolean>)[SERVER_RUNNING_KEY] === true
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function isServerRunning(serverUrl: string): Promise<boolean> {
|
export function createServerHealthStateForTesting(): ServerHealthState {
|
||||||
if (isMarkedRunningInProcess()) {
|
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
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
if (serverCheckUrl === serverUrl && serverAvailable === true) {
|
const cachedUrl = state?.serverCheckUrl ?? serverCheckUrl
|
||||||
|
const cachedAvailable = state?.serverAvailable ?? serverAvailable
|
||||||
|
if (cachedUrl === serverUrl && cachedAvailable === true) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,14 +57,19 @@ export async function isServerRunning(serverUrl: string): Promise<boolean> {
|
|||||||
const timeout = setTimeout(() => controller.abort(), timeoutMs)
|
const timeout = setTimeout(() => controller.abort(), timeoutMs)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(healthUrl, {
|
const response = await fetchImplementation(healthUrl, {
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
}).catch(() => null)
|
}).catch(() => null)
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
|
|
||||||
if (response?.ok) {
|
if (response?.ok) {
|
||||||
serverCheckUrl = serverUrl
|
if (state) {
|
||||||
serverAvailable = true
|
state.serverCheckUrl = serverUrl
|
||||||
|
state.serverAvailable = true
|
||||||
|
} else {
|
||||||
|
serverCheckUrl = serverUrl
|
||||||
|
serverAvailable = true
|
||||||
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
} finally {
|
} 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 { TmuxConfig } from "../../../config/schema"
|
||||||
import type { TmuxCommandResult } from "../runner"
|
import type { TmuxCommandResult } from "../runner"
|
||||||
|
import { spawnTmuxSession } from "./session-spawn"
|
||||||
const sessionSpawnSpecifier = import.meta.resolve("./session-spawn")
|
|
||||||
|
|
||||||
const enabledTmuxConfig = {
|
const enabledTmuxConfig = {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
@@ -14,17 +13,7 @@ const enabledTmuxConfig = {
|
|||||||
isolation: "inline",
|
isolation: "inline",
|
||||||
} satisfies TmuxConfig
|
} satisfies TmuxConfig
|
||||||
|
|
||||||
const runTmuxCommandMock = mock(async (): Promise<TmuxCommandResult> => ({
|
type SpawnTmuxSessionDeps = NonNullable<Parameters<typeof spawnTmuxSession>[6]>
|
||||||
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)
|
|
||||||
|
|
||||||
function toStringArray(value: unknown): string[] {
|
function toStringArray(value: unknown): string[] {
|
||||||
if (!Array.isArray(value)) {
|
if (!Array.isArray(value)) {
|
||||||
@@ -38,83 +27,74 @@ function toStringArray(value: unknown): string[] {
|
|||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRunTmuxCommandCall(index: number): [string, string[]] {
|
function defaultTmuxCommandResults(): TmuxCommandResult[] {
|
||||||
const call = Reflect.get(runTmuxCommandMock.mock.calls, index)
|
return [
|
||||||
const command = Reflect.get(call, 0)
|
{ success: true, output: "120,40", stdout: "120,40", stderr: "", exitCode: 0 },
|
||||||
const args = Reflect.get(call, 1)
|
{ success: false, output: "", stdout: "", stderr: "", exitCode: 1 },
|
||||||
if (!Array.isArray(call) || typeof command !== "string" || !Array.isArray(args)) {
|
{ success: true, output: "%42", stdout: "%42", stderr: "", exitCode: 0 },
|
||||||
throw new Error(`Expected tmux runner call at index ${index}`)
|
{ success: true, output: "", stdout: "", stderr: "", exitCode: 0 },
|
||||||
}
|
]
|
||||||
|
|
||||||
return [command, toStringArray(args)]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getSpawnCommand(): string {
|
function createHarness() {
|
||||||
const newSessionCall = getRunTmuxCommandCall(2)
|
const calls: Array<[string, string[]]> = []
|
||||||
const newSessionCommand = newSessionCall[1][newSessionCall[1].length - 1]
|
const logs: string[] = []
|
||||||
if (newSessionCommand === undefined) {
|
const tmuxCommandResults = defaultTmuxCommandResults()
|
||||||
throw new Error("Expected new-session command")
|
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 [call[0], toStringArray(call[1])]
|
||||||
return {
|
|
||||||
log: logMock,
|
|
||||||
runTmuxCommand: runTmuxCommandMock,
|
|
||||||
isInsideTmux: isInsideTmuxMock,
|
|
||||||
isServerRunning: isServerRunningMock,
|
|
||||||
getTmuxPath: getTmuxPathMock,
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
async function loadSpawnTmuxSession(): Promise<typeof import("./session-spawn").spawnTmuxSession> {
|
function getSpawnCommand(): string {
|
||||||
const module = await import(`${sessionSpawnSpecifier}?test=${crypto.randomUUID()}`)
|
const newSessionCall = getRunTmuxCommandCall(2)
|
||||||
return module.spawnTmuxSession
|
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", () => {
|
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 () => {
|
it("#given source pane available #when spawnTmuxSession called #then delegates display, has-session, new-session, and select-pane to shared runner", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
const harness = createHarness()
|
||||||
const directory = "/tmp/omo-project/(session)"
|
const directory = "/tmp/omo-project/(session)"
|
||||||
|
|
||||||
// when
|
// 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
|
// then
|
||||||
const displayCall = getRunTmuxCommandCall(0)
|
|
||||||
const hasSessionCall = getRunTmuxCommandCall(1)
|
|
||||||
const newSessionCall = getRunTmuxCommandCall(2)
|
|
||||||
const selectPaneCall = getRunTmuxCommandCall(3)
|
|
||||||
expect(result).toEqual({ success: true, paneId: "%42" })
|
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(displayCall[1]).toEqual(["display", "-p", "-t", "%0", "#{window_width},#{window_height}"])
|
||||||
expect(hasSessionCall[1][0]).toBe("has-session")
|
expect(hasSessionCall[1][0]).toBe("has-session")
|
||||||
expect(hasSessionCall[1][1]).toBe("-t")
|
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(newSessionCall[1].slice(0, 4)).toEqual(["new-session", "-d", "-s", newSessionCall[1][3]])
|
||||||
expect(String(newSessionCall[1][3]).startsWith("omo-agents-")).toBe(true)
|
expect(String(newSessionCall[1][3]).startsWith("omo-agents-")).toBe(true)
|
||||||
expect(selectPaneCall[1]).toEqual(["select-pane", "-t", "%42", "-T", "omo-subagent-worker"])
|
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 () => {
|
it("#given directory with spaces #when spawnTmuxSession called #then wraps --dir value in single quotes", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
const harness = createHarness()
|
||||||
|
|
||||||
// when
|
// 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
|
// 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 () => {
|
it("#given empty directory #when spawnTmuxSession called #then falls back to process cwd", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
const harness = createHarness()
|
||||||
|
|
||||||
// when
|
// 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
|
// 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 () => {
|
it("#given directory with single quotes #when spawnTmuxSession called #then escapes the value with POSIX-safe single quoting", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxSession = await loadSpawnTmuxSession()
|
const harness = createHarness()
|
||||||
|
|
||||||
// when
|
// 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
|
// 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 { TmuxConfig } from "../../../config/schema"
|
||||||
import type { TmuxCommandResult } from "../runner"
|
import type { TmuxCommandResult } from "../runner"
|
||||||
|
import { spawnTmuxWindow } from "./window-spawn"
|
||||||
const windowSpawnSpecifier = import.meta.resolve("./window-spawn")
|
|
||||||
|
|
||||||
const enabledTmuxConfig = {
|
const enabledTmuxConfig = {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
@@ -14,17 +13,7 @@ const enabledTmuxConfig = {
|
|||||||
isolation: "inline",
|
isolation: "inline",
|
||||||
} satisfies TmuxConfig
|
} satisfies TmuxConfig
|
||||||
|
|
||||||
const runTmuxCommandMock = mock(async (): Promise<TmuxCommandResult> => ({
|
type SpawnTmuxWindowDeps = NonNullable<Parameters<typeof spawnTmuxWindow>[5]>
|
||||||
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)
|
|
||||||
|
|
||||||
function toStringArray(value: unknown): string[] {
|
function toStringArray(value: unknown): string[] {
|
||||||
if (!Array.isArray(value)) {
|
if (!Array.isArray(value)) {
|
||||||
@@ -38,114 +27,102 @@ function toStringArray(value: unknown): string[] {
|
|||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRunTmuxCommandCall(index: number): [string, string[]] {
|
function defaultTmuxCommandResults(): TmuxCommandResult[] {
|
||||||
const call = Reflect.get(runTmuxCommandMock.mock.calls, index)
|
return [
|
||||||
const command = Reflect.get(call, 0)
|
{ success: true, output: "%42", stdout: "%42", stderr: "", exitCode: 0 },
|
||||||
const args = Reflect.get(call, 1)
|
{ success: true, output: "", stdout: "", stderr: "", exitCode: 0 },
|
||||||
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 getNewWindowCommand(): string {
|
function createHarness() {
|
||||||
const firstCall = getRunTmuxCommandCall(0)
|
const calls: Array<[string, string[]]> = []
|
||||||
const newWindowCommand = firstCall[1][7]
|
const tmuxCommandResults = defaultTmuxCommandResults()
|
||||||
if (newWindowCommand === undefined) {
|
const runTmuxCommand = async (command: string, args: string[]): Promise<TmuxCommandResult> => {
|
||||||
throw new Error("Expected new-window command")
|
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 [call[0], toStringArray(call[1])]
|
||||||
return {
|
|
||||||
log: logMock,
|
|
||||||
runTmuxCommand: runTmuxCommandMock,
|
|
||||||
isInsideTmux: isInsideTmuxMock,
|
|
||||||
isServerRunning: isServerRunningMock,
|
|
||||||
getTmuxPath: getTmuxPathMock,
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
async function loadSpawnTmuxWindow(): Promise<typeof import("./window-spawn").spawnTmuxWindow> {
|
function getNewWindowCommand(): string {
|
||||||
const module = await import(`${windowSpawnSpecifier}?test=${crypto.randomUUID()}`)
|
const firstCall = getRunTmuxCommandCall(0)
|
||||||
return module.spawnTmuxWindow
|
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", () => {
|
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 () => {
|
it("#given healthy tmux environment #when spawnTmuxWindow called #then delegates new-window and select-pane to shared runner", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
const harness = createHarness()
|
||||||
const directory = "/tmp/omo-project/(window)"
|
const directory = "/tmp/omo-project/(window)"
|
||||||
|
|
||||||
// when
|
// 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
|
// then
|
||||||
const firstCall = getRunTmuxCommandCall(0)
|
const firstCall = harness.getRunTmuxCommandCall(0)
|
||||||
const secondCall = getRunTmuxCommandCall(1)
|
const secondCall = harness.getRunTmuxCommandCall(1)
|
||||||
expect(result).toEqual({ success: true, paneId: "%42" })
|
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(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(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 () => {
|
it("#given directory with spaces #when spawnTmuxWindow called #then wraps --dir value in single quotes", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
const harness = createHarness()
|
||||||
|
|
||||||
// when
|
// 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
|
// 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 () => {
|
it("#given empty directory #when spawnTmuxWindow called #then falls back to process cwd", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
const harness = createHarness()
|
||||||
|
|
||||||
// when
|
// 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
|
// 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 () => {
|
it("#given directory with single quotes #when spawnTmuxWindow called #then escapes the value with POSIX-safe single quoting", async () => {
|
||||||
// given
|
// given
|
||||||
const spawnTmuxWindow = await loadSpawnTmuxWindow()
|
const harness = createHarness()
|
||||||
|
|
||||||
// when
|
// 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
|
// then
|
||||||
expect(getNewWindowCommand()).toContain("--dir '/path/with'\\''quote'")
|
expect(harness.getNewWindowCommand()).toContain("--dir '/path/with'\\''quote'")
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -31,6 +31,36 @@ describe("installModuleMockLifecycle", () => {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test("restores original exports after the delegate restore runs", () => {
|
||||||
|
// given
|
||||||
|
const events: string[] = []
|
||||||
|
const mockApi = {
|
||||||
|
module: (specifier: string, factory: () => Record<string, unknown>) => {
|
||||||
|
events.push(`module:${specifier}:${String(factory().named)}`)
|
||||||
|
},
|
||||||
|
restore: mock(() => {
|
||||||
|
events.push("delegate:restore")
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
installModuleMockLifecycle(mockApi, {
|
||||||
|
getCallerUrl: () => "file:///repo/tests/example.test.ts",
|
||||||
|
resolveSpecifier: (specifier) => `resolved:${specifier}`,
|
||||||
|
loadOriginalModule: () => ({ ok: true, value: { named: "original" } }),
|
||||||
|
})
|
||||||
|
|
||||||
|
// when
|
||||||
|
mockApi.module("./dependency", () => ({ named: "mocked" }))
|
||||||
|
mockApi.restore()
|
||||||
|
|
||||||
|
// then
|
||||||
|
expect(events).toEqual([
|
||||||
|
"module:./dependency:mocked",
|
||||||
|
"delegate:restore",
|
||||||
|
"module:resolved:./dependency:original",
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
test("captures the original module only once per resolved specifier", () => {
|
test("captures the original module only once per resolved specifier", () => {
|
||||||
// given
|
// given
|
||||||
let loadCount = 0
|
let loadCount = 0
|
||||||
|
|||||||
@@ -135,8 +135,9 @@ export function installModuleMockLifecycle(
|
|||||||
}
|
}
|
||||||
|
|
||||||
mockApi.restore = (): unknown => {
|
mockApi.restore = (): unknown => {
|
||||||
|
const result = delegateRestore()
|
||||||
restoreModuleMocks()
|
restoreModuleMocks()
|
||||||
return delegateRestore()
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
return { restoreModuleMocks }
|
return { restoreModuleMocks }
|
||||||
|
|||||||
@@ -1,19 +1,7 @@
|
|||||||
/// <reference types="bun-types" />
|
/// <reference types="bun-types" />
|
||||||
|
|
||||||
import { describe, expect, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
import type { ToolContext } from "@opencode-ai/plugin/tool"
|
import { executeInteractiveBash } from "./tools"
|
||||||
import { interactive_bash } from "./tools"
|
|
||||||
|
|
||||||
const mockContext = {
|
|
||||||
sessionID: "test-session",
|
|
||||||
messageID: "test-message",
|
|
||||||
agent: "test-agent",
|
|
||||||
directory: "/project",
|
|
||||||
worktree: "/project",
|
|
||||||
abort: new AbortController().signal,
|
|
||||||
metadata: () => {},
|
|
||||||
ask: async () => {},
|
|
||||||
} satisfies ToolContext
|
|
||||||
|
|
||||||
describe("interactive_bash", () => {
|
describe("interactive_bash", () => {
|
||||||
test("#given kill-server command #when executed #then returns a strong prohibition without running tmux", async () => {
|
test("#given kill-server command #when executed #then returns a strong prohibition without running tmux", async () => {
|
||||||
@@ -21,7 +9,7 @@ describe("interactive_bash", () => {
|
|||||||
const args = { tmux_command: "kill-server" }
|
const args = { tmux_command: "kill-server" }
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const output = await interactive_bash.execute(args, mockContext)
|
const output = await executeInteractiveBash(args)
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(output).toContain("Error: 'kill-server' is prohibited in interactive_bash.")
|
expect(output).toContain("Error: 'kill-server' is prohibited in interactive_bash.")
|
||||||
@@ -34,7 +22,7 @@ describe("interactive_bash", () => {
|
|||||||
const args = { tmux_command: "-L omo-socket kill-server" }
|
const args = { tmux_command: "-L omo-socket kill-server" }
|
||||||
|
|
||||||
// when
|
// when
|
||||||
const output = await interactive_bash.execute(args, mockContext)
|
const output = await executeInteractiveBash(args)
|
||||||
|
|
||||||
// then
|
// then
|
||||||
expect(output).toContain("Error: 'kill-server' is prohibited in interactive_bash.")
|
expect(output).toContain("Error: 'kill-server' is prohibited in interactive_bash.")
|
||||||
|
|||||||
@@ -144,74 +144,80 @@ tmux kill-session -t <session-name>
|
|||||||
If you created an omo-* session, kill only that exact session. Do not retry kill-server with Bash or any other tool.`
|
If you created an omo-* session, kill only that exact session. Do not retry kill-server with Bash or any other tool.`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type InteractiveBashArgs = {
|
||||||
|
tmux_command: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function executeInteractiveBash(args: InteractiveBashArgs): Promise<string> {
|
||||||
|
try {
|
||||||
|
const tmuxPath = getCachedTmuxPath() ?? "tmux"
|
||||||
|
|
||||||
|
const parts = tokenizeCommand(args.tmux_command)
|
||||||
|
|
||||||
|
if (parts.length === 0) {
|
||||||
|
return "Error: Empty tmux command"
|
||||||
|
}
|
||||||
|
|
||||||
|
const subcommandIndex = findSubcommandIndex(parts)
|
||||||
|
const rawSubcommand = subcommandIndex === -1 ? "" : parts[subcommandIndex]
|
||||||
|
const subcommand = rawSubcommand.toLowerCase()
|
||||||
|
|
||||||
|
if (PROHIBITED_TMUX_SUBCOMMANDS.includes(subcommand)) {
|
||||||
|
return buildProhibitedTmuxCommandMessage(rawSubcommand)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (BLOCKED_TMUX_SUBCOMMANDS.includes(subcommand)) {
|
||||||
|
return buildBlockedTmuxCommandMessage(rawSubcommand, parts)
|
||||||
|
}
|
||||||
|
|
||||||
|
const proc = spawnWithWindowsHide([...resolveTmuxExecutable(tmuxPath), ...parts], {
|
||||||
|
stdout: "pipe",
|
||||||
|
stderr: "pipe",
|
||||||
|
})
|
||||||
|
|
||||||
|
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||||
|
const id = setTimeout(() => {
|
||||||
|
const timeoutError = new Error(`Timeout after ${DEFAULT_TIMEOUT_MS}ms`)
|
||||||
|
try {
|
||||||
|
proc.kill()
|
||||||
|
// Fire-and-forget: wait for process exit in background to avoid zombies
|
||||||
|
void proc.exited.catch(() => {})
|
||||||
|
} catch {
|
||||||
|
// Ignore kill errors; we'll still reject with timeoutError below
|
||||||
|
}
|
||||||
|
reject(timeoutError)
|
||||||
|
}, DEFAULT_TIMEOUT_MS)
|
||||||
|
proc.exited
|
||||||
|
.then(() => clearTimeout(id))
|
||||||
|
.catch(() => clearTimeout(id))
|
||||||
|
})
|
||||||
|
|
||||||
|
// Read stdout and stderr in parallel to avoid race conditions
|
||||||
|
const [stdout, stderr, exitCode] = await Promise.race([
|
||||||
|
Promise.all([
|
||||||
|
new Response(proc.stdout).text(),
|
||||||
|
new Response(proc.stderr).text(),
|
||||||
|
proc.exited,
|
||||||
|
]),
|
||||||
|
timeoutPromise,
|
||||||
|
])
|
||||||
|
|
||||||
|
// Check exitCode properly - return error even if stderr is empty
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
const errorMsg = stderr.trim() || `Command failed with exit code ${exitCode}`
|
||||||
|
return `Error: ${errorMsg}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return stdout || "(no output)"
|
||||||
|
} catch (e) {
|
||||||
|
return `Error: ${e instanceof Error ? e.message : String(e)}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const interactive_bash: ToolDefinition = tool({
|
export const interactive_bash: ToolDefinition = tool({
|
||||||
description: INTERACTIVE_BASH_DESCRIPTION,
|
description: INTERACTIVE_BASH_DESCRIPTION,
|
||||||
args: {
|
args: {
|
||||||
tmux_command: tool.schema.string().describe("The tmux command to execute (without 'tmux' prefix)"),
|
tmux_command: tool.schema.string().describe("The tmux command to execute (without 'tmux' prefix)"),
|
||||||
},
|
},
|
||||||
execute: async (args) => {
|
execute: executeInteractiveBash,
|
||||||
try {
|
|
||||||
const tmuxPath = getCachedTmuxPath() ?? "tmux"
|
|
||||||
|
|
||||||
const parts = tokenizeCommand(args.tmux_command)
|
|
||||||
|
|
||||||
if (parts.length === 0) {
|
|
||||||
return "Error: Empty tmux command"
|
|
||||||
}
|
|
||||||
|
|
||||||
const subcommandIndex = findSubcommandIndex(parts)
|
|
||||||
const rawSubcommand = subcommandIndex === -1 ? "" : parts[subcommandIndex]
|
|
||||||
const subcommand = rawSubcommand.toLowerCase()
|
|
||||||
|
|
||||||
if (PROHIBITED_TMUX_SUBCOMMANDS.includes(subcommand)) {
|
|
||||||
return buildProhibitedTmuxCommandMessage(rawSubcommand)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (BLOCKED_TMUX_SUBCOMMANDS.includes(subcommand)) {
|
|
||||||
return buildBlockedTmuxCommandMessage(rawSubcommand, parts)
|
|
||||||
}
|
|
||||||
|
|
||||||
const proc = spawnWithWindowsHide([...resolveTmuxExecutable(tmuxPath), ...parts], {
|
|
||||||
stdout: "pipe",
|
|
||||||
stderr: "pipe",
|
|
||||||
})
|
|
||||||
|
|
||||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
||||||
const id = setTimeout(() => {
|
|
||||||
const timeoutError = new Error(`Timeout after ${DEFAULT_TIMEOUT_MS}ms`)
|
|
||||||
try {
|
|
||||||
proc.kill()
|
|
||||||
// Fire-and-forget: wait for process exit in background to avoid zombies
|
|
||||||
void proc.exited.catch(() => {})
|
|
||||||
} catch {
|
|
||||||
// Ignore kill errors; we'll still reject with timeoutError below
|
|
||||||
}
|
|
||||||
reject(timeoutError)
|
|
||||||
}, DEFAULT_TIMEOUT_MS)
|
|
||||||
proc.exited
|
|
||||||
.then(() => clearTimeout(id))
|
|
||||||
.catch(() => clearTimeout(id))
|
|
||||||
})
|
|
||||||
|
|
||||||
// Read stdout and stderr in parallel to avoid race conditions
|
|
||||||
const [stdout, stderr, exitCode] = await Promise.race([
|
|
||||||
Promise.all([
|
|
||||||
new Response(proc.stdout).text(),
|
|
||||||
new Response(proc.stderr).text(),
|
|
||||||
proc.exited,
|
|
||||||
]),
|
|
||||||
timeoutPromise,
|
|
||||||
])
|
|
||||||
|
|
||||||
// Check exitCode properly - return error even if stderr is empty
|
|
||||||
if (exitCode !== 0) {
|
|
||||||
const errorMsg = stderr.trim() || `Command failed with exit code ${exitCode}`
|
|
||||||
return `Error: ${errorMsg}`
|
|
||||||
}
|
|
||||||
|
|
||||||
return stdout || "(no output)"
|
|
||||||
} catch (e) {
|
|
||||||
return `Error: ${e instanceof Error ? e.message : String(e)}`
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user