Skip to content

Commit 52e2322

Browse files
committed
refactor(cli): extract option resolution helpers
1 parent 721d2c8 commit 52e2322

3 files changed

Lines changed: 220 additions & 28 deletions

File tree

‎apps/cli/src/commands/cli/__tests__/list.test.ts‎

Lines changed: 114 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,45 @@
1-
import { providerIdentifiers } from "@roo-code/types"
1+
import fs from "fs"
2+
import os from "os"
3+
import path from "path"
4+
import { EventEmitter } from "events"
5+
6+
import { openRouterDefaultModelId, providerIdentifiers } from "@roo-code/types"
27

38
import { readWorkspaceTaskSessions } from "@/lib/task-history/index.js"
4-
import { isRecord } from "@/lib/utils/guards.js"
59

6-
import { listSessions, parseFormat } from "../list.js"
10+
import { listModels, listSessions, parseFormat } from "../list.js"
11+
12+
const extensionHostMock = vi.hoisted(() => ({
13+
activate: vi.fn(async () => undefined),
14+
dispose: vi.fn(async () => undefined),
15+
options: [] as unknown[],
16+
responses: [] as unknown[],
17+
sendToExtension: vi.fn(),
18+
}))
19+
20+
vi.mock("@/agent/index.js", () => ({
21+
ExtensionHost: class extends EventEmitter {
22+
client = {
23+
isInitialized: () => true,
24+
on: vi.fn(() => () => undefined),
25+
}
26+
27+
constructor(options: unknown) {
28+
super()
29+
extensionHostMock.options.push(options)
30+
}
31+
32+
activate = extensionHostMock.activate
33+
dispose = extensionHostMock.dispose
34+
35+
sendToExtension(message: unknown): void {
36+
extensionHostMock.sendToExtension(message)
37+
for (const response of extensionHostMock.responses) {
38+
this.emit("extensionWebviewMessage", response)
39+
}
40+
}
41+
},
42+
}))
743

844
vi.mock("@/lib/task-history/index.js", async (importOriginal) => {
945
const actual = await importOriginal<typeof import("@/lib/task-history/index.js")>()
@@ -41,30 +77,88 @@ describe("parseFormat", () => {
4177
})
4278
})
4379

