Skip to content
Merged
72 changes: 72 additions & 0 deletions src/main/agent/api/__tests__/openai-model-config.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { OpenAiHandler } = vi.hoisted(() => ({ OpenAiHandler: vi.fn() }))

vi.mock('../providers/openai', () => ({ OpenAiHandler }))
vi.mock('../providers/bedrock', () => ({ AwsBedrockHandler: vi.fn() }))
vi.mock('../providers/litellm', () => ({ LiteLlmHandler: { createSync: vi.fn() } }))
vi.mock('../providers/deepseek', () => ({ DeepSeekHandler: vi.fn() }))
vi.mock('../providers/anthropic', () => ({ AnthropicHandler: vi.fn() }))
vi.mock('../providers/ollama', () => ({ OllamaHandler: vi.fn() }))

import { buildApiHandler } from '../index'
import { applyOpenAiModelConfig, type ApiConfiguration } from '../../shared/api'

const shared: ApiConfiguration = {
apiProvider: 'openai',
openAiBaseUrl: 'https://shared.example.com/v1',
openAiApiKey: 'shared-key',
openAiModelInfo: { apiFormat: 'chat-completions', contextWindow: 64000 },
openAiModelConfigs: {
'model-a': { baseUrl: 'https://provider-a.example.com/v1', apiKey: 'key-a', apiFormat: 'responses' },
'model-b': { baseUrl: 'https://provider-b.example.com/v1', apiKey: 'key-b' }
}
}

describe('applyOpenAiModelConfig', () => {
it('uses the endpoint and API format bound to the selected model', () => {
const resolved = applyOpenAiModelConfig({ ...shared, openAiModelId: 'model-a' })

expect(resolved.openAiBaseUrl).toBe('https://provider-a.example.com/v1')
expect(resolved.openAiApiKey).toBe('key-a')
expect(resolved.openAiModelInfo).toEqual({ apiFormat: 'responses', contextWindow: 64000 })
})

it('keeps the shared API format when the bound endpoint does not specify one', () => {
const resolved = applyOpenAiModelConfig({ ...shared, openAiModelId: 'model-b' })

expect(resolved.openAiBaseUrl).toBe('https://provider-b.example.com/v1')
expect(resolved.openAiModelInfo).toEqual(shared.openAiModelInfo)
})

it('falls back to the shared endpoint for models without a bound endpoint', () => {
const unbound = { ...shared, openAiModelId: 'legacy-model' }
expect(applyOpenAiModelConfig(unbound)).toBe(unbound)

const noModel = { ...shared, openAiModelId: undefined }
expect(applyOpenAiModelConfig(noModel)).toBe(noModel)

const noConfigs = { ...shared, openAiModelConfigs: undefined, openAiModelId: 'model-a' }
expect(applyOpenAiModelConfig(noConfigs)).toBe(noConfigs)
})

it('resolves an explicitly named model instead of the selected one', () => {
const resolved = applyOpenAiModelConfig({ ...shared, openAiModelId: 'model-a' }, 'model-b')

expect(resolved.openAiApiKey).toBe('key-b')
})
})

describe('buildApiHandler with OpenAI Compatible models', () => {
beforeEach(() => {
OpenAiHandler.mockClear()
})

it('creates the handler with the endpoint bound to the selected model', () => {
buildApiHandler({ ...shared, openAiModelId: 'model-b' })

expect(OpenAiHandler).toHaveBeenCalledWith(
expect.objectContaining({ openAiModelId: 'model-b', openAiBaseUrl: 'https://provider-b.example.com/v1', openAiApiKey: 'key-b' })
)
})
})
4 changes: 2 additions & 2 deletions src/main/agent/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// Licensed under the Apache License, Version 2.0

