feat: 品牌替换 + 启动优化 + AGENTS.md 模板定制
- 品牌替换:OpenCode/opencode → AirCoding/aircoding(16+ 文件) - Logo ASCII art:修复 left/right 行数不匹配导致的启动崩溃 - 启动诊断:添加 OPENCODE_PRINT_TIMING 计时探针 - dev 模式默认 --pure 跳过外部插件加载 - AGENTS.md 模板:追加 AirCoding 多 Agent 专项段落 - architect prompt + plugin:强化 AGENTS.md 产出验证
This commit is contained in:
105
packages/opencode/test/plugin/auth-override.test.ts
Normal file
105
packages/opencode/test/plugin/auth-override.test.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { FSUtil } from "@opencode-ai/core/fs-util"
|
||||
import { provideInstance, TestInstance, tmpdirScoped } from "../fixture/fixture"
|
||||
import { ProviderAuth } from "@/provider/auth"
|
||||
|
||||
import { Plugin } from "@/plugin"
|
||||
import { RuntimeFlags } from "@/effect/runtime-flags"
|
||||
import { Auth } from "@/auth"
|
||||
import { EventV2Bridge } from "@/event-v2-bridge"
|
||||
import { TestConfig } from "../fixture/config"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
|
||||
import { ProviderV2 } from "@opencode-ai/core/provider"
|
||||
|
||||
const it = testEffect(Layer.mergeAll(CrossSpawnSpawner.defaultLayer, FSUtil.defaultLayer))
|
||||
|
||||
function layer(directory: string, plugins: string[]) {
|
||||
return ProviderAuth.layer.pipe(
|
||||
Layer.provide(Auth.defaultLayer),
|
||||
Layer.provide(
|
||||
Plugin.layer.pipe(
|
||||
Layer.provide(EventV2Bridge.defaultLayer),
|
||||
Layer.provide(RuntimeFlags.layer()),
|
||||
Layer.provide(
|
||||
TestConfig.layer({
|
||||
get: () =>
|
||||
Effect.succeed({
|
||||
plugin: plugins,
|
||||
plugin_origins: plugins.map((plugin) => ({
|
||||
spec: plugin,
|
||||
source: path.join(directory, "opencode.json"),
|
||||
scope: "local" as const,
|
||||
})),
|
||||
}),
|
||||
directories: () => Effect.succeed([directory]),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
describe("plugin.auth-override", () => {
|
||||
it.instance(
|
||||
"user plugin overrides built-in github-copilot auth",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* TestInstance
|
||||
const fs = yield* FSUtil.Service
|
||||
const pluginDir = path.join(tmp.directory, ".opencode", "plugin")
|
||||
|
||||
yield* fs.writeWithDirs(
|
||||
path.join(pluginDir, "custom-copilot-auth.ts"),
|
||||
[
|
||||
"export default {",
|
||||
' id: "demo.custom-copilot-auth",',
|
||||
" server: async () => ({",
|
||||
" auth: {",
|
||||
' provider: "github-copilot",',
|
||||
" methods: [",
|
||||
' { type: "api", label: "Test Override Auth" },',
|
||||
" ],",
|
||||
" loader: async () => ({ access: 'test-token' }),",
|
||||
" },",
|
||||
" }),",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
)
|
||||
|
||||
const plain = yield* tmpdirScoped({ git: true })
|
||||
const plugin = pathToFileURL(path.join(pluginDir, "custom-copilot-auth.ts")).href
|
||||
const methods = yield* ProviderAuth.use.methods().pipe(Effect.provide(layer(tmp.directory, [plugin])))
|
||||
const plainMethods = yield* ProviderAuth.use
|
||||
.methods()
|
||||
.pipe(Effect.provide(layer(plain, [])), provideInstance(plain))
|
||||
|
||||
const copilot = methods[ProviderV2.ID.make("github-copilot")]
|
||||
expect(copilot).toBeDefined()
|
||||
expect(copilot.length).toBe(1)
|
||||
expect(copilot[0].label).toBe("Test Override Auth")
|
||||
expect(plainMethods[ProviderV2.ID.make("github-copilot")][0].label).not.toBe("Test Override Auth")
|
||||
}),
|
||||
{ git: true },
|
||||
30000,
|
||||
)
|
||||
})
|
||||
|
||||
const file = path.join(import.meta.dir, "../../src/plugin/index.ts")
|
||||
|
||||
describe("plugin.config-hook-error-isolation", () => {
|
||||
test("config hooks are individually error-isolated in the layer factory", async () => {
|
||||
const src = await Bun.file(file).text()
|
||||
|
||||
// Each hook's config call is wrapped in Effect.tryPromise with error logging + Effect.ignore
|
||||
expect(src).toContain("plugin config hook failed")
|
||||
|
||||
const pattern =
|
||||
/for\s*\(const hook of hooks\)\s*\{[\s\S]*?Effect\.tryPromise[\s\S]*?\.config\?\.\([\s\S]*?plugin config hook failed[\s\S]*?Effect\.ignore/
|
||||
expect(pattern.test(src)).toBe(true)
|
||||
})
|
||||
})
|
||||
68
packages/opencode/test/plugin/cloudflare.test.ts
Normal file
68
packages/opencode/test/plugin/cloudflare.test.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { CloudflareAIGatewayAuthPlugin } from "@/plugin/cloudflare"
|
||||
|
||||
const pluginInput = {
|
||||
client: {} as never,
|
||||
project: {} as never,
|
||||
directory: "",
|
||||
worktree: "",
|
||||
experimental_workspace: {
|
||||
register() {},
|
||||
},
|
||||
serverUrl: new URL("https://example.com"),
|
||||
$: {} as never,
|
||||
}
|
||||
|
||||
function makeHookInput(overrides: { providerID?: string; apiId?: string; reasoning?: boolean }) {
|
||||
return {
|
||||
sessionID: "s",
|
||||
agent: "a",
|
||||
provider: {} as never,
|
||||
message: {} as never,
|
||||
model: {
|
||||
providerID: overrides.providerID ?? "cloudflare-ai-gateway",
|
||||
api: { id: overrides.apiId ?? "openai/gpt-5.2-codex", url: "", npm: "ai-gateway-provider" },
|
||||
capabilities: {
|
||||
reasoning: overrides.reasoning ?? true,
|
||||
temperature: false,
|
||||
attachment: true,
|
||||
toolcall: true,
|
||||
input: { text: true, audio: false, image: false, video: false, pdf: false },
|
||||
output: { text: true, audio: false, image: false, video: false, pdf: false },
|
||||
interleaved: false,
|
||||
},
|
||||
} as never,
|
||||
}
|
||||
}
|
||||
|
||||
function makeHookOutput() {
|
||||
return { temperature: 0, topP: 1, topK: 0, maxOutputTokens: 32_000 as number | undefined, options: {} }
|
||||
}
|
||||
|
||||
test("omits maxOutputTokens for openai reasoning models on cloudflare-ai-gateway", async () => {
|
||||
const hooks = await CloudflareAIGatewayAuthPlugin(pluginInput)
|
||||
const out = makeHookOutput()
|
||||
await hooks["chat.params"]!(makeHookInput({ apiId: "openai/gpt-5.2-codex", reasoning: true }), out)
|
||||
expect(out.maxOutputTokens).toBeUndefined()
|
||||
})
|
||||
|
||||
test("keeps maxOutputTokens for openai non-reasoning models", async () => {
|
||||
const hooks = await CloudflareAIGatewayAuthPlugin(pluginInput)
|
||||
const out = makeHookOutput()
|
||||
await hooks["chat.params"]!(makeHookInput({ apiId: "openai/gpt-4-turbo", reasoning: false }), out)
|
||||
expect(out.maxOutputTokens).toBe(32_000)
|
||||
})
|
||||
|
||||
test("keeps maxOutputTokens for non-openai reasoning models on cloudflare-ai-gateway", async () => {
|
||||
const hooks = await CloudflareAIGatewayAuthPlugin(pluginInput)
|
||||
const out = makeHookOutput()
|
||||
await hooks["chat.params"]!(makeHookInput({ apiId: "anthropic/claude-sonnet-4-5", reasoning: true }), out)
|
||||
expect(out.maxOutputTokens).toBe(32_000)
|
||||
})
|
||||
|
||||
test("ignores non-cloudflare-ai-gateway providers", async () => {
|
||||
const hooks = await CloudflareAIGatewayAuthPlugin(pluginInput)
|
||||
const out = makeHookOutput()
|
||||
await hooks["chat.params"]!(makeHookInput({ providerID: "openai", apiId: "gpt-5.2-codex", reasoning: true }), out)
|
||||
expect(out.maxOutputTokens).toBe(32_000)
|
||||
})
|
||||
247
packages/opencode/test/plugin/codex.test.ts
Normal file
247
packages/opencode/test/plugin/codex.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
CodexAuthPlugin,
|
||||
parseJwtClaims,
|
||||
extractAccountIdFromClaims,
|
||||
extractAccountId,
|
||||
type IdTokenClaims,
|
||||
} from "../../src/plugin/openai/codex"
|
||||
|
||||
function createTestJwt(payload: object): string {
|
||||
const header = Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url")
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString("base64url")
|
||||
return `${header}.${body}.sig`
|
||||
}
|
||||
|
||||
describe("plugin.codex", () => {
|
||||
describe("parseJwtClaims", () => {
|
||||
test("parses valid JWT with claims", () => {
|
||||
const payload = { email: "test@example.com", chatgpt_account_id: "acc-123" }
|
||||
const jwt = createTestJwt(payload)
|
||||
const claims = parseJwtClaims(jwt)
|
||||
expect(claims).toEqual(payload)
|
||||
})
|
||||
|
||||
test("returns undefined for JWT with less than 3 parts", () => {
|
||||
expect(parseJwtClaims("invalid")).toBeUndefined()
|
||||
expect(parseJwtClaims("only.two")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("returns undefined for invalid base64", () => {
|
||||
expect(parseJwtClaims("a.!!!invalid!!!.b")).toBeUndefined()
|
||||
})
|
||||
|
||||
test("returns undefined for invalid JSON payload", () => {
|
||||
const header = Buffer.from("{}").toString("base64url")
|
||||
const invalidJson = Buffer.from("not json").toString("base64url")
|
||||
expect(parseJwtClaims(`${header}.${invalidJson}.sig`)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe("extractAccountIdFromClaims", () => {
|
||||
test("extracts chatgpt_account_id from root", () => {
|
||||
const claims: IdTokenClaims = { chatgpt_account_id: "acc-root" }
|
||||
expect(extractAccountIdFromClaims(claims)).toBe("acc-root")
|
||||
})
|
||||
|
||||
test("extracts chatgpt_account_id from nested https://api.openai.com/auth", () => {
|
||||
const claims: IdTokenClaims = {
|
||||
"https://api.openai.com/auth": { chatgpt_account_id: "acc-nested" },
|
||||
}
|
||||
expect(extractAccountIdFromClaims(claims)).toBe("acc-nested")
|
||||
})
|
||||
|
||||
test("prefers root over nested", () => {
|
||||
const claims: IdTokenClaims = {
|
||||
chatgpt_account_id: "acc-root",
|
||||
"https://api.openai.com/auth": { chatgpt_account_id: "acc-nested" },
|
||||
}
|
||||
expect(extractAccountIdFromClaims(claims)).toBe("acc-root")
|
||||
})
|
||||
|
||||
test("extracts from organizations array as fallback", () => {
|
||||
const claims: IdTokenClaims = {
|
||||
organizations: [{ id: "org-123" }, { id: "org-456" }],
|
||||
}
|
||||
expect(extractAccountIdFromClaims(claims)).toBe("org-123")
|
||||
})
|
||||
|
||||
test("returns undefined when no accountId found", () => {
|
||||
const claims: IdTokenClaims = { email: "test@example.com" }
|
||||
expect(extractAccountIdFromClaims(claims)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe("extractAccountId", () => {
|
||||
test("extracts from id_token first", () => {
|
||||
const idToken = createTestJwt({ chatgpt_account_id: "from-id-token" })
|
||||
const accessToken = createTestJwt({ chatgpt_account_id: "from-access-token" })
|
||||
expect(
|
||||
extractAccountId({
|
||||
id_token: idToken,
|
||||
access_token: accessToken,
|
||||
refresh_token: "rt",
|
||||
}),
|
||||
).toBe("from-id-token")
|
||||
})
|
||||
|
||||
test("falls back to access_token when id_token has no accountId", () => {
|
||||
const idToken = createTestJwt({ email: "test@example.com" })
|
||||
const accessToken = createTestJwt({
|
||||
"https://api.openai.com/auth": { chatgpt_account_id: "from-access" },
|
||||
})
|
||||
expect(
|
||||
extractAccountId({
|
||||
id_token: idToken,
|
||||
access_token: accessToken,
|
||||
refresh_token: "rt",
|
||||
}),
|
||||
).toBe("from-access")
|
||||
})
|
||||
|
||||
test("returns undefined when no tokens have accountId", () => {
|
||||
const token = createTestJwt({ email: "test@example.com" })
|
||||
expect(
|
||||
extractAccountId({
|
||||
id_token: token,
|
||||
access_token: token,
|
||||
refresh_token: "rt",
|
||||
}),
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
test("handles missing id_token", () => {
|
||||
const accessToken = createTestJwt({ chatgpt_account_id: "acc-123" })
|
||||
expect(
|
||||
extractAccountId({
|
||||
id_token: "",
|
||||
access_token: accessToken,
|
||||
refresh_token: "rt",
|
||||
}),
|
||||
).toBe("acc-123")
|
||||
})
|
||||
})
|
||||
|
||||
test("installs websocket transport only when experimental websockets are enabled", async () => {
|
||||
const disabled = await CodexAuthPlugin({} as never)
|
||||
const enabled = await CodexAuthPlugin({} as never, { experimentalWebSockets: true })
|
||||
|
||||
const disabledOptions = await disabled.auth!.loader!(
|
||||
async () => ({ type: "api", key: "sk-test" }) as never,
|
||||
{} as never,
|
||||
)
|
||||
const enabledOptions = await enabled.auth!.loader!(
|
||||
async () => ({ type: "api", key: "sk-test" }) as never,
|
||||
{} as never,
|
||||
)
|
||||
|
||||
expect(disabledOptions.fetch).toBeUndefined()
|
||||
expect(enabledOptions.fetch).toBeFunction()
|
||||
await enabled.dispose?.()
|
||||
})
|
||||
|
||||
test("deduplicates concurrent Codex token refreshes", async () => {
|
||||
let auth = {
|
||||
type: "oauth" as const,
|
||||
refresh: "refresh-old",
|
||||
access: "",
|
||||
expires: 0,
|
||||
}
|
||||
const authUpdates: Array<{
|
||||
body: { refresh: string; access: string; expires: number; accountId?: string }
|
||||
}> = []
|
||||
let resolveRefresh: (() => void) | undefined
|
||||
const refreshReady = new Promise<void>((resolve) => {
|
||||
resolveRefresh = resolve
|
||||
})
|
||||
let refreshRequests = 0
|
||||
const apiRequests: { authorization: string | null; accountId: string | null }[] = []
|
||||
|
||||
using server = Bun.serve({
|
||||
port: 0,
|
||||
async fetch(request) {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === "/oauth/token") {
|
||||
expect(await request.text()).toContain("refresh_token=refresh-old")
|
||||
refreshRequests += 1
|
||||
await refreshReady
|
||||
return Response.json({
|
||||
id_token: createTestJwt({ chatgpt_account_id: "acc-123" }),
|
||||
access_token: "access-new",
|
||||
refresh_token: "refresh-new",
|
||||
expires_in: 3600,
|
||||
})
|
||||
}
|
||||
|
||||
if (url.pathname === "/backend-api/codex/responses") {
|
||||
apiRequests.push({
|
||||
authorization: request.headers.get("authorization"),
|
||||
accountId: request.headers.get("ChatGPT-Account-Id"),
|
||||
})
|
||||
return new Response("{}", { status: 200 })
|
||||
}
|
||||
|
||||
return new Response("unexpected request", { status: 500 })
|
||||
},
|
||||
})
|
||||
|
||||
const hooks = await CodexAuthPlugin(
|
||||
{
|
||||
client: {
|
||||
auth: {
|
||||
async set(input: { body: { refresh: string; access: string; expires: number; accountId?: string } }) {
|
||||
authUpdates.push(input)
|
||||
auth = {
|
||||
type: "oauth",
|
||||
refresh: input.body.refresh,
|
||||
access: input.body.access,
|
||||
expires: input.body.expires,
|
||||
...(input.body.accountId && { accountId: input.body.accountId }),
|
||||
}
|
||||
},
|
||||
},
|
||||
} as never,
|
||||
project: {} as never,
|
||||
directory: "",
|
||||
worktree: "",
|
||||
experimental_workspace: {
|
||||
register() {},
|
||||
},
|
||||
serverUrl: new URL("https://example.com"),
|
||||
$: {} as never,
|
||||
},
|
||||
{
|
||||
issuer: server.url.origin,
|
||||
codexApiEndpoint: new URL("/backend-api/codex/responses", server.url).toString(),
|
||||
},
|
||||
)
|
||||
const loaded = await hooks.auth!.loader!(async () => auth as never, {} as never)
|
||||
|
||||
const first = loaded.fetch!("https://api.openai.com/v1/responses")
|
||||
const second = loaded.fetch!("https://api.openai.com/v1/responses")
|
||||
|
||||
await waitFor(() => refreshRequests === 1)
|
||||
expect(apiRequests).toHaveLength(0)
|
||||
|
||||
resolveRefresh!()
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(refreshRequests).toBe(1)
|
||||
expect(authUpdates).toHaveLength(1)
|
||||
expect(authUpdates[0]?.body.refresh).toBe("refresh-new")
|
||||
expect(authUpdates[0]?.body.access).toBe("access-new")
|
||||
expect(authUpdates[0]?.body.accountId).toBe("acc-123")
|
||||
expect(apiRequests).toEqual([
|
||||
{ authorization: "Bearer access-new", accountId: "acc-123" },
|
||||
{ authorization: "Bearer access-new", accountId: "acc-123" },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
async function waitFor(predicate: () => boolean) {
|
||||
const started = Date.now()
|
||||
while (!predicate()) {
|
||||
if (Date.now() - started > 1_000) throw new Error("timed out waiting for condition")
|
||||
await new Promise((resolve) => setTimeout(resolve, 1))
|
||||
}
|
||||
}
|
||||
332
packages/opencode/test/plugin/github-copilot-models.test.ts
Normal file
332
packages/opencode/test/plugin/github-copilot-models.test.ts
Normal file
@@ -0,0 +1,332 @@
|
||||
import { afterEach, expect, mock, test } from "bun:test"
|
||||
import { CopilotModels } from "@/plugin/github-copilot/models"
|
||||
import { CopilotAuthPlugin } from "@/plugin/github-copilot/copilot"
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch
|
||||
})
|
||||
|
||||
test("preserves temperature support from existing provider models", async () => {
|
||||
globalThis.fetch = mock(() =>
|
||||
Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{
|
||||
model_picker_enabled: true,
|
||||
id: "gpt-4o",
|
||||
name: "GPT-4o",
|
||||
version: "gpt-4o-2024-05-13",
|
||||
capabilities: {
|
||||
family: "gpt",
|
||||
limits: {
|
||||
max_context_window_tokens: 64000,
|
||||
max_output_tokens: 16384,
|
||||
max_prompt_tokens: 64000,
|
||||
},
|
||||
supports: {
|
||||
streaming: true,
|
||||
tool_calls: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
model_picker_enabled: true,
|
||||
id: "brand-new",
|
||||
name: "Brand New",
|
||||
version: "brand-new-2026-04-01",
|
||||
capabilities: {
|
||||
family: "test",
|
||||
limits: {
|
||||
max_context_window_tokens: 32000,
|
||||
max_output_tokens: 8192,
|
||||
max_prompt_tokens: 32000,
|
||||
},
|
||||
supports: {
|
||||
streaming: true,
|
||||
tool_calls: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
),
|
||||
) as unknown as typeof fetch
|
||||
|
||||
const result = await CopilotModels.get(
|
||||
"https://api.githubcopilot.com",
|
||||
{},
|
||||
{
|
||||
"gpt-4o": {
|
||||
id: "gpt-4o",
|
||||
providerID: "github-copilot",
|
||||
api: {
|
||||
id: "gpt-4o",
|
||||
url: "https://api.githubcopilot.com",
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
},
|
||||
name: "GPT-4o",
|
||||
family: "gpt",
|
||||
capabilities: {
|
||||
temperature: true,
|
||||
reasoning: false,
|
||||
attachment: true,
|
||||
toolcall: true,
|
||||
input: {
|
||||
text: true,
|
||||
audio: false,
|
||||
image: true,
|
||||
video: false,
|
||||
pdf: false,
|
||||
},
|
||||
output: {
|
||||
text: true,
|
||||
audio: false,
|
||||
image: false,
|
||||
video: false,
|
||||
pdf: false,
|
||||
},
|
||||
interleaved: false,
|
||||
},
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cache: {
|
||||
read: 0,
|
||||
write: 0,
|
||||
},
|
||||
},
|
||||
limit: {
|
||||
context: 64000,
|
||||
output: 16384,
|
||||
},
|
||||
options: {},
|
||||
headers: {},
|
||||
release_date: "2024-05-13",
|
||||
variants: {},
|
||||
status: "active",
|
||||
},
|
||||
},
|
||||
)
|
||||
const models = result.models
|
||||
|
||||
expect(models["gpt-4o"].capabilities.temperature).toBe(true)
|
||||
expect(models["brand-new"].capabilities.temperature).toBe(true)
|
||||
})
|
||||
|
||||
test("converts Copilot AIC token prices to USD per million tokens", async () => {
|
||||
globalThis.fetch = mock(() =>
|
||||
Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{
|
||||
model_picker_enabled: true,
|
||||
id: "gpt-5",
|
||||
name: "GPT-5",
|
||||
version: "gpt-5-2026-06-01",
|
||||
billing: {
|
||||
token_prices: {
|
||||
batch_size: 500000,
|
||||
default: {
|
||||
input_price: 500,
|
||||
output_price: 3000,
|
||||
cache_price: 50,
|
||||
},
|
||||
},
|
||||
},
|
||||
capabilities: {
|
||||
family: "gpt",
|
||||
limits: {
|
||||
max_context_window_tokens: 200000,
|
||||
max_output_tokens: 16384,
|
||||
max_prompt_tokens: 200000,
|
||||
},
|
||||
supports: {
|
||||
streaming: true,
|
||||
tool_calls: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
model_picker_enabled: true,
|
||||
id: "incomplete-internal-model",
|
||||
name: "Incomplete Internal Model",
|
||||
version: "incomplete-internal-model-2026-06-01",
|
||||
capabilities: {
|
||||
family: "internal",
|
||||
supports: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
model_picker_enabled: false,
|
||||
id: "ignored-non-chat-record",
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
),
|
||||
) as unknown as typeof fetch
|
||||
|
||||
const models = (await CopilotModels.get("https://api.githubcopilot.com")).models
|
||||
|
||||
expect(models["gpt-5"].cost).toEqual({
|
||||
input: 10,
|
||||
output: 60,
|
||||
cache: {
|
||||
read: 1,
|
||||
write: 0,
|
||||
},
|
||||
})
|
||||
expect(models["incomplete-internal-model"]).toBeUndefined()
|
||||
expect(models["ignored-non-chat-record"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("clears existing variants so refreshed models calculate provider-specific variants", async () => {
|
||||
globalThis.fetch = mock(() =>
|
||||
Promise.resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{
|
||||
model_picker_enabled: true,
|
||||
id: "claude-opus-4.7",
|
||||
name: "Claude Opus 4.7",
|
||||
version: "claude-opus-4.7-2026-04-16",
|
||||
supported_endpoints: ["/v1/messages"],
|
||||
capabilities: {
|
||||
family: "claude-opus",
|
||||
limits: {
|
||||
max_context_window_tokens: 144000,
|
||||
max_output_tokens: 64000,
|
||||
max_prompt_tokens: 128000,
|
||||
},
|
||||
supports: {
|
||||
adaptive_thinking: true,
|
||||
streaming: true,
|
||||
tool_calls: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
),
|
||||
) as unknown as typeof fetch
|
||||
|
||||
const result = await CopilotModels.get(
|
||||
"https://api.githubcopilot.com",
|
||||
{},
|
||||
{
|
||||
"claude-opus-4.7": {
|
||||
id: "claude-opus-4.7",
|
||||
providerID: "github-copilot",
|
||||
api: {
|
||||
id: "claude-opus-4.7",
|
||||
url: "https://api.githubcopilot.com",
|
||||
npm: "@ai-sdk/github-copilot",
|
||||
},
|
||||
name: "Claude Opus 4.7",
|
||||
family: "claude-opus",
|
||||
capabilities: {
|
||||
temperature: true,
|
||||
reasoning: true,
|
||||
attachment: true,
|
||||
toolcall: true,
|
||||
input: {
|
||||
text: true,
|
||||
audio: false,
|
||||
image: true,
|
||||
video: false,
|
||||
pdf: false,
|
||||
},
|
||||
output: {
|
||||
text: true,
|
||||
audio: false,
|
||||
image: false,
|
||||
video: false,
|
||||
pdf: false,
|
||||
},
|
||||
interleaved: false,
|
||||
},
|
||||
cost: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cache: {
|
||||
read: 0,
|
||||
write: 0,
|
||||
},
|
||||
},
|
||||
limit: {
|
||||
context: 144000,
|
||||
input: 128000,
|
||||
output: 64000,
|
||||
},
|
||||
options: {},
|
||||
headers: {},
|
||||
release_date: "2026-04-16",
|
||||
variants: {
|
||||
low: {
|
||||
reasoningEffort: "low",
|
||||
},
|
||||
},
|
||||
status: "active",
|
||||
},
|
||||
},
|
||||
)
|
||||
const models = result.models
|
||||
|
||||
expect(models["claude-opus-4.7"].api.npm).toBe("@ai-sdk/anthropic")
|
||||
expect(models["claude-opus-4.7"].variants).toBeUndefined()
|
||||
})
|
||||
|
||||
test("remaps fallback oauth model urls to the enterprise host", async () => {
|
||||
globalThis.fetch = mock(() => Promise.reject(new Error("timeout"))) as unknown as typeof fetch
|
||||
|
||||
const hooks = await CopilotAuthPlugin({
|
||||
client: {} as never,
|
||||
project: {} as never,
|
||||
directory: "",
|
||||
worktree: "",
|
||||
experimental_workspace: {
|
||||
register() {},
|
||||
},
|
||||
serverUrl: new URL("https://example.com"),
|
||||
$: {} as never,
|
||||
})
|
||||
|
||||
const models = await hooks.provider!.models!(
|
||||
{
|
||||
id: "github-copilot",
|
||||
models: {
|
||||
claude: {
|
||||
id: "claude",
|
||||
providerID: "github-copilot",
|
||||
api: {
|
||||
id: "claude-sonnet-4.5",
|
||||
url: "https://api.githubcopilot.com/v1",
|
||||
npm: "@ai-sdk/anthropic",
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never,
|
||||
{
|
||||
auth: {
|
||||
type: "oauth",
|
||||
refresh: "token",
|
||||
access: "token",
|
||||
expires: Date.now() + 60_000,
|
||||
enterpriseUrl: "ghe.example.com",
|
||||
} as never,
|
||||
},
|
||||
)
|
||||
|
||||
expect(models.claude.api.url).toBe("https://copilot-api.ghe.example.com")
|
||||
expect(models.claude.api.npm).toBe("@ai-sdk/github-copilot")
|
||||
})
|
||||
140
packages/opencode/test/plugin/install-concurrency.test.ts
Normal file
140
packages/opencode/test/plugin/install-concurrency.test.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
|
||||
import { Process } from "@/util/process"
|
||||
import { Filesystem } from "@/util/filesystem"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
const root = path.join(import.meta.dir, "../..")
|
||||
const worker = path.join(import.meta.dir, "../fixture/plug-worker.ts")
|
||||
|
||||
type Msg = {
|
||||
dir: string
|
||||
target: string
|
||||
mod: string
|
||||
holdMs?: number
|
||||
}
|
||||
|
||||
function run(msg: Msg) {
|
||||
return Process.run([process.execPath, worker, JSON.stringify(msg)], {
|
||||
cwd: root,
|
||||
nothrow: true,
|
||||
})
|
||||
}
|
||||
|
||||
async function plugin(dir: string, kinds: Array<"server" | "tui">) {
|
||||
const p = path.join(dir, "plugin")
|
||||
const server = kinds.includes("server")
|
||||
const tui = kinds.includes("tui")
|
||||
const exports: Record<string, string> = {}
|
||||
if (server) exports["./server"] = "./server.js"
|
||||
if (tui) exports["./tui"] = "./tui.js"
|
||||
await fs.mkdir(p, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(p, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "acme",
|
||||
version: "1.0.0",
|
||||
...(server ? { main: "./server.js" } : {}),
|
||||
...(Object.keys(exports).length ? { exports } : {}),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
return p
|
||||
}
|
||||
|
||||
async function read(file: string) {
|
||||
return Filesystem.readJson<{ plugin?: unknown[] }>(file)
|
||||
}
|
||||
|
||||
function mods(prefix: string, n: number) {
|
||||
return Array.from({ length: n }, (_, i) => `${prefix}-${i}@1.0.0`)
|
||||
}
|
||||
|
||||
function expectPlugins(list: unknown[] | undefined, expectMods: string[]) {
|
||||
expect(Array.isArray(list)).toBe(true)
|
||||
const hit = (list ?? []).filter((item): item is string => typeof item === "string")
|
||||
expect(hit.length).toBe(expectMods.length)
|
||||
expect(new Set(hit)).toEqual(new Set(expectMods))
|
||||
}
|
||||
|
||||
describe("plugin.install.concurrent", () => {
|
||||
test("serializes concurrent server config updates across processes", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const all = mods("mod-server", 6)
|
||||
|
||||
const out = await Promise.all(
|
||||
all.map((mod) =>
|
||||
run({
|
||||
dir: tmp.path,
|
||||
target,
|
||||
mod,
|
||||
holdMs: 30,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: all.length }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const cfg = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
expectPlugins(cfg.plugin, all)
|
||||
}, 25_000)
|
||||
|
||||
test("serializes concurrent server+tui config updates across processes", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const all = mods("mod-both", 6)
|
||||
|
||||
const out = await Promise.all(
|
||||
all.map((mod) =>
|
||||
run({
|
||||
dir: tmp.path,
|
||||
target,
|
||||
mod,
|
||||
holdMs: 30,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: all.length }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expectPlugins(server.plugin, all)
|
||||
expectPlugins(tui.plugin, all)
|
||||
}, 25_000)
|
||||
|
||||
test("preserves updates when existing config uses .json", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["seed@1.0.0"] }, null, 2))
|
||||
|
||||
const next = mods("mod-json", 5)
|
||||
const out = await Promise.all(
|
||||
next.map((mod) =>
|
||||
run({
|
||||
dir: tmp.path,
|
||||
target,
|
||||
mod,
|
||||
holdMs: 30,
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((x) => x.code)).toEqual(Array.from({ length: next.length }, () => 0))
|
||||
expect(out.map((x) => x.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const json = await read(cfg)
|
||||
expectPlugins(json.plugin, ["seed@1.0.0", ...next])
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
}, 25_000)
|
||||
})
|
||||
570
packages/opencode/test/plugin/install.test.ts
Normal file
570
packages/opencode/test/plugin/install.test.ts
Normal file
@@ -0,0 +1,570 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { parse as parseJsonc } from "jsonc-parser"
|
||||
import { Filesystem } from "@/util/filesystem"
|
||||
import { createPlugTask, type PlugCtx, type PlugDeps } from "../../src/cli/cmd/plug"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
function deps(global: string, target: string | Error): PlugDeps {
|
||||
return {
|
||||
spinner: () => ({
|
||||
start() {},
|
||||
stop() {},
|
||||
}),
|
||||
log: {
|
||||
error() {},
|
||||
info() {},
|
||||
success() {},
|
||||
},
|
||||
resolve: async () => {
|
||||
if (target instanceof Error) throw target
|
||||
return target
|
||||
},
|
||||
readText: (file) => Filesystem.readText(file),
|
||||
write: async (file, text) => {
|
||||
await Filesystem.write(file, text)
|
||||
},
|
||||
exists: (file) => Filesystem.exists(file),
|
||||
files: (dir, name) => [path.join(dir, `${name}.jsonc`), path.join(dir, `${name}.json`)],
|
||||
global,
|
||||
}
|
||||
}
|
||||
|
||||
function ctx(dir: string): PlugCtx {
|
||||
return {
|
||||
vcs: "git",
|
||||
worktree: dir,
|
||||
directory: dir,
|
||||
}
|
||||
}
|
||||
|
||||
function ctxDir(dir: string, worktree: string): PlugCtx {
|
||||
return {
|
||||
vcs: "none",
|
||||
worktree,
|
||||
directory: dir,
|
||||
}
|
||||
}
|
||||
|
||||
function ctxRoot(dir: string): PlugCtx {
|
||||
return {
|
||||
vcs: "git",
|
||||
worktree: "/",
|
||||
directory: dir,
|
||||
}
|
||||
}
|
||||
|
||||
async function plugin(
|
||||
dir: string,
|
||||
kinds?: Array<"server" | "tui">,
|
||||
opts?: {
|
||||
server?: Record<string, unknown>
|
||||
tui?: Record<string, unknown>
|
||||
},
|
||||
themes?: string[],
|
||||
) {
|
||||
const p = path.join(dir, "plugin")
|
||||
const server = kinds?.includes("server") ?? false
|
||||
const tui = kinds?.includes("tui") ?? false
|
||||
const exports: Record<string, unknown> = {}
|
||||
if (server) {
|
||||
exports["./server"] = opts?.server
|
||||
? {
|
||||
import: "./server.js",
|
||||
config: opts.server,
|
||||
}
|
||||
: "./server.js"
|
||||
}
|
||||
if (tui) {
|
||||
exports["./tui"] = opts?.tui
|
||||
? {
|
||||
import: "./tui.js",
|
||||
config: opts.tui,
|
||||
}
|
||||
: "./tui.js"
|
||||
}
|
||||
await fs.mkdir(p, { recursive: true })
|
||||
await Bun.write(
|
||||
path.join(p, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "acme",
|
||||
version: "1.0.0",
|
||||
...(server ? { main: "./server.js" } : {}),
|
||||
...(Object.keys(exports).length ? { exports } : {}),
|
||||
...(themes?.length ? { "oc-themes": themes } : {}),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
return p
|
||||
}
|
||||
|
||||
async function read(file: string) {
|
||||
return Filesystem.readJson<{
|
||||
plugin?: unknown[]
|
||||
}>(file)
|
||||
}
|
||||
|
||||
describe("plugin.install.task", () => {
|
||||
test("writes both server and tui config entries", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expect(server.plugin).toEqual(["acme@1.2.3"])
|
||||
expect(tui.plugin).toEqual(["acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("writes default options from exports config metadata", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"], {
|
||||
server: { custom: true, other: false },
|
||||
tui: { compact: true },
|
||||
})
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expect(server.plugin).toEqual([["acme@1.2.3", { custom: true, other: false }]])
|
||||
expect(tui.plugin).toEqual([["acme@1.2.3", { compact: true }]])
|
||||
})
|
||||
|
||||
test("preserves JSONC comments when adding plugins to server and tui config", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const cfg = path.join(tmp.path, ".opencode")
|
||||
const server = path.join(cfg, "opencode.jsonc")
|
||||
const tui = path.join(cfg, "tui.jsonc")
|
||||
await fs.mkdir(cfg, { recursive: true })
|
||||
await Bun.write(
|
||||
server,
|
||||
`{
|
||||
// server head
|
||||
"plugin": [
|
||||
// server keep
|
||||
"seed@1.0.0"
|
||||
],
|
||||
// server tail
|
||||
"model": "x"
|
||||
}
|
||||
`,
|
||||
)
|
||||
await Bun.write(
|
||||
tui,
|
||||
`{
|
||||
// tui head
|
||||
"plugin": [
|
||||
// tui keep
|
||||
"seed@1.0.0"
|
||||
],
|
||||
// tui tail
|
||||
"theme": "opencode"
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const serverText = await fs.readFile(server, "utf8")
|
||||
const tuiText = await fs.readFile(tui, "utf8")
|
||||
expect(serverText).toContain("// server head")
|
||||
expect(serverText).toContain("// server keep")
|
||||
expect(serverText).toContain("// server tail")
|
||||
expect(tuiText).toContain("// tui head")
|
||||
expect(tuiText).toContain("// tui keep")
|
||||
expect(tuiText).toContain("// tui tail")
|
||||
|
||||
const serverJson = parseJsonc(serverText) as { plugin?: unknown[] }
|
||||
const tuiJson = parseJsonc(tuiText) as { plugin?: unknown[] }
|
||||
expect(serverJson.plugin).toEqual(["seed@1.0.0", "acme@1.2.3"])
|
||||
expect(tuiJson.plugin).toEqual(["seed@1.0.0", "acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("preserves JSONC comments when force replacing plugin version", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.jsonc")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(
|
||||
cfg,
|
||||
`{
|
||||
"plugin": [
|
||||
// keep this note
|
||||
"acme@1.0.0"
|
||||
]
|
||||
}
|
||||
`,
|
||||
)
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
force: true,
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
const text = await fs.readFile(cfg, "utf8")
|
||||
expect(text).toContain("// keep this note")
|
||||
|
||||
const json = parseJsonc(text) as { plugin?: unknown[] }
|
||||
expect(json.plugin).toEqual(["acme@2.0.0"])
|
||||
})
|
||||
|
||||
test("supports resolver target pointing to a file", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const file = path.join(target, "index.js")
|
||||
await Bun.write(file, "export {}")
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), file),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const server = await read(path.join(tmp.path, ".opencode", "opencode.jsonc"))
|
||||
expect(server.plugin).toEqual(["acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("does not change configured package version without force", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["acme@1.0.0"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual(["acme@1.0.0"])
|
||||
})
|
||||
|
||||
test("does not change scoped package version without force", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["@scope/acme@1.0.0"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "@scope/acme@2.0.0",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual(["@scope/acme@1.0.0"])
|
||||
})
|
||||
|
||||
test("keeps file plugin entries and still adds npm plugin", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(cfg, JSON.stringify({ plugin: ["file:///tmp/acme.ts"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual(["file:///tmp/acme.ts", "acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("force replaces configured package version and keeps tuple options", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
await Bun.write(
|
||||
cfg,
|
||||
JSON.stringify(
|
||||
{
|
||||
plugin: [["acme@1.0.0", { mode: "safe" }], "acme@1.1.0", "other@1.0.0"],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
force: true,
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const json = await read(cfg)
|
||||
expect(json.plugin).toEqual([["acme@2.0.0", { mode: "safe" }], "other@1.0.0"])
|
||||
})
|
||||
|
||||
test("writes to global scope when global flag is set", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const global = path.join(tmp.path, "global")
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
global: true,
|
||||
},
|
||||
deps(global, target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
|
||||
expect(await Filesystem.exists(path.join(global, "opencode.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("writes local scope under directory when vcs is not git", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const directory = path.join(tmp.path, "dir")
|
||||
const worktree = path.join(tmp.path, "worktree")
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
await fs.mkdir(worktree, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctxDir(directory, worktree))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(directory, ".opencode", "opencode.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(worktree, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("writes local scope under directory when worktree is root slash", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const directory = path.join(tmp.path, "dir")
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctxRoot(directory))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(directory, ".opencode", "opencode.jsonc"))).toBe(true)
|
||||
})
|
||||
|
||||
test("writes tui local scope under directory when worktree is root slash", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["tui"])
|
||||
const directory = path.join(tmp.path, "dir")
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctxRoot(directory))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(directory, ".opencode", "tui.jsonc"))).toBe(true)
|
||||
})
|
||||
|
||||
test("writes only tui config for tui-only plugins", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["tui"])
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "tui.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("writes tui config for oc-themes-only packages", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, undefined, undefined, ["themes/forest.json"])
|
||||
await fs.mkdir(path.join(target, "themes"), { recursive: true })
|
||||
await Bun.write(path.join(target, "themes", "forest.json"), JSON.stringify({ theme: { text: "#fff" } }, null, 2))
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "tui.jsonc"))).toBe(true)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
|
||||
const tui = await read(path.join(tmp.path, ".opencode", "tui.jsonc"))
|
||||
expect(tui.plugin).toEqual(["acme@1.2.3"])
|
||||
})
|
||||
|
||||
test("returns false for oc-themes outside plugin directory", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, undefined, undefined, ["../outside.json"])
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "tui.jsonc"))).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("force replaces version in both server and tui configs", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server", "tui"])
|
||||
const server = path.join(tmp.path, ".opencode", "opencode.json")
|
||||
const tui = path.join(tmp.path, ".opencode", "tui.json")
|
||||
await fs.mkdir(path.dirname(server), { recursive: true })
|
||||
await Bun.write(server, JSON.stringify({ plugin: ["acme@1.0.0", "other@1.0.0"] }, null, 2))
|
||||
await Bun.write(tui, JSON.stringify({ plugin: [["acme@1.0.0", { mode: "safe" }], "other@1.0.0"] }, null, 2))
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
force: true,
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(true)
|
||||
const serverJson = await read(server)
|
||||
const tuiJson = await read(tui)
|
||||
expect(serverJson.plugin).toEqual(["acme@2.0.0", "other@1.0.0"])
|
||||
expect(tuiJson.plugin).toEqual([["acme@2.0.0", { mode: "safe" }], "other@1.0.0"])
|
||||
})
|
||||
|
||||
test("returns false and keeps config unchanged for invalid JSONC", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path, ["server"])
|
||||
const cfg = path.join(tmp.path, ".opencode", "opencode.jsonc")
|
||||
await fs.mkdir(path.dirname(cfg), { recursive: true })
|
||||
const bad = '{"plugin": ["acme@1.0.0",}'
|
||||
await Bun.write(cfg, bad)
|
||||
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@2.0.0",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await fs.readFile(cfg, "utf8")).toBe(bad)
|
||||
})
|
||||
|
||||
test("returns false when manifest declares no supported targets", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = await plugin(tmp.path)
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "tui.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false when manifest cannot be read", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const target = path.join(tmp.path, "plugin")
|
||||
await fs.mkdir(target, { recursive: true })
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@1.2.3",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), target),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
|
||||
test("returns false when install fails", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
const run = createPlugTask(
|
||||
{
|
||||
mod: "acme@9.9.9",
|
||||
},
|
||||
deps(path.join(tmp.path, "global"), new Error("boom")),
|
||||
)
|
||||
|
||||
const ok = await run(ctx(tmp.path))
|
||||
expect(ok).toBe(false)
|
||||
expect(await Filesystem.exists(path.join(tmp.path, ".opencode", "opencode.jsonc"))).toBe(false)
|
||||
})
|
||||
})
|
||||
1303
packages/opencode/test/plugin/loader-shared.test.ts
Normal file
1303
packages/opencode/test/plugin/loader-shared.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
137
packages/opencode/test/plugin/meta.test.ts
Normal file
137
packages/opencode/test/plugin/meta.test.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
import { Process } from "@/util/process"
|
||||
import { Filesystem } from "@/util/filesystem"
|
||||
|
||||
const { PluginMeta } = await import("../../src/plugin/meta")
|
||||
const root = path.join(import.meta.dir, "../..")
|
||||
const worker = path.join(import.meta.dir, "../fixture/plugin-meta-worker.ts")
|
||||
|
||||
function run(input: { file: string; spec: string; target: string; id: string }) {
|
||||
return Process.run([process.execPath, worker, JSON.stringify(input)], {
|
||||
cwd: root,
|
||||
nothrow: true,
|
||||
})
|
||||
}
|
||||
|
||||
async function map<Value>(file: string): Promise<Record<string, Value>> {
|
||||
return Filesystem.readJson<Record<string, Value>>(file)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.OPENCODE_PLUGIN_META_FILE
|
||||
})
|
||||
|
||||
describe("plugin.meta", () => {
|
||||
test("tracks file plugin loads and changes", async () => {
|
||||
await using tmp = await tmpdir<{ file: string }>({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
await Bun.write(file, "export default async () => ({})\n")
|
||||
return { file }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "state", "plugin-meta.json")
|
||||
const file = process.env.OPENCODE_PLUGIN_META_FILE!
|
||||
const spec = pathToFileURL(tmp.extra.file).href
|
||||
|
||||
const one = await PluginMeta.touch(spec, spec, "demo.file")
|
||||
expect(one.state).toBe("first")
|
||||
expect(one.entry.source).toBe("file")
|
||||
expect(one.entry.id).toBe("demo.file")
|
||||
expect(one.entry.modified).toBeDefined()
|
||||
|
||||
const two = await PluginMeta.touch(spec, spec, "demo.file")
|
||||
expect(two.state).toBe("same")
|
||||
expect(two.entry.load_count).toBe(2)
|
||||
|
||||
await Bun.write(tmp.extra.file, "export default async () => ({ ok: true })\n")
|
||||
const stamp = new Date(Date.now() + 10_000)
|
||||
await fs.utimes(tmp.extra.file, stamp, stamp)
|
||||
|
||||
const three = await PluginMeta.touch(spec, spec, "demo.file")
|
||||
expect(three.state).toBe("updated")
|
||||
expect(three.entry.load_count).toBe(3)
|
||||
expect((three.entry.modified ?? 0) > (one.entry.modified ?? 0)).toBe(true)
|
||||
|
||||
const all = await PluginMeta.list()
|
||||
expect(Object.values(all).some((item) => item.spec === spec && item.source === "file")).toBe(true)
|
||||
const saved = await map<{ spec: string; load_count: number }>(file)
|
||||
expect(saved["demo.file"]?.spec).toBe(spec)
|
||||
expect(saved["demo.file"]?.load_count).toBe(3)
|
||||
})
|
||||
|
||||
test("tracks npm plugin versions", async () => {
|
||||
await using tmp = await tmpdir<{ mod: string; pkg: string }>({
|
||||
init: async (dir) => {
|
||||
const mod = path.join(dir, "node_modules", "acme-plugin")
|
||||
const pkg = path.join(mod, "package.json")
|
||||
await fs.mkdir(mod, { recursive: true })
|
||||
await Bun.write(pkg, JSON.stringify({ name: "acme-plugin", version: "1.0.0" }, null, 2))
|
||||
return { mod, pkg }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "state", "plugin-meta.json")
|
||||
const file = process.env.OPENCODE_PLUGIN_META_FILE!
|
||||
|
||||
const one = await PluginMeta.touch("acme-plugin@latest", tmp.extra.mod, "acme-plugin")
|
||||
expect(one.state).toBe("first")
|
||||
expect(one.entry.source).toBe("npm")
|
||||
expect(one.entry.requested).toBe("latest")
|
||||
expect(one.entry.version).toBe("1.0.0")
|
||||
|
||||
await Bun.write(tmp.extra.pkg, JSON.stringify({ name: "acme-plugin", version: "1.1.0" }, null, 2))
|
||||
|
||||
const two = await PluginMeta.touch("acme-plugin@latest", tmp.extra.mod, "acme-plugin")
|
||||
expect(two.state).toBe("updated")
|
||||
expect(two.entry.version).toBe("1.1.0")
|
||||
expect(two.entry.load_count).toBe(2)
|
||||
|
||||
const all = await PluginMeta.list()
|
||||
expect(Object.values(all).some((item) => item.id === "acme-plugin" && item.version === "1.1.0")).toBe(true)
|
||||
const saved = await map<{ id: string; version?: string }>(file)
|
||||
expect(Object.values(saved).some((item) => item.id === "acme-plugin" && item.version === "1.1.0")).toBe(true)
|
||||
})
|
||||
|
||||
test("serializes concurrent metadata updates across processes", async () => {
|
||||
await using tmp = await tmpdir<{ file: string }>({
|
||||
init: async (dir) => {
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
await Bun.write(file, "export default async () => ({})\n")
|
||||
return { file }
|
||||
},
|
||||
})
|
||||
|
||||
process.env.OPENCODE_PLUGIN_META_FILE = path.join(tmp.path, "state", "plugin-meta.json")
|
||||
const file = process.env.OPENCODE_PLUGIN_META_FILE!
|
||||
const spec = pathToFileURL(tmp.extra.file).href
|
||||
const n = 12
|
||||
|
||||
const out = await Promise.all(
|
||||
Array.from({ length: n }, () =>
|
||||
run({
|
||||
file,
|
||||
spec,
|
||||
target: spec,
|
||||
id: "demo.file",
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(out.map((item) => item.code)).toEqual(Array.from({ length: n }, () => 0))
|
||||
expect(out.map((item) => item.stderr.toString()).filter(Boolean)).toEqual([])
|
||||
|
||||
const all = await PluginMeta.list()
|
||||
const hit = Object.values(all).find((item) => item.spec === spec)
|
||||
expect(hit?.load_count).toBe(n)
|
||||
|
||||
const saved = await map<{ spec: string; load_count: number }>(file)
|
||||
expect(Object.values(saved).find((item) => item.spec === spec)?.load_count).toBe(n)
|
||||
}, 20_000)
|
||||
})
|
||||
17
packages/opencode/test/plugin/openai-rollout.test.ts
Normal file
17
packages/opencode/test/plugin/openai-rollout.test.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { experimentalWebSocketsEnabled } from "../../src/plugin"
|
||||
|
||||
describe("plugin.openai.websocket rollout", () => {
|
||||
test("enables websockets by default only on pre-release channels", () => {
|
||||
expect(experimentalWebSocketsEnabled({ enabled: false, channel: "local" })).toBe(true)
|
||||
expect(experimentalWebSocketsEnabled({ enabled: false, channel: "dev" })).toBe(true)
|
||||
expect(experimentalWebSocketsEnabled({ enabled: false, channel: "beta" })).toBe(true)
|
||||
expect(experimentalWebSocketsEnabled({ enabled: false, channel: "latest" })).toBe(false)
|
||||
expect(experimentalWebSocketsEnabled({ enabled: false, channel: "prod" })).toBe(false)
|
||||
})
|
||||
|
||||
test("allows releases to opt in through the experimental flag", () => {
|
||||
expect(experimentalWebSocketsEnabled({ enabled: true, channel: "latest" })).toBe(true)
|
||||
expect(experimentalWebSocketsEnabled({ enabled: true, channel: "prod" })).toBe(true)
|
||||
})
|
||||
})
|
||||
877
packages/opencode/test/plugin/openai-ws.test.ts
Normal file
877
packages/opencode/test/plugin/openai-ws.test.ts
Normal file
@@ -0,0 +1,877 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { EventEmitter } from "node:events"
|
||||
import { createServer, type IncomingMessage, type Server as HttpServer } from "node:http"
|
||||
import net, { type AddressInfo, type Socket } from "node:net"
|
||||
import WebSocket, { WebSocketServer } from "ws"
|
||||
import { APICallError } from "ai"
|
||||
import { ProviderError } from "../../src/provider/error"
|
||||
import { OpenAIWebSocket } from "../../src/plugin/openai/ws"
|
||||
import { OpenAIWebSocketPool, TITLE_HEADER } from "../../src/plugin/openai/ws-pool"
|
||||
|
||||
describe("plugin.openai.ws", () => {
|
||||
test("derives websocket URLs and sends auth plus protocol headers", async () => {
|
||||
let headers: IncomingMessage["headers"] | undefined
|
||||
await using server = await createWebSocketServer((_socket, request) => {
|
||||
headers = request.headers
|
||||
})
|
||||
|
||||
const socket = await OpenAIWebSocket.connectResponsesWebSocket({
|
||||
url: server.wsUrl,
|
||||
headers: { authorization: "Bearer test", "content-length": "123" },
|
||||
})
|
||||
|
||||
expect(OpenAIWebSocket.toWebSocketUrl("http://example.com/v1/responses")).toBe("ws://example.com/v1/responses")
|
||||
expect(OpenAIWebSocket.toWebSocketUrl("https://example.com/v1/responses")).toBe("wss://example.com/v1/responses")
|
||||
expect(headers?.authorization).toBe("Bearer test")
|
||||
expect(headers?.["openai-beta"]).toBe(OpenAIWebSocket.PROTOCOL_HEADER)
|
||||
expect(headers?.["content-length"]).toBeUndefined()
|
||||
socket.terminate()
|
||||
})
|
||||
|
||||
test("enforces websocket connect timeout", async () => {
|
||||
await using server = await createHangingTcpServer()
|
||||
|
||||
await expect(
|
||||
OpenAIWebSocket.connectResponsesWebSocket({
|
||||
url: server.wsUrl,
|
||||
headers: {},
|
||||
timeout: 20,
|
||||
}),
|
||||
).rejects.toThrow("WebSocket connect timed out")
|
||||
})
|
||||
|
||||
test("surfaces websocket upgrade rejection messages", async () => {
|
||||
await using server = await createRejectingWebSocketServer(() => {})
|
||||
|
||||
await expect(
|
||||
OpenAIWebSocket.connectResponsesWebSocket({
|
||||
url: server.wsUrl,
|
||||
headers: {},
|
||||
}),
|
||||
).rejects.toThrow("Expected 101 status code")
|
||||
})
|
||||
|
||||
test("enforces websocket send idle timeout", async () => {
|
||||
const socket = new (class extends EventEmitter {
|
||||
send(_data: string, _callback: (error?: Error) => void) {}
|
||||
})() as unknown as WebSocket
|
||||
const invalid: string[] = []
|
||||
const response = OpenAIWebSocket.streamResponsesWebSocket({
|
||||
socket,
|
||||
body: { stream: true, input: "hi" },
|
||||
idleTimeout: 20,
|
||||
onConnectionInvalid: (error) => invalid.push(error.message),
|
||||
})
|
||||
|
||||
expect((await readTextError(response.text())).message).toContain("idle timeout sending websocket request")
|
||||
expect(invalid).toEqual(["idle timeout sending websocket request"])
|
||||
})
|
||||
|
||||
test("streams websocket events as SSE and handles response.done", async () => {
|
||||
let requestBody: unknown
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
socket.once("message", (data) => {
|
||||
requestBody = JSON.parse(data.toString())
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "hello" }))
|
||||
socket.send(JSON.stringify({ type: "response.done", response: { id: "resp_123" } }))
|
||||
socket.close(1000, "done")
|
||||
})
|
||||
})
|
||||
|
||||
const socket = await OpenAIWebSocket.connectResponsesWebSocket({
|
||||
url: server.wsUrl,
|
||||
headers: { authorization: "Bearer test", "content-length": "123" },
|
||||
})
|
||||
const completed: Record<string, unknown>[] = []
|
||||
const response = OpenAIWebSocket.streamResponsesWebSocket({
|
||||
socket,
|
||||
body: { stream: true, background: true, input: "hi" },
|
||||
onComplete: (event) => completed.push(event),
|
||||
})
|
||||
|
||||
expect(await response.text()).toBe(
|
||||
'data: {"type":"response.output_text.delta","delta":"hello"}\n\ndata: {"type":"response.done","response":{"id":"resp_123"}}\n\ndata: [DONE]\n\n',
|
||||
)
|
||||
expect(requestBody).toEqual({ type: "response.create", input: "hi" })
|
||||
expect(completed).toHaveLength(1)
|
||||
expect(completed[0]?.type).toBe("response.done")
|
||||
})
|
||||
|
||||
test("errors the SSE stream when the server closes before a terminal event", async () => {
|
||||
const invalid: Error[] = []
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
socket.once("message", () => {
|
||||
socket.close(1009, "payload too large")
|
||||
})
|
||||
})
|
||||
|
||||
const socket = await OpenAIWebSocket.connectResponsesWebSocket({ url: server.wsUrl, headers: {} })
|
||||
const response = OpenAIWebSocket.streamResponsesWebSocket({
|
||||
socket,
|
||||
body: { stream: true, input: "hi" },
|
||||
onConnectionInvalid: (error) => invalid.push(error),
|
||||
})
|
||||
|
||||
expect((await readTextError(response.text())).message).toContain(
|
||||
"WebSocket closed before response.completed (code 1009: message too big: payload too large)",
|
||||
)
|
||||
expect(invalid[0]).toBeInstanceOf(ProviderError.ResponseStreamError)
|
||||
expect(invalid.map((error) => error.message)).toEqual([
|
||||
"WebSocket closed before response.completed (code 1009: message too big: payload too large)",
|
||||
])
|
||||
})
|
||||
|
||||
test("rejects unexpected binary websocket frames", async () => {
|
||||
const invalid: string[] = []
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
socket.once("message", () => {
|
||||
socket.send(Buffer.from("not json text"))
|
||||
})
|
||||
})
|
||||
|
||||
const socket = await OpenAIWebSocket.connectResponsesWebSocket({ url: server.wsUrl, headers: {} })
|
||||
const response = OpenAIWebSocket.streamResponsesWebSocket({
|
||||
socket,
|
||||
body: { stream: true, input: "hi" },
|
||||
onConnectionInvalid: (error) => invalid.push(error.message),
|
||||
})
|
||||
|
||||
expect((await readTextError(response.text())).message).toContain("Unexpected binary WebSocket frame")
|
||||
expect(invalid).toEqual(["Unexpected binary WebSocket frame"])
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin.openai.ws-pool", () => {
|
||||
test("reuses one healthy websocket for sequential requests", async () => {
|
||||
let connections = 0
|
||||
let messages = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.on("message", () => {
|
||||
messages += 1
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${messages}` } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect(await first.text()).toContain("data: [DONE]")
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(1)
|
||||
expect(messages).toBe(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("rotates a socket that exceeds max connection age", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.on("message", () => {
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${connections}` } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
maxConnectionAge: 0,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect(await first.text()).toContain("data: [DONE]")
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("falls back to HTTP after websocket setup retries are exhausted", async () => {
|
||||
const attempts: string[] = []
|
||||
await using server = await createRejectingWebSocketServer(() => attempts.push("websocket"))
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
connectTimeout: 100,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "false" }))
|
||||
expect(await readTextError(first.text())).toBeInstanceOf(ProviderError.ResponseStreamError)
|
||||
const second = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "false" }))
|
||||
const third = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "false" }))
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(await third.text()).toBe("http")
|
||||
expect(attempts).toEqual(["websocket", "websocket"])
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
expect(server.httpRequests[0]?.headers[TITLE_HEADER]).toBeUndefined()
|
||||
expect(server.httpRequests[1]?.headers[TITLE_HEADER]).toBeUndefined()
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("keeps HTTP fallback active after its idle timeout", async () => {
|
||||
let websocketAttempts = 0
|
||||
await using server = await createRejectingWebSocketServer(() => websocketAttempts++)
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
connectTimeout: 100,
|
||||
idleTimeout: 20,
|
||||
streamRetries: 0,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect(await first.text()).toBe("http")
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(websocketAttempts).toBe(1)
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("removes HTTP fallback when its session is deleted", async () => {
|
||||
let websocketAttempts = 0
|
||||
await using server = await createRejectingWebSocketServer(() => websocketAttempts++)
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
connectTimeout: 100,
|
||||
streamRetries: 0,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect(await first.text()).toBe("http")
|
||||
fetch.remove("session-1")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(websocketAttempts).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("terminates active websocket connections when their session is deleted", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
if (connections === 1) {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
return
|
||||
}
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_after_remove" } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
const firstText = first.text()
|
||||
fetch.remove("session-1")
|
||||
expect((await readTextError(firstText)).message).toContain("WebSocket closed before response.completed")
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("prunes idle websocket connections after completed responses", async () => {
|
||||
let connections = 0
|
||||
let closed = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("close", () => closed++)
|
||||
socket.once("message", () => {
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${connections}` } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
idleTimeout: 20,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect(await first.text()).toContain("data: [DONE]")
|
||||
await waitFor(() => closed === 1, "idle websocket was not pruned")
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("invalidates but does not reuse a socket after terminal failure frames", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
socket.send(JSON.stringify({ type: connections === 1 ? "response.failed" : "response.completed" }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect(await first.text()).toContain('data: {"type":"response.failed"}')
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
expect(await second.text()).toContain('data: {"type":"response.completed"}')
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(0)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("returns initial websocket error frames as HTTP-style API errors", async () => {
|
||||
const error = {
|
||||
type: "invalid_request_error",
|
||||
message: "The model is not supported when using Codex with a ChatGPT account.",
|
||||
}
|
||||
const event = {
|
||||
type: "error",
|
||||
status: 400,
|
||||
error,
|
||||
headers: {
|
||||
"x-codex-primary-window-minutes": 15,
|
||||
ignored: { nested: true },
|
||||
},
|
||||
}
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
socket.once("message", () => {
|
||||
socket.send(JSON.stringify(event))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const response = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(response.headers.get("content-type")).toContain("application/json")
|
||||
expect(response.headers.get("x-codex-primary-window-minutes")).toBe("15")
|
||||
expect(response.headers.get("ignored")).toBeNull()
|
||||
expect(await response.json()).toEqual(event)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("fails mid-stream wrapped websocket errors as HTTP-style API errors", async () => {
|
||||
const event = {
|
||||
type: "error",
|
||||
status_code: 429,
|
||||
error: {
|
||||
type: "usage_limit_reached",
|
||||
message: "The usage limit has been reached",
|
||||
},
|
||||
headers: {
|
||||
"x-codex-primary-used-percent": "100.0",
|
||||
},
|
||||
}
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
socket.once("message", () => {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
socket.send(JSON.stringify(event))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const response = await fetch(server.url, streamRequest())
|
||||
const error = await readTextError(response.text())
|
||||
|
||||
expect(APICallError.isInstance(error)).toBe(true)
|
||||
if (!APICallError.isInstance(error)) throw new Error("Expected APICallError")
|
||||
expect(error.statusCode).toBe(429)
|
||||
expect(error.responseHeaders).toEqual({ "x-codex-primary-used-percent": "100.0" })
|
||||
expect(error.responseBody).toBe(JSON.stringify(event))
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("retries websocket connection limit errors on the next stream attempt", async () => {
|
||||
let connections = 0
|
||||
let messages = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
messages += 1
|
||||
if (connections === 1) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
status: 400,
|
||||
error: {
|
||||
type: "invalid_request_error",
|
||||
code: "websocket_connection_limit_reached",
|
||||
message: "Responses websocket connection limit reached",
|
||||
},
|
||||
}),
|
||||
)
|
||||
return
|
||||
}
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_retry" } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("Responses websocket connection limit reached")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
const text = await second.text()
|
||||
|
||||
expect(text).not.toContain("websocket_connection_limit_reached")
|
||||
expect(text).toContain('data: {"type":"response.completed","response":{"id":"resp_retry"}}')
|
||||
expect(text).toContain("data: [DONE]")
|
||||
expect(connections).toBe(2)
|
||||
expect(messages).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(0)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("falls back to HTTP after websocket connection limit retries are exhausted", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
status: 400,
|
||||
error: {
|
||||
type: "invalid_request_error",
|
||||
code: "websocket_connection_limit_reached",
|
||||
message: "Responses websocket connection limit reached",
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
streamRetries: 2,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("Responses websocket connection limit reached")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(second.text())).message).toContain("Responses websocket connection limit reached")
|
||||
const third = await fetch(server.url, streamRequest())
|
||||
const fourth = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await third.text()).toBe("http")
|
||||
expect(await fourth.text()).toBe("http")
|
||||
expect(connections).toBe(3)
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("shares the websocket retry budget across stream and connection limit failures", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
if (connections === 1) {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
socket.terminate()
|
||||
return
|
||||
}
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
error: {
|
||||
code: "websocket_connection_limit_reached",
|
||||
message: "Responses websocket connection limit reached",
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("WebSocket closed before response.completed")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(1)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("retries websocket idle failures before first event then falls back to HTTP", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
idleTimeout: 20,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("idle timeout waiting for websocket")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
const third = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(await third.text()).toBe("http")
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("keeps websocket retry state until the failed stream becomes idle", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
idleTimeout: 500,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 250))
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("idle timeout waiting for websocket")
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(1)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("retries failed websocket streams before using HTTP fallback", async () => {
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
socket.once("message", () => {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
idleTimeout: 20,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("idle timeout waiting for websocket")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(second.text())).message).toContain("idle timeout waiting for websocket")
|
||||
const third = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await third.text()).toBe("http")
|
||||
expect(server.httpRequests).toHaveLength(1)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("resets websocket stream failures after a completed response", async () => {
|
||||
let connections = 0
|
||||
let requests = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.on("message", () => {
|
||||
requests += 1
|
||||
if (requests === 1 || requests === 3) {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
socket.terminate()
|
||||
return
|
||||
}
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: `resp_${requests}` } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("WebSocket closed before response.completed")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
const third = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(third.text())).message).toContain("WebSocket closed before response.completed")
|
||||
const fourth = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await fourth.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(3)
|
||||
expect(requests).toBe(4)
|
||||
expect(server.httpRequests).toHaveLength(0)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("falls back to HTTP for missing session and title requests", async () => {
|
||||
await using server = await createWebSocketServer(() => {})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch()
|
||||
|
||||
const missingSession = await fetch(server.url, {
|
||||
method: "POST",
|
||||
headers: { [TITLE_HEADER]: "false" },
|
||||
body: JSON.stringify({ stream: true }),
|
||||
})
|
||||
const title = await fetch(server.url, streamRequest({ [TITLE_HEADER]: "true" }))
|
||||
|
||||
expect(await missingSession.text()).toBe("http")
|
||||
expect(await title.text()).toBe("http")
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
expect(server.httpRequests[0]?.headers[TITLE_HEADER]).toBeUndefined()
|
||||
expect(server.httpRequests[1]?.headers[TITLE_HEADER]).toBeUndefined()
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("falls back to HTTP while a websocket lane is busy", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
})
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest({}, abort.signal))
|
||||
const firstText = first.text()
|
||||
await waitFor(() => connections === 1, "websocket did not connect")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(server.httpRequests).toHaveLength(1)
|
||||
expect(connections).toBe(1)
|
||||
abort.abort(new Error("stop"))
|
||||
expect((await readTextError(firstText)).message).toContain("stop")
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("reserves a websocket lane while its socket is connecting", async () => {
|
||||
await using server = await createHangingTcpServer()
|
||||
await using fallback = await createHttpServer()
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
connectTimeout: 20,
|
||||
streamRetries: 0,
|
||||
})
|
||||
|
||||
const first = fetch(fallback.url, streamRequest())
|
||||
await waitFor(() => server.connections() === 1, "first websocket did not begin connecting")
|
||||
const second = fetch(fallback.url, streamRequest())
|
||||
|
||||
expect(await (await second).text()).toBe("http")
|
||||
expect(await (await first).text()).toBe("http")
|
||||
expect(server.connections()).toBe(1)
|
||||
expect(fallback.httpRequests).toHaveLength(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("retries unexpected closes before first event then falls back to HTTP", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
socket.close(1001, "server shutdown")
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
streamRetries: 1,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
expect((await readTextError(first.text())).message).toContain("WebSocket closed before response.completed")
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
const third = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toBe("http")
|
||||
expect(await third.text()).toBe("http")
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(2)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("does not keep HTTP fallback active after aborting a websocket response", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
if (connections === 1) {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
return
|
||||
}
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_456" } }))
|
||||
})
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest({}, abort.signal))
|
||||
const firstText = first.text()
|
||||
await waitFor(() => connections === 1, "first websocket did not connect")
|
||||
abort.abort(new Error("stop"))
|
||||
expect((await readTextError(firstText)).message).toContain("stop")
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(0)
|
||||
fetch.close()
|
||||
})
|
||||
|
||||
test("releases the websocket lane when the response body is cancelled", async () => {
|
||||
let connections = 0
|
||||
await using server = await createWebSocketServer((socket) => {
|
||||
connections += 1
|
||||
socket.once("message", () => {
|
||||
if (connections === 1) {
|
||||
socket.send(JSON.stringify({ type: "response.output_text.delta", delta: "started" }))
|
||||
return
|
||||
}
|
||||
socket.send(JSON.stringify({ type: "response.completed", response: { id: "resp_after_cancel" } }))
|
||||
})
|
||||
})
|
||||
const fetch = OpenAIWebSocketPool.createWebSocketFetch({
|
||||
url: server.url,
|
||||
})
|
||||
|
||||
const first = await fetch(server.url, streamRequest())
|
||||
await waitFor(() => connections === 1, "first websocket did not connect")
|
||||
await first.body!.cancel("stop")
|
||||
|
||||
const second = await fetch(server.url, streamRequest())
|
||||
|
||||
expect(await second.text()).toContain("data: [DONE]")
|
||||
expect(connections).toBe(2)
|
||||
expect(server.httpRequests).toHaveLength(0)
|
||||
fetch.close()
|
||||
})
|
||||
})
|
||||
|
||||
function streamRequest(headers?: Record<string, string>, signal?: AbortSignal): RequestInit {
|
||||
return {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"session-id": "session-1",
|
||||
authorization: "Bearer test",
|
||||
...headers,
|
||||
},
|
||||
body: JSON.stringify({ stream: true, input: "hi" }),
|
||||
signal,
|
||||
}
|
||||
}
|
||||
|
||||
async function readTextError(promise: Promise<string>) {
|
||||
// Bun 1.3.14 hangs on expect(response.text()).rejects for streams errored from ws callbacks.
|
||||
return promise.then(
|
||||
() => {
|
||||
throw new Error("Expected response text to reject")
|
||||
},
|
||||
(error) => {
|
||||
expect(error).toBeInstanceOf(Error)
|
||||
return error as Error
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
async function createWebSocketServer(onConnection: (socket: WebSocket, request: IncomingMessage) => void) {
|
||||
const http = await createHttpServer()
|
||||
const server = new WebSocketServer({ server: http.server })
|
||||
server.on("connection", onConnection)
|
||||
return websocketServerHandle(server, http)
|
||||
}
|
||||
|
||||
async function createHangingTcpServer() {
|
||||
const sockets = new Set<Socket>()
|
||||
let connections = 0
|
||||
const server = net.createServer((socket) => {
|
||||
connections += 1
|
||||
sockets.add(socket)
|
||||
socket.on("close", () => sockets.delete(socket))
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
|
||||
const address = server.address() as AddressInfo
|
||||
return {
|
||||
url: `http://127.0.0.1:${address.port}/v1/responses`,
|
||||
wsUrl: `ws://127.0.0.1:${address.port}/v1/responses`,
|
||||
connections: () => connections,
|
||||
async [Symbol.asyncDispose]() {
|
||||
for (const socket of sockets) socket.destroy()
|
||||
server.close()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function createRejectingWebSocketServer(onAttempt: () => void) {
|
||||
const http = await createHttpServer()
|
||||
const server = new WebSocketServer({
|
||||
server: http.server,
|
||||
verifyClient(_info, callback) {
|
||||
onAttempt()
|
||||
callback(false, 401, "denied")
|
||||
},
|
||||
})
|
||||
return websocketServerHandle(server, http)
|
||||
}
|
||||
|
||||
async function createHttpServer() {
|
||||
const httpRequests: IncomingMessage[] = []
|
||||
const server = createServer((request, response) => {
|
||||
httpRequests.push(request)
|
||||
response.writeHead(200, { "content-type": "text/plain" })
|
||||
response.end("http")
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))
|
||||
const address = server.address() as AddressInfo
|
||||
return {
|
||||
server,
|
||||
httpRequests,
|
||||
url: `http://127.0.0.1:${address.port}/v1/responses`,
|
||||
async [Symbol.asyncDispose]() {
|
||||
await closeHttpServer(server)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function websocketServerHandle(server: WebSocketServer, http: Awaited<ReturnType<typeof createHttpServer>>) {
|
||||
return {
|
||||
url: http.url,
|
||||
wsUrl: http.url.replace(/^http/, "ws"),
|
||||
httpRequests: http.httpRequests,
|
||||
async [Symbol.asyncDispose]() {
|
||||
for (const socket of server.clients) socket.terminate()
|
||||
server.close()
|
||||
http.server.close()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function closeHttpServer(server: HttpServer) {
|
||||
return new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())))
|
||||
}
|
||||
|
||||
async function waitFor(predicate: () => boolean, message: string) {
|
||||
const started = Date.now()
|
||||
while (!predicate()) {
|
||||
if (Date.now() - started > 1_000) throw new Error(message)
|
||||
await new Promise((resolve) => setTimeout(resolve, 1))
|
||||
}
|
||||
}
|
||||
88
packages/opencode/test/plugin/shared.test.ts
Normal file
88
packages/opencode/test/plugin/shared.test.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { parsePluginSpecifier } from "../../src/plugin/shared"
|
||||
|
||||
describe("parsePluginSpecifier", () => {
|
||||
test("parses standard npm package without version", () => {
|
||||
expect(parsePluginSpecifier("acme")).toEqual({
|
||||
pkg: "acme",
|
||||
version: "latest",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses standard npm package with version", () => {
|
||||
expect(parsePluginSpecifier("acme@1.0.0")).toEqual({
|
||||
pkg: "acme",
|
||||
version: "1.0.0",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses scoped npm package without version", () => {
|
||||
expect(parsePluginSpecifier("@opencode/acme")).toEqual({
|
||||
pkg: "@opencode/acme",
|
||||
version: "latest",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses scoped npm package with version", () => {
|
||||
expect(parsePluginSpecifier("@opencode/acme@1.0.0")).toEqual({
|
||||
pkg: "@opencode/acme",
|
||||
version: "1.0.0",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses package with git+https url", () => {
|
||||
expect(parsePluginSpecifier("acme@git+https://github.com/opencode/acme.git")).toEqual({
|
||||
pkg: "acme",
|
||||
version: "git+https://github.com/opencode/acme.git",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses scoped package with git+https url", () => {
|
||||
expect(parsePluginSpecifier("@opencode/acme@git+https://github.com/opencode/acme.git")).toEqual({
|
||||
pkg: "@opencode/acme",
|
||||
version: "git+https://github.com/opencode/acme.git",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses package with git+ssh url containing another @", () => {
|
||||
expect(parsePluginSpecifier("acme@git+ssh://git@github.com/opencode/acme.git")).toEqual({
|
||||
pkg: "acme",
|
||||
version: "git+ssh://git@github.com/opencode/acme.git",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses scoped package with git+ssh url containing another @", () => {
|
||||
expect(parsePluginSpecifier("@opencode/acme@git+ssh://git@github.com/opencode/acme.git")).toEqual({
|
||||
pkg: "@opencode/acme",
|
||||
version: "git+ssh://git@github.com/opencode/acme.git",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses unaliased git+ssh url", () => {
|
||||
expect(parsePluginSpecifier("git+ssh://git@github.com/opencode/acme.git")).toEqual({
|
||||
pkg: "git+ssh://git@github.com/opencode/acme.git",
|
||||
version: "",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses npm alias using the alias name", () => {
|
||||
expect(parsePluginSpecifier("acme@npm:@opencode/acme@1.0.0")).toEqual({
|
||||
pkg: "acme",
|
||||
version: "npm:@opencode/acme@1.0.0",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses bare npm protocol specifier using the target package", () => {
|
||||
expect(parsePluginSpecifier("npm:@opencode/acme@1.0.0")).toEqual({
|
||||
pkg: "@opencode/acme",
|
||||
version: "1.0.0",
|
||||
})
|
||||
})
|
||||
|
||||
test("parses unversioned npm protocol specifier", () => {
|
||||
expect(parsePluginSpecifier("npm:@opencode/acme")).toEqual({
|
||||
pkg: "@opencode/acme",
|
||||
version: "latest",
|
||||
})
|
||||
})
|
||||
})
|
||||
120
packages/opencode/test/plugin/trigger.test.ts
Normal file
120
packages/opencode/test/plugin/trigger.test.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { FetchHttpClient } from "effect/unstable/http"
|
||||
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
|
||||
import { FSUtil } from "@opencode-ai/core/fs-util"
|
||||
import { EffectFlock } from "@opencode-ai/core/util/effect-flock"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { EventV2Bridge } from "../../src/event-v2-bridge"
|
||||
import { Config } from "../../src/config/config"
|
||||
import { Env } from "../../src/env"
|
||||
import { RuntimeFlags } from "../../src/effect/runtime-flags"
|
||||
import { Plugin } from "../../src/plugin/index"
|
||||
|
||||
import { TestInstance } from "../fixture/fixture"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { AccountTest } from "../fake/account"
|
||||
import { AuthTest } from "../fake/auth"
|
||||
import { NpmTest } from "../fake/npm"
|
||||
import { ProviderV2 } from "@opencode-ai/core/provider"
|
||||
import { ModelV2 } from "@opencode-ai/core/model"
|
||||
|
||||
const configLayer = Config.layer.pipe(
|
||||
Layer.provide(EffectFlock.defaultLayer),
|
||||
Layer.provide(FSUtil.defaultLayer),
|
||||
Layer.provide(Env.defaultLayer),
|
||||
Layer.provide(AuthTest.empty),
|
||||
Layer.provide(AccountTest.empty),
|
||||
Layer.provide(NpmTest.noop),
|
||||
Layer.provide(FetchHttpClient.layer),
|
||||
)
|
||||
const it = testEffect(
|
||||
Layer.mergeAll(
|
||||
Plugin.layer.pipe(
|
||||
Layer.provide(EventV2Bridge.defaultLayer),
|
||||
Layer.provide(configLayer),
|
||||
Layer.provide(RuntimeFlags.layer({ disableDefaultPlugins: true })),
|
||||
),
|
||||
CrossSpawnSpawner.defaultLayer,
|
||||
),
|
||||
)
|
||||
const systemHook = "experimental.chat.system.transform"
|
||||
|
||||
function withProject<A, E, R>(source: string, self: Effect.Effect<A, E, R>) {
|
||||
return Effect.gen(function* () {
|
||||
const test = yield* TestInstance
|
||||
const file = path.join(test.directory, "plugin.ts")
|
||||
yield* Effect.all(
|
||||
[
|
||||
Effect.promise(() => Bun.write(file, source)),
|
||||
Effect.promise(() =>
|
||||
Bun.write(
|
||||
path.join(test.directory, "opencode.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
plugin: [pathToFileURL(file).href],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ discard: true, concurrency: 2 },
|
||||
)
|
||||
return yield* self
|
||||
})
|
||||
}
|
||||
|
||||
const triggerSystemTransform = Effect.fn("PluginTriggerTest.triggerSystemTransform")(function* () {
|
||||
const plugin = yield* Plugin.Service
|
||||
const out = { system: [] as string[] }
|
||||
yield* plugin.trigger(
|
||||
systemHook,
|
||||
{
|
||||
model: {
|
||||
providerID: ProviderV2.ID.anthropic,
|
||||
modelID: ModelV2.ID.make("claude-sonnet-4-6"),
|
||||
},
|
||||
},
|
||||
out,
|
||||
)
|
||||
return out.system
|
||||
})
|
||||
|
||||
describe("plugin.trigger", () => {
|
||||
it.instance("runs synchronous hooks without crashing", () =>
|
||||
withProject(
|
||||
[
|
||||
"export default async () => ({",
|
||||
` ${JSON.stringify(systemHook)}: (_input, output) => {`,
|
||||
' output.system.unshift("sync")',
|
||||
" },",
|
||||
"})",
|
||||
"",
|
||||
].join("\n"),
|
||||
Effect.gen(function* () {
|
||||
expect(yield* triggerSystemTransform()).toEqual(["sync"])
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
it.instance("awaits asynchronous hooks", () =>
|
||||
withProject(
|
||||
[
|
||||
"export default async () => ({",
|
||||
` ${JSON.stringify(systemHook)}: async (_input, output) => {`,
|
||||
" await Bun.sleep(1)",
|
||||
' output.system.unshift("async")',
|
||||
" },",
|
||||
"})",
|
||||
"",
|
||||
].join("\n"),
|
||||
Effect.gen(function* () {
|
||||
expect(yield* triggerSystemTransform()).toEqual(["async"])
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
140
packages/opencode/test/plugin/workspace-adapter.test.ts
Normal file
140
packages/opencode/test/plugin/workspace-adapter.test.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { afterEach, describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { FetchHttpClient } from "effect/unstable/http"
|
||||
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { FSUtil } from "@opencode-ai/core/fs-util"
|
||||
import { Ripgrep } from "@opencode-ai/core/ripgrep"
|
||||
import { EffectFlock } from "@opencode-ai/core/util/effect-flock"
|
||||
import path from "path"
|
||||
import { pathToFileURL } from "url"
|
||||
import { Auth } from "../../src/auth"
|
||||
import { EventV2Bridge } from "../../src/event-v2-bridge"
|
||||
import { Config } from "../../src/config/config"
|
||||
import { Env } from "../../src/env"
|
||||
import { RuntimeFlags } from "../../src/effect/runtime-flags"
|
||||
import { Workspace } from "../../src/control-plane/workspace"
|
||||
import { Plugin } from "../../src/plugin/index"
|
||||
import { InstanceBootstrap } from "../../src/project/bootstrap-service"
|
||||
import { InstanceStore } from "../../src/project/instance-store"
|
||||
import { Project } from "../../src/project/project"
|
||||
import { Vcs } from "../../src/project/vcs"
|
||||
import { InstanceState } from "../../src/effect/instance-state"
|
||||
import { Session } from "../../src/session/session"
|
||||
import { SessionPrompt } from "../../src/session/prompt"
|
||||
import { disposeAllInstances, TestInstance } from "../fixture/fixture"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { AccountTest } from "../fake/account"
|
||||
import { AuthTest } from "../fake/auth"
|
||||
import { NpmTest } from "../fake/npm"
|
||||
|
||||
const configLayer = Config.layer.pipe(
|
||||
Layer.provide(EffectFlock.defaultLayer),
|
||||
Layer.provide(FSUtil.defaultLayer),
|
||||
Layer.provide(Env.defaultLayer),
|
||||
Layer.provide(AuthTest.empty),
|
||||
Layer.provide(AccountTest.empty),
|
||||
Layer.provide(NpmTest.noop),
|
||||
Layer.provide(FetchHttpClient.layer),
|
||||
)
|
||||
const pluginLayer = Plugin.layer.pipe(
|
||||
Layer.provide(EventV2Bridge.defaultLayer),
|
||||
Layer.provide(configLayer),
|
||||
Layer.provide(RuntimeFlags.layer({ disableDefaultPlugins: true })),
|
||||
)
|
||||
const noopBootstrapLayer = Layer.succeed(InstanceBootstrap.Service, InstanceBootstrap.Service.of({ run: Effect.void }))
|
||||
const workspaceLayer = Workspace.layer.pipe(
|
||||
Layer.provide(Auth.defaultLayer),
|
||||
Layer.provide(Session.defaultLayer),
|
||||
Layer.provide(SessionPrompt.defaultLayer),
|
||||
Layer.provide(Project.defaultLayer),
|
||||
Layer.provide(Vcs.defaultLayer),
|
||||
Layer.provide(FetchHttpClient.layer),
|
||||
Layer.provide(Database.defaultLayer),
|
||||
Layer.provide(EventV2Bridge.defaultLayer),
|
||||
Layer.provide(FSUtil.defaultLayer),
|
||||
Layer.provide(InstanceStore.defaultLayer.pipe(Layer.provide(noopBootstrapLayer))),
|
||||
Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: true })),
|
||||
)
|
||||
const it = testEffect(
|
||||
Layer.mergeAll(pluginLayer, workspaceLayer, CrossSpawnSpawner.defaultLayer).pipe(Layer.provide(Ripgrep.defaultLayer)),
|
||||
)
|
||||
|
||||
afterEach(async () => {
|
||||
await disposeAllInstances()
|
||||
})
|
||||
|
||||
describe("plugin.workspace", () => {
|
||||
it.instance("plugin can install a workspace adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const dir = (yield* TestInstance).directory
|
||||
const type = `plug-${Math.random().toString(36).slice(2)}`
|
||||
const file = path.join(dir, "plugin.ts")
|
||||
const mark = path.join(dir, "created.json")
|
||||
const space = path.join(dir, "space")
|
||||
yield* Effect.promise(() =>
|
||||
Bun.write(
|
||||
file,
|
||||
[
|
||||
"export default async ({ experimental_workspace }) => {",
|
||||
` experimental_workspace.register(${JSON.stringify(type)}, {`,
|
||||
' name: "plug",',
|
||||
' description: "plugin workspace adapter",',
|
||||
" configure(input) {",
|
||||
` return { ...input, name: "plug", branch: "plug/main", directory: ${JSON.stringify(space)} }`,
|
||||
" },",
|
||||
" async create(input) {",
|
||||
` await Bun.write(${JSON.stringify(mark)}, JSON.stringify(input))`,
|
||||
" },",
|
||||
" async remove() {},",
|
||||
" target(input) {",
|
||||
' return { type: "local", directory: input.directory }',
|
||||
" },",
|
||||
" })",
|
||||
" return {}",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
),
|
||||
)
|
||||
|
||||
yield* Effect.promise(() =>
|
||||
Bun.write(
|
||||
path.join(dir, "opencode.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
plugin: [pathToFileURL(file).href],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
const plugin = yield* Plugin.Service
|
||||
yield* plugin.init()
|
||||
const workspace = yield* Workspace.Service
|
||||
const ctx = yield* InstanceState.context
|
||||
const info = yield* workspace.create({
|
||||
type,
|
||||
branch: null,
|
||||
extra: { key: "value" },
|
||||
projectID: ctx.project.id,
|
||||
})
|
||||
|
||||
expect(info.type).toBe(type)
|
||||
expect(info.name).toBe("plug")
|
||||
expect(info.branch).toBe("plug/main")
|
||||
expect(info.directory).toBe(space)
|
||||
expect(info.extra).toEqual({ key: "value" })
|
||||
expect(JSON.parse(yield* Effect.promise(() => Bun.file(mark).text()))).toMatchObject({
|
||||
type,
|
||||
name: "plug",
|
||||
branch: "plug/main",
|
||||
directory: space,
|
||||
extra: { key: "value" },
|
||||
})
|
||||
}),
|
||||
)
|
||||
})
|
||||
634
packages/opencode/test/plugin/xai.test.ts
Normal file
634
packages/opencode/test/plugin/xai.test.ts
Normal file
@@ -0,0 +1,634 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
accessTokenIsExpiring,
|
||||
buildAuthorizeUrl,
|
||||
escapeHtml,
|
||||
pollDeviceCodeToken,
|
||||
requestDeviceCode,
|
||||
XaiAuthPlugin,
|
||||
} from "../../src/plugin/xai"
|
||||
import { OAUTH_DUMMY_KEY } from "../../src/auth"
|
||||
|
||||
function makeJwt(payload: object): string {
|
||||
const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url")
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString("base64url")
|
||||
return `${header}.${body}.sig`
|
||||
}
|
||||
|
||||
function makeInput(opts?: { failSet?: boolean }) {
|
||||
const setCalls: Array<Record<string, unknown>> = []
|
||||
return {
|
||||
input: {
|
||||
client: {
|
||||
auth: {
|
||||
set: async (req: Record<string, unknown>) => {
|
||||
setCalls.push(req)
|
||||
if (opts?.failSet) throw new Error("auth.set boom")
|
||||
},
|
||||
},
|
||||
},
|
||||
} as any,
|
||||
setCalls,
|
||||
}
|
||||
}
|
||||
|
||||
function makeServer(handler: (request: Request, url: URL) => Response | Promise<Response>) {
|
||||
return Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => handler(request, new URL(request.url)),
|
||||
})
|
||||
}
|
||||
|
||||
function serverOptions(server: ReturnType<typeof Bun.serve>) {
|
||||
return {
|
||||
authorizeUrl: new URL("/oauth2/authorize", server.url).toString(),
|
||||
tokenUrl: new URL("/oauth2/token", server.url).toString(),
|
||||
deviceAuthorizationUrl: new URL("/oauth2/device/code", server.url).toString(),
|
||||
}
|
||||
}
|
||||
|
||||
describe("plugin.xai", () => {
|
||||
describe("accessTokenIsExpiring", () => {
|
||||
test("returns true for an already-expired JWT", () => {
|
||||
expect(accessTokenIsExpiring(makeJwt({ exp: Math.floor(Date.now() / 1000) - 60 }), 0)).toBe(true)
|
||||
})
|
||||
|
||||
test("returns false for a fresh JWT outside the skew window", () => {
|
||||
expect(accessTokenIsExpiring(makeJwt({ exp: Math.floor(Date.now() / 1000) + 3600 }), 0)).toBe(false)
|
||||
})
|
||||
|
||||
test("honors the skew window", () => {
|
||||
const nearExpiry = makeJwt({ exp: Math.floor(Date.now() / 1000) + 30 })
|
||||
expect(accessTokenIsExpiring(nearExpiry, 60_000)).toBe(true)
|
||||
expect(accessTokenIsExpiring(nearExpiry, 0)).toBe(false)
|
||||
})
|
||||
|
||||
test("clamps negative skew to zero rather than refusing to refresh", () => {
|
||||
expect(accessTokenIsExpiring(makeJwt({ exp: Math.floor(Date.now() / 1000) - 1 }), -60_000)).toBe(true)
|
||||
})
|
||||
|
||||
test("returns false for opaque and malformed tokens", () => {
|
||||
expect(accessTokenIsExpiring("opaque-token-no-dots", 0)).toBe(false)
|
||||
expect(accessTokenIsExpiring("", 0)).toBe(false)
|
||||
expect(accessTokenIsExpiring(undefined, 0)).toBe(false)
|
||||
expect(accessTokenIsExpiring(makeJwt({ sub: "user-1" }), 0)).toBe(false)
|
||||
expect(accessTokenIsExpiring(makeJwt({ exp: "1234" }), 0)).toBe(false)
|
||||
expect(accessTokenIsExpiring("header.!!!not-valid-base64-or-json!!!.sig", 0)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("buildAuthorizeUrl", () => {
|
||||
const pkce = { verifier: "ver", challenge: "chal" }
|
||||
|
||||
test("includes required OAuth + PKCE + OIDC params", () => {
|
||||
const url = new URL(buildAuthorizeUrl(pkce, "state-abc", "nonce-xyz"))
|
||||
const params = url.searchParams
|
||||
|
||||
expect(url.origin + url.pathname).toBe("https://auth.x.ai/oauth2/authorize")
|
||||
expect(params.get("response_type")).toBe("code")
|
||||
expect(params.get("client_id")).toBe("b1a00492-073a-47ea-816f-4c329264a828")
|
||||
expect(params.get("redirect_uri")).toBe("http://127.0.0.1:56121/callback")
|
||||
expect(params.get("scope")).toBe("openid profile email offline_access grok-cli:access api:access")
|
||||
expect(params.get("code_challenge")).toBe("chal")
|
||||
expect(params.get("code_challenge_method")).toBe("S256")
|
||||
expect(params.get("state")).toBe("state-abc")
|
||||
expect(params.get("nonce")).toBe("nonce-xyz")
|
||||
expect(params.get("plan")).toBe("generic")
|
||||
expect(params.get("referrer")).toBe("opencode")
|
||||
})
|
||||
|
||||
test("supports endpoint override for local integration tests", () => {
|
||||
const url = new URL(buildAuthorizeUrl(pkce, "s", "n", { authorizeUrl: "http://127.0.0.1/oauth2/authorize" }))
|
||||
expect(url.origin + url.pathname).toBe("http://127.0.0.1/oauth2/authorize")
|
||||
})
|
||||
})
|
||||
|
||||
describe("escapeHtml", () => {
|
||||
test("escapes HTML metacharacters", () => {
|
||||
expect(escapeHtml(`</div><script>alert(1)</script><div class="x">`)).toBe(
|
||||
"</div><script>alert(1)</script><div class="x">",
|
||||
)
|
||||
expect(escapeHtml("a & b")).toBe("a & b")
|
||||
expect(escapeHtml("it's fine")).toBe("it's fine")
|
||||
expect(escapeHtml("invalid_grant")).toBe("invalid_grant")
|
||||
expect(escapeHtml("")).toBe("")
|
||||
expect(escapeHtml("&<")).toBe("&<")
|
||||
})
|
||||
})
|
||||
|
||||
describe("loader", () => {
|
||||
test("returns no options unless stored auth is OAuth and exposes methods in order", async () => {
|
||||
const hooks = await XaiAuthPlugin({} as any)
|
||||
expect(await hooks.auth!.loader!(async () => ({ type: "api", key: "sk-test" }), {} as any)).toEqual({})
|
||||
expect(
|
||||
await hooks.auth!.loader!(async () => ({ type: "wellknown", key: "k", token: "t" }) as any, {} as any),
|
||||
).toEqual({})
|
||||
expect(hooks.auth!.methods.map((m) => [m.type, m.label])).toEqual([
|
||||
["oauth", "xAI Grok OAuth (SuperGrok Subscription)"],
|
||||
["oauth", "xAI Grok OAuth (Headless / Remote / VPS)"],
|
||||
["api", "Manually enter API Key"],
|
||||
])
|
||||
})
|
||||
|
||||
test("replaces the dummy bearer, sets User-Agent, and preserves caller headers", async () => {
|
||||
const { input } = makeInput()
|
||||
const captured: Headers[] = []
|
||||
using server = makeServer((request) => {
|
||||
captured.push(request.headers)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const hooks = await XaiAuthPlugin(input)
|
||||
const opts = await hooks.auth!.loader!(
|
||||
async () => ({ type: "oauth", access: "live-token", refresh: "rt", expires: Date.now() + 3600_000 }),
|
||||
{} as any,
|
||||
)
|
||||
expect(opts.apiKey).toBe(OAUTH_DUMMY_KEY)
|
||||
expect(opts.baseURL).toBeUndefined()
|
||||
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), {
|
||||
headers: { Authorization: `Bearer ${OAUTH_DUMMY_KEY}`, "x-keep": "yes" },
|
||||
})
|
||||
|
||||
expect(captured[0].get("authorization")).toBe("Bearer live-token")
|
||||
expect(captured[0].get("x-keep")).toBe("yes")
|
||||
expect(captured[0].get("user-agent")).toMatch(/^opencode\//)
|
||||
})
|
||||
|
||||
test("does not mutate caller headers and supports HeadersInit shapes", async () => {
|
||||
const { input } = makeInput()
|
||||
const captured: Headers[] = []
|
||||
using server = makeServer((request) => {
|
||||
captured.push(request.headers)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input)
|
||||
).auth!.loader!(
|
||||
async () => ({ type: "oauth", access: "tok", refresh: "rt", expires: Date.now() + 3600_000 }),
|
||||
{} as any,
|
||||
)
|
||||
|
||||
const objHeaders: Record<string, string> = {
|
||||
Authorization: `Bearer ${OAUTH_DUMMY_KEY}`,
|
||||
"x-trace": "plain-object",
|
||||
}
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), { headers: objHeaders })
|
||||
expect(objHeaders).toEqual({ Authorization: `Bearer ${OAUTH_DUMMY_KEY}`, "x-trace": "plain-object" })
|
||||
|
||||
const arrayHeaders: [string, string][] = [["x-trace", "tuple-array"]]
|
||||
const arrayCopy = arrayHeaders.map(([key, value]) => [key, value] as [string, string])
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), { headers: arrayHeaders })
|
||||
expect(arrayHeaders).toEqual(arrayCopy)
|
||||
|
||||
const headersInstance = new Headers({ "x-trace": "headers-instance" })
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), { headers: headersInstance })
|
||||
expect(headersInstance.get("x-trace")).toBe("headers-instance")
|
||||
|
||||
expect(captured.map((headers) => headers.get("x-trace"))).toEqual([
|
||||
"plain-object",
|
||||
"tuple-array",
|
||||
"headers-instance",
|
||||
])
|
||||
for (const headers of captured) {
|
||||
expect(headers.get("authorization")).toBe("Bearer tok")
|
||||
expect(headers.get("user-agent")).toMatch(/^opencode\//)
|
||||
}
|
||||
})
|
||||
|
||||
test("preserves headers from Request input and lets init headers override them", async () => {
|
||||
const { input } = makeInput()
|
||||
const captured: Headers[] = []
|
||||
using server = makeServer((request) => {
|
||||
captured.push(request.headers)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input)
|
||||
).auth!.loader!(
|
||||
async () => ({ type: "oauth", access: "tok", refresh: "rt", expires: Date.now() + 3600_000 }),
|
||||
{} as any,
|
||||
)
|
||||
|
||||
await opts.fetch!(
|
||||
new Request(new URL("/chat/completions", server.url), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${OAUTH_DUMMY_KEY}`,
|
||||
"content-type": "application/json",
|
||||
"x-trace": "request",
|
||||
},
|
||||
}),
|
||||
{ headers: { "x-trace": "init", "x-extra": "yes" } },
|
||||
)
|
||||
|
||||
expect(captured[0].get("authorization")).toBe("Bearer tok")
|
||||
expect(captured[0].get("content-type")).toBe("application/json")
|
||||
expect(captured[0].get("x-trace")).toBe("init")
|
||||
expect(captured[0].get("x-extra")).toBe("yes")
|
||||
})
|
||||
|
||||
test("falls through to plain fetch when stored auth flips from oauth to api", async () => {
|
||||
const { input } = makeInput()
|
||||
const captured: Headers[] = []
|
||||
using server = makeServer((request) => {
|
||||
captured.push(request.headers)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
let firstCall = true
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input)
|
||||
).auth!.loader!(async () => {
|
||||
if (firstCall) {
|
||||
firstCall = false
|
||||
return { type: "oauth", access: "tok", refresh: "rt", expires: Date.now() + 3600_000 }
|
||||
}
|
||||
return { type: "api", key: "sk-new" }
|
||||
}, {} as any)
|
||||
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), {
|
||||
headers: { Authorization: "Bearer sk-from-aisdk", "x-keep": "v" },
|
||||
})
|
||||
expect(captured[0].get("authorization")).toBe("Bearer sk-from-aisdk")
|
||||
expect(captured[0].get("x-keep")).toBe("v")
|
||||
})
|
||||
|
||||
test("deduplicates concurrent refreshes within a loader instance", async () => {
|
||||
const { input, setCalls } = makeInput()
|
||||
let tokenRequests = 0
|
||||
const apiRequests: Headers[] = []
|
||||
using server = makeServer(async (request, url) => {
|
||||
if (url.pathname === "/oauth2/token") {
|
||||
tokenRequests++
|
||||
expect(await request.text()).toContain("refresh_token=rt-old")
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
return Response.json({ access_token: "new-access", refresh_token: "rt-new", expires_in: 3600 })
|
||||
}
|
||||
apiRequests.push(request.headers)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input, serverOptions(server))
|
||||
).auth!.loader!(async () => ({ type: "oauth" as const, access: "old", refresh: "rt-old", expires: 0 }), {} as any)
|
||||
|
||||
await Promise.all([
|
||||
opts.fetch!(new URL("/chat/completions", server.url), { headers: {} }),
|
||||
opts.fetch!(new URL("/chat/completions", server.url), { headers: {} }),
|
||||
])
|
||||
|
||||
expect(tokenRequests).toBe(1)
|
||||
expect(apiRequests.map((headers) => headers.get("authorization"))).toEqual([
|
||||
"Bearer new-access",
|
||||
"Bearer new-access",
|
||||
])
|
||||
expect(setCalls).toHaveLength(1)
|
||||
expect((setCalls[0].body as any).refresh).toBe("rt-new")
|
||||
})
|
||||
|
||||
test("does not share refresh single-flight across loader instances", async () => {
|
||||
const { input } = makeInput()
|
||||
const tokenRequests: string[] = []
|
||||
const apiRequests: string[] = []
|
||||
using server = makeServer(async (request, url) => {
|
||||
if (url.pathname === "/oauth2/token") {
|
||||
const refreshToken = new URLSearchParams(await request.text()).get("refresh_token")!
|
||||
tokenRequests.push(refreshToken)
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
return Response.json({
|
||||
access_token: `access-${refreshToken}`,
|
||||
refresh_token: `next-${refreshToken}`,
|
||||
expires_in: 3600,
|
||||
})
|
||||
}
|
||||
apiRequests.push(request.headers.get("authorization")!)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const hooks = await XaiAuthPlugin(input, serverOptions(server))
|
||||
const first = await hooks.auth!.loader!(
|
||||
async () => ({ type: "oauth", access: "old-a", refresh: "rt-a", expires: 0 }),
|
||||
{} as any,
|
||||
)
|
||||
const second = await hooks.auth!.loader!(
|
||||
async () => ({ type: "oauth", access: "old-b", refresh: "rt-b", expires: 0 }),
|
||||
{} as any,
|
||||
)
|
||||
|
||||
await Promise.all([
|
||||
first.fetch!(new URL("/chat/completions", server.url), { headers: {} }),
|
||||
second.fetch!(new URL("/chat/completions", server.url), { headers: {} }),
|
||||
])
|
||||
|
||||
expect(tokenRequests.sort()).toEqual(["rt-a", "rt-b"])
|
||||
expect(apiRequests.sort()).toEqual(["Bearer access-rt-a", "Bearer access-rt-b"])
|
||||
})
|
||||
|
||||
test("starts a new refresh after success and clears the refresh promise after failure", async () => {
|
||||
const { input } = makeInput()
|
||||
let tokenRequests = 0
|
||||
using server = makeServer((_, url) => {
|
||||
if (url.pathname === "/oauth2/token") {
|
||||
tokenRequests++
|
||||
if (tokenRequests === 2) return new Response("temporarily unavailable", { status: 503 })
|
||||
return Response.json({
|
||||
access_token: `new-${tokenRequests}`,
|
||||
refresh_token: `rt-${tokenRequests}`,
|
||||
expires_in: 3600,
|
||||
})
|
||||
}
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input, serverOptions(server))
|
||||
).auth!.loader!(async () => ({ type: "oauth", access: "old", refresh: "rt-old", expires: 0 }), {} as any)
|
||||
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), { headers: {} })
|
||||
await expect(opts.fetch!(new URL("/chat/completions", server.url), { headers: {} })).rejects.toThrow(
|
||||
/xAI token refresh failed \(503\)/,
|
||||
)
|
||||
await opts.fetch!(new URL("/chat/completions", server.url), { headers: {} })
|
||||
expect(tokenRequests).toBe(3)
|
||||
})
|
||||
|
||||
test("handles refresh response variants and persistence failure", async () => {
|
||||
const { input, setCalls } = makeInput({ failSet: true })
|
||||
const captured: Headers[] = []
|
||||
using server = makeServer((request, url) => {
|
||||
if (url.pathname === "/oauth2/token") return Response.json({ access_token: "new-access", expires_in: 3600 })
|
||||
captured.push(request.headers)
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input, serverOptions(server))
|
||||
).auth!.loader!(async () => ({ type: "oauth", access: "old", refresh: "rt-old", expires: 0 }), {} as any)
|
||||
|
||||
const resp = await opts.fetch!(new URL("/chat/completions", server.url), { headers: {} })
|
||||
expect(resp.status).toBe(200)
|
||||
expect(captured[0].get("authorization")).toBe("Bearer new-access")
|
||||
expect((setCalls[0].body as any).refresh).toBe("rt-old")
|
||||
})
|
||||
|
||||
test("refreshes based on stored expiry or JWT expiry and skips refresh when both are fresh", async () => {
|
||||
const { input, setCalls } = makeInput()
|
||||
let tokenRequests = 0
|
||||
using server = makeServer((_, url) => {
|
||||
if (url.pathname === "/oauth2/token") {
|
||||
tokenRequests++
|
||||
return Response.json({ access_token: "new-access", refresh_token: "rt-new", expires_in: 3600 })
|
||||
}
|
||||
return new Response("{}", { status: 200 })
|
||||
})
|
||||
const fresh = await (
|
||||
await XaiAuthPlugin(input, serverOptions(server))
|
||||
).auth!.loader!(
|
||||
async () => ({
|
||||
type: "oauth",
|
||||
access: makeJwt({ exp: Math.floor(Date.now() / 1000) + 24 * 3600 }),
|
||||
refresh: "rt",
|
||||
expires: Date.now() + 24 * 3600 * 1000,
|
||||
}),
|
||||
{} as any,
|
||||
)
|
||||
await fresh.fetch!(new URL("/chat/completions", server.url), { headers: {} })
|
||||
expect(tokenRequests).toBe(0)
|
||||
|
||||
const jwtExpiring = await (
|
||||
await XaiAuthPlugin(input, serverOptions(server))
|
||||
).auth!.loader!(
|
||||
async () => ({
|
||||
type: "oauth",
|
||||
access: makeJwt({ exp: Math.floor((Date.now() + 30_000) / 1000) }),
|
||||
refresh: "rt-old",
|
||||
expires: Date.now() + 24 * 3600 * 1000,
|
||||
}),
|
||||
{} as any,
|
||||
)
|
||||
const missingExpires = await (
|
||||
await XaiAuthPlugin(input, serverOptions(server))
|
||||
).auth!.loader!(async () => ({ type: "oauth", access: "opaque-token", refresh: "rt", expires: 0 }), {} as any)
|
||||
await jwtExpiring.fetch!(new URL("/chat/completions", server.url), { headers: {} })
|
||||
await missingExpires.fetch!(new URL("/chat/completions", server.url), { headers: {} })
|
||||
expect(tokenRequests).toBe(2)
|
||||
expect(setCalls).toHaveLength(2)
|
||||
})
|
||||
|
||||
test("network failure during refresh surfaces the underlying fetch error", async () => {
|
||||
const { input } = makeInput()
|
||||
const opts = await (
|
||||
await XaiAuthPlugin(input, { tokenUrl: "http://127.0.0.1:9/oauth2/token" })
|
||||
).auth!.loader!(async () => ({ type: "oauth", access: "old", refresh: "rt", expires: 0 }), {} as any)
|
||||
|
||||
await expect(opts.fetch!("https://api.x.ai/v1/chat/completions", { headers: {} })).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe("device code flow", () => {
|
||||
test("authorize advertises verification URL + user code and returns success on callback", async () => {
|
||||
using server = makeServer((_, url) => {
|
||||
if (url.pathname === "/oauth2/device/code") {
|
||||
return Response.json({
|
||||
device_code: "DEVICE-1",
|
||||
user_code: "ABCD-1234",
|
||||
verification_uri: "https://x.ai/device",
|
||||
verification_uri_complete: "https://x.ai/device?user_code=ABCD-1234",
|
||||
expires_in: 600,
|
||||
interval: 5,
|
||||
})
|
||||
}
|
||||
if (url.pathname === "/oauth2/token") {
|
||||
return Response.json({ access_token: "AT", refresh_token: "RT", expires_in: 3600 })
|
||||
}
|
||||
return new Response("unexpected request", { status: 500 })
|
||||
})
|
||||
const hooks = await XaiAuthPlugin({} as any, serverOptions(server))
|
||||
const headless = hooks.auth!.methods.find(
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> =>
|
||||
m.type === "oauth" && m.label === "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
)!
|
||||
const result = await headless.authorize!()
|
||||
|
||||
expect(result.method).toBe("auto")
|
||||
expect(result.url).toBe("https://x.ai/device?user_code=ABCD-1234")
|
||||
expect(result.instructions).toContain("https://x.ai/device")
|
||||
expect(result.instructions).toContain("ABCD-1234")
|
||||
expect(await (result as any).callback()).toMatchObject({ type: "success", refresh: "RT", access: "AT" })
|
||||
})
|
||||
|
||||
test("authorize falls back to verification_uri when verification_uri_complete is absent", async () => {
|
||||
using server = makeServer((_, url) => {
|
||||
if (url.pathname === "/oauth2/device/code") {
|
||||
return Response.json({
|
||||
device_code: "DEVICE-2",
|
||||
user_code: "WXYZ-9876",
|
||||
verification_uri: "https://x.ai/device",
|
||||
})
|
||||
}
|
||||
return new Response("unexpected request", { status: 500 })
|
||||
})
|
||||
const headless = (await XaiAuthPlugin({} as any, serverOptions(server))).auth!.methods.find(
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> =>
|
||||
m.type === "oauth" && m.label === "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
)!
|
||||
expect((await headless.authorize!()).url).toBe("https://x.ai/device")
|
||||
})
|
||||
|
||||
test("requestDeviceCode posts form body, validates fields, and surfaces endpoint errors", async () => {
|
||||
let capturedBody = ""
|
||||
using server = makeServer(async (request, url) => {
|
||||
if (url.pathname === "/missing") return Response.json({ device_code: "x" })
|
||||
if (url.pathname === "/error") return new Response("rate limited", { status: 429 })
|
||||
expect(request.method).toBe("POST")
|
||||
expect(request.headers.get("content-type")).toBe("application/x-www-form-urlencoded")
|
||||
expect(request.headers.get("accept")).toBe("application/json")
|
||||
expect(request.headers.get("user-agent")).toMatch(/^opencode\//)
|
||||
capturedBody = await request.text()
|
||||
return Response.json({ device_code: "DC", user_code: "UC", verification_uri: "https://x.ai/device" })
|
||||
})
|
||||
|
||||
await requestDeviceCode({ deviceAuthorizationUrl: new URL("/oauth2/device/code", server.url).toString() })
|
||||
const parsed = new URLSearchParams(capturedBody)
|
||||
expect(parsed.get("client_id")).toBe("b1a00492-073a-47ea-816f-4c329264a828")
|
||||
expect(parsed.get("scope")).toContain("offline_access")
|
||||
expect(parsed.get("scope")).toContain("grok-cli:access")
|
||||
expect(parsed.get("scope")).toContain("api:access")
|
||||
await expect(
|
||||
requestDeviceCode({ deviceAuthorizationUrl: new URL("/error", server.url).toString() }),
|
||||
).rejects.toThrow(/429.*rate limited/)
|
||||
await expect(
|
||||
requestDeviceCode({ deviceAuthorizationUrl: new URL("/missing", server.url).toString() }),
|
||||
).rejects.toThrow(/missing device_code/)
|
||||
})
|
||||
|
||||
test("pollDeviceCodeToken resolves on success and posts the device-code grant", async () => {
|
||||
let tokenCalls = 0
|
||||
using server = makeServer(async (request) => {
|
||||
tokenCalls++
|
||||
expect(request.headers.get("content-type")).toBe("application/x-www-form-urlencoded")
|
||||
const body = new URLSearchParams(await request.text())
|
||||
expect(body.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:device_code")
|
||||
expect(body.get("device_code")).toBe("DC-1")
|
||||
return Response.json({ access_token: "AT", refresh_token: "RT", expires_in: 3600 })
|
||||
})
|
||||
|
||||
const tokens = await pollDeviceCodeToken(
|
||||
{ device_code: "DC-1", user_code: "UC", verification_uri: "https://x.ai/device", interval: 1, expires_in: 600 },
|
||||
{ sleep: async () => {}, tokenUrl: new URL("/oauth2/token", server.url).toString() },
|
||||
)
|
||||
expect(tokens.access_token).toBe("AT")
|
||||
expect(tokens.refresh_token).toBe("RT")
|
||||
expect(tokenCalls).toBe(1)
|
||||
})
|
||||
|
||||
test("pollDeviceCodeToken honors authorization_pending and slow_down", async () => {
|
||||
let n = 0
|
||||
using server = makeServer(() => {
|
||||
n++
|
||||
if (n === 1) return Response.json({ error: "authorization_pending" }, { status: 400 })
|
||||
if (n === 2) return Response.json({ error: "slow_down" }, { status: 400 })
|
||||
return Response.json({ access_token: "AT", refresh_token: "RT", expires_in: 3600 })
|
||||
})
|
||||
const sleeps: number[] = []
|
||||
const tokens = await pollDeviceCodeToken(
|
||||
{ device_code: "DC", user_code: "UC", verification_uri: "https://x.ai/device", interval: 5, expires_in: 600 },
|
||||
{ sleep: async (ms) => void sleeps.push(ms), tokenUrl: new URL("/oauth2/token", server.url).toString() },
|
||||
)
|
||||
expect(tokens.access_token).toBe("AT")
|
||||
expect(n).toBe(3)
|
||||
expect(sleeps).toEqual([8_000, 13_000])
|
||||
})
|
||||
|
||||
test("pollDeviceCodeToken handles terminal errors and timeout", async () => {
|
||||
for (const [body, error] of [
|
||||
[{ error: "access_denied" }, /authorization was denied/],
|
||||
[{ error: "expired_token" }, /device code expired/],
|
||||
[{ error: "server_error", error_description: "oops" }, /500.*oops/],
|
||||
] as const) {
|
||||
using server = makeServer(() => Response.json(body, { status: 500 }))
|
||||
await expect(
|
||||
pollDeviceCodeToken(
|
||||
{
|
||||
device_code: "DC",
|
||||
user_code: "UC",
|
||||
verification_uri: "https://x.ai/device",
|
||||
interval: 1,
|
||||
expires_in: 600,
|
||||
},
|
||||
{ sleep: async () => {}, tokenUrl: new URL("/oauth2/token", server.url).toString() },
|
||||
),
|
||||
).rejects.toThrow(error)
|
||||
}
|
||||
|
||||
using pending = makeServer(() => Response.json({ error: "authorization_pending" }, { status: 400 }))
|
||||
let tick = 0
|
||||
await expect(
|
||||
pollDeviceCodeToken(
|
||||
{ device_code: "DC", user_code: "UC", verification_uri: "https://x.ai/device", interval: 1, expires_in: 1 },
|
||||
{
|
||||
sleep: async () => {},
|
||||
now: () => 1_000_000 + tick++ * 600,
|
||||
tokenUrl: new URL("/oauth2/token", pending.url).toString(),
|
||||
},
|
||||
),
|
||||
).rejects.toThrow(/timed out/)
|
||||
})
|
||||
|
||||
test("pollDeviceCodeToken normalizes bad interval and expires_in values", async () => {
|
||||
const badIntervals: Array<unknown> = [Number.NaN, "NaN", "garbage", -5, null, 0]
|
||||
for (const bad of badIntervals) {
|
||||
let n = 0
|
||||
using server = makeServer(() => {
|
||||
n++
|
||||
if (n === 1) return Response.json({ error: "authorization_pending" }, { status: 400 })
|
||||
return Response.json({ access_token: "AT", refresh_token: "RT", expires_in: 3600 })
|
||||
})
|
||||
const sleeps: number[] = []
|
||||
await pollDeviceCodeToken(
|
||||
{
|
||||
device_code: "DC",
|
||||
user_code: "UC",
|
||||
verification_uri: "https://x.ai/device",
|
||||
interval: bad as number,
|
||||
expires_in: 600,
|
||||
},
|
||||
{ sleep: async (ms) => void sleeps.push(ms), tokenUrl: new URL("/oauth2/token", server.url).toString() },
|
||||
)
|
||||
expect(sleeps[0]).toBe(8_000)
|
||||
}
|
||||
|
||||
for (const bad of [Number.NaN, "NaN", "garbage", -5, null, 0]) {
|
||||
using server = makeServer(() => Response.json({ access_token: "AT", refresh_token: "RT", expires_in: 3600 }))
|
||||
expect(
|
||||
(
|
||||
await pollDeviceCodeToken(
|
||||
{
|
||||
device_code: "DC",
|
||||
user_code: "UC",
|
||||
verification_uri: "https://x.ai/device",
|
||||
interval: 1,
|
||||
expires_in: bad as number,
|
||||
},
|
||||
{ sleep: async () => {}, tokenUrl: new URL("/oauth2/token", server.url).toString() },
|
||||
)
|
||||
).access_token,
|
||||
).toBe("AT")
|
||||
}
|
||||
})
|
||||
|
||||
test("device-code authorize callback returns failed when polling errors", async () => {
|
||||
using server = makeServer((_, url) => {
|
||||
if (url.pathname === "/oauth2/device/code") {
|
||||
return Response.json({
|
||||
device_code: "DC",
|
||||
user_code: "UC",
|
||||
verification_uri: "https://x.ai/device",
|
||||
interval: 0,
|
||||
expires_in: 600,
|
||||
})
|
||||
}
|
||||
return Response.json({ error: "access_denied" }, { status: 400 })
|
||||
})
|
||||
const headless = (await XaiAuthPlugin({} as any, serverOptions(server))).auth!.methods.find(
|
||||
(m): m is Extract<typeof m, { type: "oauth" }> =>
|
||||
m.type === "oauth" && m.label === "xAI Grok OAuth (Headless / Remote / VPS)",
|
||||
)!
|
||||
expect(await ((await headless.authorize!()) as any).callback()).toEqual({ type: "failed" })
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user