Files
deepseek-harness/packages/web/web-deepseek-api/tests/fetch.spec.ts
T
LegGasai 651a6ccdf0 refactor(web-deepseek-api): take Search and Fetch credentials from ctx.deepseekAuth
The plugin asked `ctx.llm.providerCredential()` for each route's credential, read `DEEPSEEK_API_KEY` and the account service itself when a route was not mounted, ordered those sources by billing, and rendered the request headers in its transport. It now names the kinds the two APIs accept and the capability's billing, and `ctx.deepseekAuth` returns the ordered credentials, each bound to its endpoint. The plugin keeps the wording of its failures; the transport sends the headers it is given.

Behavior is unchanged except in two places. A key that is blank or cannot travel in an HTTP header is reported with the error name `DeepSeekAuthError` where it named `LlmError`. A capability's own base URL that embeds credentials now leaves the provider unavailable, as one that does not parse already did; `fetch` refused such a URL before.

The package no longer depends on `dsh-llm`, `dsh-launch-environment`, or the account service. The transport's `apiKeyHeaders` request option, which only tests set, is gone, and the tests of adapters that publish the other credential kind under a DeepSeek route id went with that publication.
2026-11-15 16:21:01 +08:00

80 lines
5.3 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import DeepSeekAuth from '@deepseek-ai/dsh-deepseek-auth'
import WebRuntime from '@deepseek-ai/dsh-web'
import { DeepSeekFetchApiProvider, type DeepSeekFetchApiOptions } from '@deepseek-ai/dsh-web-deepseek-api'
import * as webApiPlugin from '@deepseek-ai/dsh-web-deepseek-api'
import { DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { customGuidance } from './guidance.ts'
import { keyCandidate } from './sources.ts'
const fetchProvider = (options: DeepSeekFetchApiOptions) => new DeepSeekFetchApiProvider(() => options)
const BASE = 'https://api.deepseek.test/api/v1/tools'
const auth = (key: string): DeepSeekFetchApiOptions['auth'] => ({ sources: [keyCandidate(`${BASE}/fetch`, key)] })
const options = { auth: auth('ds-key'), guidance: customGuidance('fetch') }
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init })
}
afterEach(() => { vi.unstubAllGlobals() })
describe('DeepSeek Fetch API', () => {
it('posts the URL and returns the Markdown as a retrieved page', async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse({ title: 'Example', content: '# Article\n\nBody' }))
vi.stubGlobal('fetch', fetchMock)
const provider = fetchProvider(options)
expect(await provider.fetch({ url: 'https://example.com/article' })).toEqual({
url: 'https://example.com/article', statusCode: 200, body: { kind: 'text', content: '# Article\n\nBody' }, truncated: false,
})
const [url, init] = fetchMock.mock.calls[0]!
expect(url).toBe('https://api.deepseek.test/api/v1/tools/fetch')
if (typeof init?.body !== 'string') throw new Error('expected JSON request body')
expect(JSON.parse(init.body)).toEqual({ url: 'https://example.com/article' })
expect(init).toMatchObject({ redirect: 'error', headers: { authorization: 'Bearer ds-key' } })
expect(init?.headers).not.toHaveProperty('anthropic-version')
})
it.each([null, {}, { title: '', content: null }])('rejects malformed Fetch response %j', async (body) => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse(body)))
await expect(fetchProvider(options).fetch({ url: 'https://example.com' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_ERROR' })
})
it.each([400, 401, 402, 403, 404, 408, 413, 429, 500, 502, 503, 504])('reports HTTP %i as a retrieval failure', async (status) => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'request failed', type: 'api_error', param: null, code: 'api_error' } }, { status })))
await expect(fetchProvider(options).fetch({ url: 'https://example.com' })).rejects.toThrow(`HTTP ${status}`)
})
it('honors pre-dispatch cancellation for fetch', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
await expect(fetchProvider(options).fetch({ url: 'https://example.com' }, AbortSignal.abort())).rejects.toMatchObject({ code: 'WEB_ABORTED' })
expect(fetchMock).not.toHaveBeenCalled()
})
it('names the Fetch settings in endpoint guidance', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'not found' } }, { status: 404 })))
await expect(fetchProvider(options).fetch({ url: 'https://example.com' })).rejects.toMatchObject({
code: 'WEB_PROVIDER_ERROR',
message: 'DeepSeek API error (HTTP 404): not found\n\n'
+ 'The web request used endpoint "https://api.deepseek.test/api/v1/tools/fetch". '
+ 'Fetch sends the API key under web-deepseek-api.fetchApiKeyEnv to web-deepseek-api.fetchBaseURL. If that '
+ 'endpoint is not intended, guide the user to correct web-deepseek-api.fetchBaseURL and '
+ 'web-deepseek-api.fetchApiKeyEnv, or to remove both so Fetch uses the DeepSeek credential of the conversation. '
+ 'Only the user should choose or change the endpoint.',
})
})
it('is available only with a credential source', () => {
expect(fetchProvider(options).available()).toBe(true)
expect(fetchProvider({ ...options, auth: { sources: [] } }).available()).toBe(false)
expect(fetchProvider({ ...options, auth: auth('') }).available()).toBe(true)
})
it('unregisters both providers with its plugin fiber', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ title: '', content: 'body' })))
const ctx = new Context()
try {
await ctx.plugin(WebRuntime, { searchProvider: 'deepseek-search-api', fetchProvider: 'deepseek-fetch-api' })
ctx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, createLaunchEnvironmentSnapshot([{ source: 'process', values: { DEEPSEEK_API_KEY: 'ds-key' } }]))
await ctx.plugin(DeepSeekAuth)
const fiber = await ctx.plugin(webApiPlugin, { fetchBaseURL: BASE })
await expect(ctx.web.fetch({ url: 'https://example.com' })).resolves.toMatchObject({ body: { content: 'body' } })
await fiber.dispose()
await expect(ctx.web.fetch({ url: 'https://example.com' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_CONFIGURED_MISSING' })
await expect(ctx.web.search({ query: 'q' })).rejects.toMatchObject({ code: 'WEB_PROVIDER_CONFIGURED_MISSING' })
} finally { await ctx.fiber.dispose() }
})
})