44-
describe("router model extraction", () => {
45-
// This mirrors the extraction logic in requestOpenRouterModels (list.ts:226-228)
46-
const extractOpenRouterModels = (routerModelsRaw: unknown) => {
47-
const routerModels = isRecord(routerModelsRaw) ? routerModelsRaw : {}
48-
const openRouterModels = routerModels[providerIdentifiers.openrouter]
49-
return isRecord(openRouterModels) ? openRouterModels : {}
50-
}
80+
describe("listModels", () => {
81+
let tempDir: string
82+
let workspacePath: string
83+
let extensionPath: string
5184

52-
it("extracts openrouter models from valid routerModels", () => {
53-
const models = { "openai/gpt-4.1": { contextWindow: 128000, supportsPromptCache: false } }
54-
const result = extractOpenRouterModels({ [providerIdentifiers.openrouter]: models })
55-
expect(result).toEqual(models)
85+
beforeEach(() => {
86+
vi.clearAllMocks()
87+
extensionHostMock.options.length = 0
88+
extensionHostMock.responses.length = 0
89+
90+
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "roo-list-test-"))
91+
workspacePath = path.join(tempDir, "workspace")
92+
extensionPath = path.join(tempDir, "extension")
93+
fs.mkdirSync(workspacePath)
94+
fs.mkdirSync(extensionPath)
95+
fs.writeFileSync(path.join(extensionPath, "extension.js"), "")
5696
})
5797

58-
it("returns empty object when routerModels is null", () => {
59-
expect(extractOpenRouterModels(null)).toEqual({})
98+
afterEach(() => {
99+
fs.rmSync(tempDir, { recursive: true, force: true })
100+
vi.restoreAllMocks()
60101
})
61102

62-
it("returns empty object when openrouter key is missing", () => {
63-
expect(extractOpenRouterModels({ [providerIdentifiers.requesty]: {} })).toEqual({})
103+
const captureStdout = async (fn: () => Promise<void>): Promise<string> => {
104+
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true)
105+
await fn()
106+
return stdoutSpy.mock.calls.map(([chunk]) => String(chunk)).join("")
107+
}
108+
109+
it("creates a host with resolved paths and returns OpenRouter models", async () => {
110+
const models = { "openai/gpt-4.1": { contextWindow: 128000, supportsPromptCache: false } }
111+
extensionHostMock.responses.push(
112+
{ type: "unrelatedMessage" },
113+
{ type: "routerModels", routerModels: { [providerIdentifiers.openrouter]: models } },
114+
)
115+
116+
const output = await captureStdout(() =>
117+
listModels({
118+
format: "json",
119+
workspace: path.relative(process.cwd(), workspacePath),
120+
extension: path.relative(process.cwd(), extensionPath),
121+
apiKey: "test-api-key",
122+
debug: true,
123+
}),
124+
)
125+
126+
expect(extensionHostMock.options).toEqual([
127+
expect.objectContaining({
128+
mode: "code",
129+
provider: providerIdentifiers.openrouter,
130+
model: openRouterDefaultModelId,
131+
apiKey: "test-api-key",
132+
workspacePath,
133+
extensionPath,
134+
nonInteractive: true,
135+
ephemeral: true,
136+
debug: true,
137+
exitOnComplete: true,
138+
exitOnError: false,
139+
disableOutput: true,
140+
}),
141+
])
142+
expect(extensionHostMock.activate).toHaveBeenCalledOnce()
143+
expect(extensionHostMock.sendToExtension).toHaveBeenCalledWith({
144+
type: "requestRouterModels",
145+
values: { provider: providerIdentifiers.openrouter },
146+
})
147+
expect(extensionHostMock.dispose).toHaveBeenCalledOnce()
148+
expect(JSON.parse(output)).toEqual({ models })
64149
})
65150

66-
it("returns empty object when openrouter value is not a record", () => {
67-
expect(extractOpenRouterModels({ [providerIdentifiers.openrouter]: "invalid" })).toEqual({})
151+
it.each([
152+
["a malformed routerModels value", null],
153+
["a malformed OpenRouter value", { [providerIdentifiers.openrouter]: "invalid" }],
154+
])("returns an empty model record for %s", async (_description, routerModels) => {
155+
extensionHostMock.responses.push({ type: "routerModels", routerModels })
156+
157+
const output = await captureStdout(() =>
158+
listModels({ format: "json", workspace: workspacePath, extension: extensionPath }),
159+
)
160+
161+
expect(JSON.parse(output)).toEqual({ models: {} })
68162
})
69163
})
70164

‎apps/cli/src/commands/cli/__tests__/run.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,73 @@ import fs from "fs"
22
import path from "path"
33
import os from "os"
44

5+
import { providerIdentifiers } from "@roo-code/types"
6+
import { DEFAULT_FLAGS } from "@/types/index.js"
7+
import {
8+
resolveLegacyRequireApproval,
9+
resolveModel,
10+
resolveProvider,
11+
resolveReasoningEffort,
12+
resolveWorkspacePath,
13+
} from "../run.js"
14+
15+
describe("resolveModel", () => {
16+
it("uses the CLI flag before the settings model", () => {
17+
expect(resolveModel("flag-model", "settings-model")).toBe("flag-model")
18+
})
19+
20+
it("uses the settings model when the CLI flag is absent", () => {
21+
expect(resolveModel(undefined, "settings-model")).toBe("settings-model")
22+
})
23+
24+
it("uses the default model when neither the CLI flag nor settings provide one", () => {
25+
expect(resolveModel()).toBe(DEFAULT_FLAGS.model)
26+
})
27+
})
28+
29+
describe("resolveReasoningEffort", () => {
30+
it("uses CLI, settings, and default values in priority order", () => {
31+
expect(resolveReasoningEffort("high", "low")).toBe("high")
32+
expect(resolveReasoningEffort(undefined, "low")).toBe("low")
33+
expect(resolveReasoningEffort()).toBe(DEFAULT_FLAGS.reasoningEffort)
34+
})
35+
})
36+
37+
describe("resolveProvider", () => {
38+
it("uses CLI, settings, and openrouter values in priority order", () => {
39+
expect(resolveProvider(providerIdentifiers.anthropic, providerIdentifiers.gemini)).toBe(
40+
providerIdentifiers.anthropic,
41+
)
42+
expect(resolveProvider(undefined, providerIdentifiers.gemini)).toBe(providerIdentifiers.gemini)
43+
expect(resolveProvider()).toBe(providerIdentifiers.openrouter)
44+
})
45+
})
46+
47+
describe("resolveWorkspacePath", () => {
48+
it("resolves the provided workspace path", () => {
49+
expect(resolveWorkspacePath("relative/workspace")).toBe(path.resolve("relative/workspace"))
50+
})
51+
52+
it("uses the current working directory when workspace is absent", () => {
53+
expect(resolveWorkspacePath()).toBe(process.cwd())
54+
})
55+
})
56+
57+
describe("resolveLegacyRequireApproval", () => {
58+
it.each([
59+
{ requireApproval: true, dangerouslySkipPermissions: true, expected: true },
60+
{ requireApproval: false, dangerouslySkipPermissions: false, expected: false },
61+
{ requireApproval: undefined, dangerouslySkipPermissions: false, expected: true },
62+
{ requireApproval: undefined, dangerouslySkipPermissions: true, expected: false },
63+
{ requireApproval: undefined, dangerouslySkipPermissions: undefined, expected: undefined },
64+
])(
65+
"resolves requireApproval=$requireApproval and dangerouslySkipPermissions=$dangerouslySkipPermissions",
66+
({ requireApproval, dangerouslySkipPermissions, expected }) => {
67+
expect(resolveLegacyRequireApproval(requireApproval, dangerouslySkipPermissions)).toBe(expected)
68+
},
69+
)
70+
})
71+
572
describe("run command --prompt-file option", () => {
673
let tempDir: string
774
let promptFilePath: string

‎apps/cli/src/commands/cli/run.ts‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import { setLogger } from "@roo-code/vscode-shim"
1010

1111
import {
1212
FlagOptions,
13+
ReasoningEffortFlagOptions,
14+
SupportedProvider,
1315
isSupportedProvider,
1416
supportedProviders,
1517
DEFAULT_FLAGS,
@@ -50,6 +52,35 @@ function normalizeError(error: unknown): Error {
5052
return error instanceof Error ? error : new Error(String(error))
5153
}
5254

55+
export function resolveModel(flagModel?: string, settingsModel?: string): string {
56+
return flagModel || settingsModel || DEFAULT_FLAGS.model
57+
}
58+
59+
export function resolveReasoningEffort(
60+
flagReasoningEffort?: ReasoningEffortFlagOptions,
61+
settingsReasoningEffort?: ReasoningEffortFlagOptions,
62+
): ReasoningEffortFlagOptions {
63+
return flagReasoningEffort || settingsReasoningEffort || DEFAULT_FLAGS.reasoningEffort
64+
}
65+
66+
export function resolveProvider(
67+
flagProvider?: SupportedProvider,
68+
settingsProvider?: SupportedProvider,
69+
): SupportedProvider {
70+
return flagProvider ?? settingsProvider ?? providerIdentifiers.openrouter
71+
}
72+
73+
export function resolveWorkspacePath(workspace?: string): string {
74+
return workspace ? path.resolve(workspace) : process.cwd()
75+
}
76+
77+
export function resolveLegacyRequireApproval(
78+
requireApproval?: boolean,
79+
dangerouslySkipPermissions?: boolean,
80+
): boolean | undefined {
81+
return requireApproval ?? (dangerouslySkipPermissions === undefined ? undefined : !dangerouslySkipPermissions)
82+
}
83+
5384
export async function run(promptArg: string | undefined, flagOptions: FlagOptions) {
5485
setLogger({
5586
info: () => {},
@@ -120,14 +151,14 @@ export async function run(promptArg: string | undefined, flagOptions: FlagOption
120151

121152
// Determine effective values: CLI flags > settings file > DEFAULT_FLAGS.
122153
const effectiveMode = flagOptions.mode || settings.mode || DEFAULT_FLAGS.mode
123-
const effectiveModel = flagOptions.model || settings.model || DEFAULT_FLAGS.model
124-
const effectiveReasoningEffort =
125-
flagOptions.reasoningEffort || settings.reasoningEffort || DEFAULT_FLAGS.reasoningEffort
126-
const effectiveProvider = flagOptions.provider ?? settings.provider ?? providerIdentifiers.openrouter
127-
const effectiveWorkspacePath = flagOptions.workspace ? path.resolve(flagOptions.workspace) : process.cwd()
128-
const legacyRequireApprovalFromSettings =
129-
settings.requireApproval ??
130-
(settings.dangerouslySkipPermissions === undefined ? undefined : !settings.dangerouslySkipPermissions)
154+
const effectiveModel = resolveModel(flagOptions.model, settings.model)
155+
const effectiveReasoningEffort = resolveReasoningEffort(flagOptions.reasoningEffort, settings.reasoningEffort)
156+
const effectiveProvider = resolveProvider(flagOptions.provider, settings.provider)
157+
const effectiveWorkspacePath = resolveWorkspacePath(flagOptions.workspace)
158+
const legacyRequireApprovalFromSettings = resolveLegacyRequireApproval(
159+
settings.requireApproval,
160+
settings.dangerouslySkipPermissions,
161+
)
131162
const effectiveRequireApproval = flagOptions.requireApproval || legacyRequireApprovalFromSettings || false
132163
const effectiveExitOnComplete = flagOptions.print || flagOptions.oneshot || settings.oneshot || false
133164
const rawConsecutiveMistakeLimit =

0 commit comments

Comments
 (0)