import { Anthropic } from '@anthropic-ai/sdk'
import { ApiConfiguration, ModelInfo, liteLlmModelInfoSaneDefaults } from '../shared/api'
import { ApiConfiguration, ModelInfo, applyOpenAiModelConfig, liteLlmModelInfoSaneDefaults } from '../shared/api'
import { AwsBedrockHandler } from './providers/bedrock'
import { LiteLlmHandler } from './providers/litellm'
import { DeepSeekHandler } from './providers/deepseek'
Expand Down Expand Up @@ -86,7 +86,7 @@ export function buildApiHandler(configuration: ApiConfiguration): ApiHandler {
case 'deepseek':
return new DeepSeekHandler(options)
case 'openai':
return new OpenAiHandler(options)
return new OpenAiHandler(applyOpenAiModelConfig(options))
case 'ollama':
return new OllamaHandler(options)
case 'default': {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createRequire, Module } from 'module'

const require = createRequire(import.meta.url)
const electronPath = require.resolve('electron')
const mockElectronModule = new Module(electronPath)
mockElectronModule.filename = electronPath
mockElectronModule.loaded = true
mockElectronModule.exports = {
ipcMain: { once: vi.fn(), removeAllListeners: vi.fn() },
BrowserWindow: { getAllWindows: () => [] }
}
require.cache[electronPath] = mockElectronModule

const mocks = vi.hoisted(() => ({
instances: [] as any[],
connectError: undefined as Error | undefined,
createJumpHostTunnelByUuid: vi.fn(),
createProxySocket: vi.fn(),
globalJumpserverConnections: new Map<string, any>()
}))

vi.mock('electron', () => ({
ipcMain: { once: vi.fn(), removeAllListeners: vi.fn() },
BrowserWindow: { getAllWindows: () => [] }
}))

vi.mock('ssh2', async () => {
const { EventEmitter } = await import('events')
class Client extends EventEmitter {
connectConfig: any
connect = vi.fn((config: any) => {
this.connectConfig = config
if (mocks.connectError) throw mocks.connectError
})
end = vi.fn()
constructor() {
super()
mocks.instances.push(this)
}
}
return { Client }
})

vi.mock('../../../../index', () => ({ getUserConfigFromRenderer: vi.fn() }))
vi.mock('../../../../ssh/proxy', () => ({ createProxySocket: mocks.createProxySocket }))
vi.mock('../../../../ssh/jumpHostResolver', () => ({ createJumpHostTunnelByUuid: mocks.createJumpHostTunnelByUuid }))
vi.mock('../../../../ssh/jumpserver/userSelection', () => ({ handleJumpServerUserSelectionWithWindow: vi.fn() }))
vi.mock('../../../../ssh/jumpserverHandle', () => ({ jumpserverConnections: mocks.globalJumpserverConnections }))

import { handleJumpServerConnection, jumpserverConnections } from '../jumpserverHandle'

const baseInfo = {
id: 'agent-session-1',
host: '10.1.1.1',
port: 2222,
username: 'ops',
password: 'secret',
targetIp: '172.16.0.5',
needProxy: false,
proxyName: '',
assetUuid: 'bastion-uuid'
}

const createTunnel = () => ({ sock: { tunnel: true }, jumpClient: { end: vi.fn() } })

describe('agent JumpServer connection through a jump host', () => {
beforeEach(() => {
mocks.instances.length = 0
mocks.connectError = undefined
mocks.createJumpHostTunnelByUuid.mockReset()
mocks.createProxySocket.mockReset()
mocks.globalJumpserverConnections.clear()
jumpserverConnections.clear()
})

it('dials the bastion over the jump host tunnel and tears the tunnel down on error', async () => {
const tunnel = createTunnel()
mocks.createJumpHostTunnelByUuid.mockResolvedValue(tunnel)

const pending = handleJumpServerConnection({ ...baseInfo, jumpHostUuid: 'jump-uuid', needProxy: true, proxyName: 'corp' })
await vi.waitFor(() => expect(mocks.instances).toHaveLength(1))
const conn = mocks.instances[0]

expect(mocks.createJumpHostTunnelByUuid).toHaveBeenCalledWith('jump-uuid', '10.1.1.1', 2222)
expect(mocks.createProxySocket).not.toHaveBeenCalled()
expect(conn.connectConfig.sock).toBe(tunnel.sock)

conn.emit('error', new Error('handshake failed'))
await expect(pending).rejects.toThrow('JumpServer connection failed: handshake failed')
expect(tunnel.jumpClient.end).toHaveBeenCalledTimes(1)
})

it('uses the default SSH port for the tunnel target when none is configured', async () => {
mocks.createJumpHostTunnelByUuid.mockResolvedValue(createTunnel())

const pending = handleJumpServerConnection({ ...baseInfo, port: undefined, assetUuid: undefined, jumpHostUuid: 'jump-uuid' })
await vi.waitFor(() => expect(mocks.instances).toHaveLength(1))
mocks.instances[0].emit('error', new Error('handshake failed'))
await expect(pending).rejects.toThrow('handshake failed')

expect(mocks.createJumpHostTunnelByUuid).toHaveBeenCalledWith('jump-uuid', '10.1.1.1', 22)
})

it('closes the tunnel when bastion credentials are missing', async () => {
const tunnel = createTunnel()
mocks.createJumpHostTunnelByUuid.mockResolvedValue(tunnel)

await expect(handleJumpServerConnection({ ...baseInfo, password: undefined, jumpHostUuid: 'jump-uuid' })).rejects.toThrow(
'Missing authentication information'
)
expect(tunnel.jumpClient.end).toHaveBeenCalledTimes(1)
})

it('closes the tunnel when the bastion private key is malformed', async () => {
const tunnel = createTunnel()
mocks.createJumpHostTunnelByUuid.mockResolvedValue(tunnel)

await expect(handleJumpServerConnection({ ...baseInfo, privateKey: {} as unknown as string, jumpHostUuid: 'jump-uuid' })).rejects.toThrow(
'Private key format error'
)
expect(tunnel.jumpClient.end).toHaveBeenCalledTimes(1)
})

it('does not dial the jump host when the session already has a connection', async () => {
jumpserverConnections.set(baseInfo.id, {})

await expect(handleJumpServerConnection({ ...baseInfo, jumpHostUuid: 'jump-uuid' })).resolves.toMatchObject({ status: 'connected' })
expect(mocks.createJumpHostTunnelByUuid).not.toHaveBeenCalled()
})

it('does not dial the jump host when an authenticated bastion connection can be shared', async () => {
const sharedConn = { shell: vi.fn((cb: (err: Error) => void) => cb(new Error('shell refused'))) }
mocks.globalJumpserverConnections.set('terminal-session', { conn: sharedConn, jumpserverUuid: 'bastion-uuid' })

await expect(handleJumpServerConnection({ ...baseInfo, jumpHostUuid: 'jump-uuid' })).rejects.toThrow('shell refused')
expect(mocks.createJumpHostTunnelByUuid).not.toHaveBeenCalled()
expect(mocks.instances).toHaveLength(0)
})

it('closes the tunnel when the session connection appears while the tunnel is being created', async () => {
const tunnel = createTunnel()
mocks.createJumpHostTunnelByUuid.mockImplementation(async () => {
jumpserverConnections.set(baseInfo.id, {})
return tunnel
})

await expect(handleJumpServerConnection({ ...baseInfo, jumpHostUuid: 'jump-uuid' })).resolves.toMatchObject({ status: 'connected' })
expect(tunnel.jumpClient.end).toHaveBeenCalledTimes(1)
expect(mocks.instances).toHaveLength(0)
})

it('closes the tunnel when a shareable bastion connection appears while the tunnel is being created', async () => {
const tunnel = createTunnel()
const sharedConn = { shell: vi.fn((cb: (err: Error) => void) => cb(new Error('shell refused'))) }
mocks.createJumpHostTunnelByUuid.mockImplementation(async () => {
mocks.globalJumpserverConnections.set('terminal-session', { conn: sharedConn, jumpserverUuid: 'bastion-uuid' })
return tunnel
})

await expect(handleJumpServerConnection({ ...baseInfo, jumpHostUuid: 'jump-uuid' })).rejects.toThrow('shell refused')
expect(tunnel.jumpClient.end).toHaveBeenCalledTimes(1)
expect(mocks.instances).toHaveLength(0)
})

it('ends the new bastion connection when the shell channel is refused', async () => {
mocks.createJumpHostTunnelByUuid.mockResolvedValue(createTunnel())

const pending = handleJumpServerConnection({ ...baseInfo, jumpHostUuid: 'jump-uuid' })
await vi.waitFor(() => expect(mocks.instances).toHaveLength(1))
const conn = mocks.instances[0]
conn.shell = vi.fn((cb: (err: Error) => void) => cb(new Error('channel refused')))
conn.emit('ready')

await expect(pending).rejects.toThrow('Shell creation failed: channel refused')
expect(conn.end).toHaveBeenCalledTimes(1)
})

it('closes the tunnel when the bastion connect throws synchronously', async () => {
const tunnel = createTunnel()
mocks.createJumpHostTunnelByUuid.mockResolvedValue(tunnel)
mocks.connectError = new Error('Cannot parse privateKey')

await expect(handleJumpServerConnection({ ...baseInfo, privateKey: 'not-a-key', jumpHostUuid: 'jump-uuid' })).rejects.toThrow(
'Cannot parse privateKey'
)
expect(tunnel.jumpClient.end).toHaveBeenCalledTimes(1)
})

it('still connects through the proxy when no jump host is configured', async () => {
const proxySock = { proxy: true }
mocks.createProxySocket.mockResolvedValue(proxySock)

const pending = handleJumpServerConnection({ ...baseInfo, needProxy: true, proxyName: 'corp', proxyConfig: { host: 'proxy' } as any })
await vi.waitFor(() => expect(mocks.instances).toHaveLength(1))
const conn = mocks.instances[0]

expect(mocks.createJumpHostTunnelByUuid).not.toHaveBeenCalled()
expect(conn.connectConfig.sock).toBe(proxySock)

conn.emit('error', new Error('handshake failed'))
await expect(pending).rejects.toThrow('handshake failed')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,26 @@ describe('RemoteTerminalManager plugin bastion routing', () => {
expect(secondTerminal.sessionId).not.toBe(firstTerminal.sessionId)
expect(handleJumpServerConnectionMock).toHaveBeenCalledTimes(2)
})

it('forwards the configured jump host to the JumpServer connection', async () => {
handleJumpServerConnectionMock.mockResolvedValueOnce({ status: 'connected', message: 'ok' })

const { RemoteTerminalManager } = await import('../index')
const manager = new RemoteTerminalManager()

manager.setConnectionInfo({
sshType: 'jumpserver',
asset_ip: '10.0.0.2',
host: '172.16.0.10',
port: 22,
username: 'root',
password: 'secret',
needProxy: false,
jumpHostUuid: 'jump-uuid'
})

await manager.createTerminal()

expect(handleJumpServerConnectionMock).toHaveBeenCalledWith(expect.objectContaining({ jumpHostUuid: 'jump-uuid' }))
})
})
1 change: 1 addition & 0 deletions src/main/agent/integrations/remote-terminal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,7 @@ export class RemoteTerminalManager {
targetIp: this.connectionInfo.host!,
needProxy: this.connectionInfo.needProxy || false,
proxyName: this.connectionInfo.proxyName || '',
jumpHostUuid: this.connectionInfo.jumpHostUuid,
ident: this.connectionInfo.ident,
assetUuid
}
Expand Down
Loading
Loading