Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e99f505187 | |||
| 2e7390f29f |
@@ -63,7 +63,6 @@ const layer = Layer.effect(
|
||||
if (rule?.resource === "*" && rule.effect === "deny") continue
|
||||
registrations.set(name, registration)
|
||||
}
|
||||
if (registrations.size === 0) return {}
|
||||
const executeRule = rules.findLast((rule) => Wildcard.match("execute", rule.action))
|
||||
if (executeRule?.resource === "*" && executeRule.effect === "deny") return {}
|
||||
return {
|
||||
|
||||
@@ -6,7 +6,9 @@ import { Instructions } from "../instructions/index"
|
||||
import { CodeModeCatalog } from "./catalog"
|
||||
|
||||
// prettier-ignore
|
||||
const prompt = (hasMoreTools: boolean) => `The Code Mode tool catalog below is ${hasMoreTools ? "partial" : "complete"}.${hasMoreTools ? `
|
||||
const prompt = (hasMoreTools: boolean) => `The Code Mode tool catalog below is ${hasMoreTools ? "partial" : "complete"}.
|
||||
|
||||
Inside Code Mode, \`tools\` contains only the tools shown below${hasMoreTools ? " or returned by `search`" : ""}; surrounding top-level agent tools are not available and must not be called from the code.${hasMoreTools ? `
|
||||
|
||||
## Search
|
||||
|
||||
@@ -17,7 +19,8 @@ Use \`search\` to discover exact paths and signatures for additional tools:
|
||||
## Available tools`
|
||||
|
||||
export function render(catalog: CodeModeCatalog.Summary) {
|
||||
if (catalog.total === 0) return "No tools are currently available."
|
||||
if (catalog.total === 0)
|
||||
return "No Code Mode tools are currently available. Do not call `execute` until a later system update announces available tools."
|
||||
|
||||
const tools = catalog.namespaces.flatMap((namespace) => {
|
||||
const count = namespace.count === 1 ? "1 tool" : `${namespace.count} tools`
|
||||
@@ -36,12 +39,13 @@ ${tools.join("\n")}`
|
||||
}
|
||||
|
||||
export function update(previous: CodeModeCatalog.Summary, current: CodeModeCatalog.Summary) {
|
||||
const full = `The Code Mode tool catalog has changed. This catalog supersedes the previous Code Mode tool catalog.
|
||||
const replacement = `The Code Mode tool catalog has changed. This catalog supersedes the previous Code Mode tool catalog.
|
||||
|
||||
${render(current)}`
|
||||
if (current.total === 0) return replacement
|
||||
const previousComplete = previous.shown === previous.total
|
||||
const currentComplete = current.shown === current.total
|
||||
if (previousComplete !== currentComplete) return full
|
||||
if (previousComplete !== currentComplete) return replacement
|
||||
|
||||
const diff = Instructions.diffByKey(
|
||||
previous.namespaces.flatMap((namespace) => namespace.entries),
|
||||
@@ -52,7 +56,7 @@ ${render(current)}`
|
||||
const entriesChanged = diff.added.length > 0 || diff.removed.length > 0 || diff.changed.length > 0
|
||||
|
||||
if (!currentComplete) {
|
||||
if (entriesChanged) return full
|
||||
if (entriesChanged) return replacement
|
||||
const namespaces = Instructions.diffByKey(
|
||||
previous.namespaces,
|
||||
current.namespaces,
|
||||
@@ -60,7 +64,7 @@ ${render(current)}`
|
||||
(before, after) => before.count !== after.count,
|
||||
)
|
||||
const changed = namespaces.added.length > 0 || namespaces.removed.length > 0 || namespaces.changed.length > 0
|
||||
if (!changed) return full
|
||||
if (!changed) return replacement
|
||||
|
||||
const parts = ["The Code Mode tool catalog has changed."]
|
||||
if (namespaces.added.length > 0) {
|
||||
@@ -85,11 +89,11 @@ ${render(current)}`
|
||||
)
|
||||
}
|
||||
const delta = parts.join("\n\n")
|
||||
if (delta.length < full.length) return delta
|
||||
return full
|
||||
if (delta.length < replacement.length) return delta
|
||||
return replacement
|
||||
}
|
||||
|
||||
if (!entriesChanged) return full
|
||||
if (!entriesChanged) return replacement
|
||||
const parts = ["The Code Mode tool catalog has changed."]
|
||||
if (diff.added.length > 0) {
|
||||
parts.push(
|
||||
@@ -115,19 +119,19 @@ ${render(current)}`
|
||||
)
|
||||
}
|
||||
const delta = parts.join("\n\n")
|
||||
if (delta.length < full.length) return delta
|
||||
return full
|
||||
if (delta.length < replacement.length) return delta
|
||||
return replacement
|
||||
}
|
||||
|
||||
const key = Instructions.Key.make("core/codemode")
|
||||
const codec = Schema.toCodecJson(CodeModeCatalog.Summary)
|
||||
|
||||
export const make = (entries?: ReadonlyArray<CodeModeCatalog.Entry>): Instructions.Instructions => {
|
||||
const catalog = CodeModeCatalog.summarize(entries ?? [])
|
||||
const catalog = entries === undefined ? Instructions.removed : CodeModeCatalog.summarize(entries)
|
||||
return Instructions.make({
|
||||
key,
|
||||
codec,
|
||||
read: Effect.succeed(catalog.total === 0 ? Instructions.removed : catalog),
|
||||
read: Effect.succeed(catalog),
|
||||
render: {
|
||||
initial: render,
|
||||
changed: update,
|
||||
|
||||
@@ -36,8 +36,7 @@ type CollectedFiles = {
|
||||
const description = [
|
||||
"Run JavaScript to orchestrate tool calls and compose their results through `{ code }` in a confined Code Mode runtime.",
|
||||
"Imports, direct filesystem access, and timers are unavailable. Do not use `fetch`; all external access goes through `tools`.",
|
||||
"Within `{ code }`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by `search`. Inside `{ code }`, ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.",
|
||||
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
|
||||
'Call Code Mode tools through `tools` using only exact paths and signatures from the current catalog or `search`. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
|
||||
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
|
||||
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.all`.",
|
||||
].join("\n")
|
||||
|
||||
@@ -67,7 +67,9 @@ describe("CodeModeInstructions.render", () => {
|
||||
expect(instructions).toContain(` - ${lookup.signature} // Look up an order by ID`)
|
||||
expect(instructions).not.toContain("## Search")
|
||||
expect(instructions).toContain("The Code Mode tool catalog below is complete.")
|
||||
expect(instructions).not.toContain("surrounding top-level agent tools")
|
||||
expect(instructions).toContain(
|
||||
"`tools` contains only the tools shown below; surrounding top-level agent tools are not available and must not be called from the code.",
|
||||
)
|
||||
})
|
||||
|
||||
test("adds search guidance when the catalog exceeds the budget", () => {
|
||||
@@ -76,7 +78,9 @@ describe("CodeModeInstructions.render", () => {
|
||||
expect(partial).toContain("- orders (1 tool, none shown)")
|
||||
expect(partial).toContain("## Search")
|
||||
expect(partial).toContain("The Code Mode tool catalog below is partial.")
|
||||
expect(partial).not.toContain("surrounding top-level agent tools")
|
||||
expect(partial).toContain(
|
||||
"`tools` contains only the tools shown below or returned by `search`; surrounding top-level agent tools are not available and must not be called from the code.",
|
||||
)
|
||||
expect(partial).toContain("- search(input: {")
|
||||
expect(partial).toContain(" limit?: number,\n offset?: number,")
|
||||
expect(partial).not.toContain("tools.orders.lookup(input:")
|
||||
@@ -113,7 +117,9 @@ describe("CodeModeInstructions.render", () => {
|
||||
})
|
||||
|
||||
test("renders only the no-tools notice for an empty catalog", () => {
|
||||
expect(render([])).toBe("No tools are currently available.")
|
||||
expect(render([])).toBe(
|
||||
"No Code Mode tools are currently available. Do not call `execute` until a later system update announces available tools.",
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -123,8 +129,7 @@ describe("CodeModeInstructions.update", () => {
|
||||
test("renders additions, changes, and removals as a compact semantic delta", () => {
|
||||
const changed = { ...echo, signature: "tools.notes.echo(input: {\n text: string,\n}): Promise<string>" }
|
||||
const added = entry("notes.list", "List notes")
|
||||
const unchanged = Array.from({ length: 5 }, (_, index) => entry(`stable.tool${index}`, `Stable ${index}`))
|
||||
const text = update([echo, lookup, ...unchanged], [changed, added, ...unchanged])
|
||||
const text = update([echo, lookup], [changed, added])
|
||||
expect(text).toContain("The Code Mode tool catalog has changed.")
|
||||
expect(text).toContain(`New tools are available in addition to those previously listed:\n - ${added.signature}`)
|
||||
expect(text).toContain(
|
||||
|
||||
@@ -21,6 +21,25 @@ const lookup: CodeModeCatalog.Entry = {
|
||||
}
|
||||
|
||||
describe("CodeModeInstructions", () => {
|
||||
it.effect("instructs the model not to call execute while the catalog is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const initialized = yield* readInitial(CodeModeInstructions.make([]))
|
||||
expect(initialized.text).toBe(
|
||||
"No Code Mode tools are currently available. Do not call `execute` until a later system update announces available tools.",
|
||||
)
|
||||
|
||||
const added = yield* readUpdate(CodeModeInstructions.make([echo]), initialized)
|
||||
expect(added.text).toContain("New tools are available in addition to those previously listed:")
|
||||
expect(added.text).toContain(echo.signature)
|
||||
|
||||
expect(yield* readUpdate(CodeModeInstructions.make([]), { values: added.values })).toMatchObject({
|
||||
text:
|
||||
"The Code Mode tool catalog has changed. This catalog supersedes the previous Code Mode tool catalog.\n\n" +
|
||||
"No Code Mode tools are currently available. Do not call `execute` until a later system update announces available tools.",
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("renders the initial catalog, semantic deltas, and removal", () =>
|
||||
Effect.gen(function* () {
|
||||
const initialized = yield* readInitial(CodeModeInstructions.make([echo]))
|
||||
|
||||
@@ -32,6 +32,22 @@ export function waitForTool(
|
||||
})
|
||||
}
|
||||
|
||||
export function waitForCodeModeTool(
|
||||
registry: ToolRegistry.Interface,
|
||||
path: string,
|
||||
remaining = 1000,
|
||||
): Effect.Effect<ToolRegistry.ToolSet, Error> {
|
||||
return Effect.gen(function* () {
|
||||
const toolSet = yield* registry.snapshot()
|
||||
if (toolSet.codeModeCatalog?.some((tool) => tool.path === path)) return toolSet
|
||||
if (remaining === 0) {
|
||||
return yield* Effect.fail(new Error(`Timed out waiting for Code Mode tool: ${path}`))
|
||||
}
|
||||
yield* Effect.promise(() => Bun.sleep(1))
|
||||
return yield* waitForCodeModeTool(registry, path, remaining - 1)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a core tool plugin's tools against the real registry without booting the
|
||||
* full plugin host. Only the tool domain is live; focused tool tests exercise
|
||||
|
||||
@@ -33,7 +33,7 @@ import { Image } from "@opencode-ai/core/image"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { imagePassthrough } from "./lib/image"
|
||||
import { location } from "./fixture/location"
|
||||
import { executeTool, toolDefinitions, toolIdentity, waitForTool } from "./lib/tool"
|
||||
import { executeTool, toolDefinitions, toolIdentity, waitForCodeModeTool, waitForTool } from "./lib/tool"
|
||||
|
||||
let assertion: Deferred.Deferred<PermissionV2.AssertInput> | undefined
|
||||
let decision: Effect.Effect<void, PermissionV2.Error> = Effect.void
|
||||
@@ -802,10 +802,16 @@ test("serializes concurrent MCP lifecycle operations", async () => {
|
||||
it.effect("advertises MCP output schemas to Code Mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ToolRegistry.Service
|
||||
yield* waitForTool(registry, "execute")
|
||||
const definitions = yield* toolDefinitions(registry)
|
||||
const execute = definitions.find((tool) => tool.name === "execute")
|
||||
const toolSet = yield* waitForCodeModeTool(registry, "demo.search")
|
||||
const execute = toolSet.definitions.find((tool) => tool.name === "execute")
|
||||
|
||||
expect(toolSet.definitions.map((tool) => tool.name)).toEqual([
|
||||
"direct_fail",
|
||||
"direct_lookup",
|
||||
"direct_media",
|
||||
"execute",
|
||||
])
|
||||
expect(toolSet.codeModeCatalog?.find((tool) => tool.path === "demo.search")?.signature).toContain("ok: boolean")
|
||||
expect(execute?.description).not.toContain("tools.demo.search")
|
||||
}),
|
||||
)
|
||||
@@ -873,9 +879,9 @@ it.effect("waits for permission before calling an MCP tool", () =>
|
||||
const permission = yield* Deferred.make<void>()
|
||||
decision = Deferred.await(permission)
|
||||
const registry = yield* ToolRegistry.Service
|
||||
yield* waitForTool(registry, "execute")
|
||||
const toolSet = yield* waitForCodeModeTool(registry, "demo.search")
|
||||
|
||||
const fiber = yield* executeTool(registry, {
|
||||
const fiber = yield* toolSet.execute({
|
||||
sessionID: SessionV2.ID.make("ses_mcp_permission"),
|
||||
...toolIdentity,
|
||||
call: {
|
||||
@@ -912,9 +918,9 @@ it.effect("does not call MCP when permission is blocked", () =>
|
||||
assertion = yield* Deferred.make<PermissionV2.AssertInput>()
|
||||
decision = Effect.fail(new PermissionV2.BlockedError({ rules: [], permission: "demo_search", resources: ["*"] }))
|
||||
const registry = yield* ToolRegistry.Service
|
||||
yield* waitForTool(registry, "execute")
|
||||
const toolSet = yield* waitForCodeModeTool(registry, "demo.search")
|
||||
|
||||
const execution = yield* executeTool(registry, {
|
||||
const execution = yield* toolSet.execute({
|
||||
sessionID: SessionV2.ID.make("ses_mcp_blocked"),
|
||||
...toolIdentity,
|
||||
call: {
|
||||
|
||||
@@ -186,6 +186,7 @@ describe("SessionRunnerLLM recorded", () => {
|
||||
yield* agents.transform((draft) =>
|
||||
draft.update(AgentV2.ID.make("build"), (agent) => {
|
||||
agent.mode = "primary"
|
||||
agent.permissions.push({ action: "execute", resource: "*", effect: "deny" })
|
||||
}),
|
||||
)
|
||||
const pluginHost = host({
|
||||
|
||||
@@ -88,7 +88,7 @@ describe("ToolRegistry", () => {
|
||||
|
||||
expect(error).toBeInstanceOf(Tool.RegistrationError)
|
||||
expect(error.message).toBe('Invalid tool namespace: "slack..admin"')
|
||||
expect((yield* service.snapshot()).definitions).toEqual([])
|
||||
expect((yield* service.snapshot()).definitions.map((tool) => tool.name)).toEqual(["execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -102,7 +102,7 @@ describe("ToolRegistry", () => {
|
||||
.register({ "echo.tool": make(), echo_tool: make() }, { codemode: false })
|
||||
.pipe(Effect.flip)
|
||||
expect(collision.message).toBe("Duplicate normalized tool name: echo_tool")
|
||||
expect((yield* service.snapshot()).definitions).toEqual([])
|
||||
expect((yield* service.snapshot()).definitions.map((tool) => tool.name)).toEqual(["execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -117,7 +117,7 @@ describe("ToolRegistry", () => {
|
||||
.pipe(Effect.flip)
|
||||
|
||||
expect(error).toBeInstanceOf(Tool.RegistrationError)
|
||||
expect((yield* service.snapshot()).definitions).toEqual([])
|
||||
expect((yield* service.snapshot()).definitions.map((tool) => tool.name)).toEqual(["execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -148,6 +148,20 @@ describe("ToolRegistry", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("keeps execute available without Code Mode tools unless explicitly denied", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* ToolRegistry.Service
|
||||
|
||||
const available = yield* service.snapshot()
|
||||
expect(available.definitions.map((tool) => tool.name)).toEqual(["execute"])
|
||||
expect(available.codeModeCatalog).toEqual([])
|
||||
|
||||
const denied = yield* service.snapshot([{ action: "execute", resource: "*", effect: "deny" }])
|
||||
expect(denied.definitions).toEqual([])
|
||||
expect(denied.codeModeCatalog).toBeUndefined()
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("filters disabled tools with edit aliases and ordered wildcard precedence", () =>
|
||||
Effect.gen(function* () {
|
||||
const service = yield* ToolRegistry.Service
|
||||
@@ -156,7 +170,12 @@ describe("ToolRegistry", () => {
|
||||
const names = (permissions: PermissionV2.Ruleset) =>
|
||||
toolDefinitions(service, permissions).pipe(Effect.map((definitions) => definitions.map((tool) => tool.name)))
|
||||
|
||||
expect(yield* names([{ action: "question", resource: "*", effect: "deny" }])).toEqual(["bash", "edit", "write"])
|
||||
expect(yield* names([{ action: "question", resource: "*", effect: "deny" }])).toEqual([
|
||||
"bash",
|
||||
"edit",
|
||||
"write",
|
||||
"execute",
|
||||
])
|
||||
expect(
|
||||
yield* names([
|
||||
{ action: "*", resource: "*", effect: "deny" },
|
||||
@@ -169,7 +188,11 @@ describe("ToolRegistry", () => {
|
||||
{ action: "*", resource: "*", effect: "deny" },
|
||||
]),
|
||||
).toEqual([])
|
||||
expect(yield* names([{ action: "edit", resource: "*", effect: "deny" }])).toEqual(["bash", "question"])
|
||||
expect(yield* names([{ action: "edit", resource: "*", effect: "deny" }])).toEqual([
|
||||
"bash",
|
||||
"question",
|
||||
"execute",
|
||||
])
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -182,7 +205,7 @@ describe("ToolRegistry", () => {
|
||||
|
||||
expect(
|
||||
(yield* toolDefinitions(service, [{ action: "edit", resource: "*", effect: "deny" }])).map((tool) => tool.name),
|
||||
).toEqual(["first"])
|
||||
).toEqual(["first", "execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -191,9 +214,9 @@ describe("ToolRegistry", () => {
|
||||
const service = yield* ToolRegistry.Service
|
||||
const scope = yield* Scope.make()
|
||||
yield* service.register({ echo: make() }, { codemode: false }).pipe(Scope.provide(scope))
|
||||
expect((yield* toolDefinitions(service)).map((tool) => tool.name)).toEqual(["echo"])
|
||||
expect((yield* toolDefinitions(service)).map((tool) => tool.name)).toEqual(["echo", "execute"])
|
||||
yield* Scope.close(scope, Exit.void)
|
||||
expect(yield* toolDefinitions(service)).toEqual([])
|
||||
expect((yield* toolDefinitions(service)).map((tool) => tool.name)).toEqual(["execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -213,9 +236,9 @@ describe("ToolRegistry", () => {
|
||||
yield* Deferred.await(registered)
|
||||
yield* Fiber.interrupt(fiber)
|
||||
|
||||
expect((yield* toolDefinitions(service)).map((tool) => tool.name)).toEqual(["echo"])
|
||||
expect((yield* toolDefinitions(service)).map((tool) => tool.name)).toEqual(["echo", "execute"])
|
||||
yield* Scope.close(scope, Exit.void)
|
||||
expect(yield* toolDefinitions(service)).toEqual([])
|
||||
expect((yield* toolDefinitions(service)).map((tool) => tool.name)).toEqual(["execute"])
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -880,6 +880,46 @@ describe("SessionRunnerLLM", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("advertises execute and durable guidance for an empty Code Mode catalog", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* setup
|
||||
const empty = {
|
||||
catalog: [],
|
||||
tool: Tool.make({
|
||||
description: "Execute Code Mode",
|
||||
input: Schema.Struct({ code: Schema.String }),
|
||||
output: Schema.String,
|
||||
execute: () => Effect.succeed({ output: "unused" }),
|
||||
}),
|
||||
}
|
||||
codeModeMaterializations = [empty, empty, {}]
|
||||
yield* admit(session, "Continue without Code Mode tools")
|
||||
response = reply.stop()
|
||||
|
||||
yield* session.resume(sessionID)
|
||||
yield* admit(session, "Still no Code Mode tools")
|
||||
yield* session.resume(sessionID)
|
||||
yield* admit(session, "Code Mode denied")
|
||||
yield* session.resume(sessionID)
|
||||
|
||||
expect(requests).toHaveLength(3)
|
||||
expect(requests[0]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail", "execute"])
|
||||
expect(requests[0]?.system.some((part) => part.text.includes("Do not call `execute`"))).toBe(true)
|
||||
expect(requests[1]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail", "execute"])
|
||||
expect(requests[1]?.messages.filter((message) => message.role === "system")).toEqual([])
|
||||
expect(requests[2]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail"])
|
||||
expect(
|
||||
requests[2]?.messages.some(
|
||||
(message) =>
|
||||
message.role === "system" &&
|
||||
message.content.some(
|
||||
(part) => part.type === "text" && part.text.includes("Code Mode tools are no longer available"),
|
||||
),
|
||||
),
|
||||
).toBe(true)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("applies session context hooks without exposing unavailable tools", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* setup
|
||||
|
||||
@@ -137,10 +137,12 @@ describe("EditTool", () => {
|
||||
Effect.andThen(
|
||||
withTool(tmp.path, (registry) =>
|
||||
Effect.gen(function* () {
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["edit"])
|
||||
expect(yield* toolDefinitions(registry, [{ action: "edit", resource: "*", effect: "deny" }])).toEqual(
|
||||
[],
|
||||
)
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["edit", "execute"])
|
||||
expect(
|
||||
(yield* toolDefinitions(registry, [{ action: "edit", resource: "*", effect: "deny" }])).map(
|
||||
(tool) => tool.name,
|
||||
),
|
||||
).toEqual(["execute"])
|
||||
const settled = yield* executeTool(
|
||||
registry,
|
||||
call({ path: "hello.txt", oldString: "before", newString: "after" }),
|
||||
|
||||
@@ -19,8 +19,7 @@ test("execute describes invariant Code Mode behavior", () => {
|
||||
[
|
||||
"Run JavaScript to orchestrate tool calls and compose their results through `{ code }` in a confined Code Mode runtime.",
|
||||
"Imports, direct filesystem access, and timers are unavailable. Do not use `fetch`; all external access goes through `tools`.",
|
||||
"Within `{ code }`, the only callable tools are those explicitly listed in the Code Mode catalog instructions or returned by `search`. Inside `{ code }`, ignore tools shown outside the Code Mode catalog. They are not available in the Code Mode runtime.",
|
||||
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
|
||||
'Call Code Mode tools through `tools` using only exact paths and signatures from the current catalog or `search`. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
|
||||
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
|
||||
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.all`.",
|
||||
].join("\n"),
|
||||
|
||||
@@ -181,7 +181,7 @@ describe("PatchTool", () => {
|
||||
Effect.andThen(
|
||||
withTool(tmp.path, (registry) =>
|
||||
Effect.gen(function* () {
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["patch"])
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["patch", "execute"])
|
||||
const settled = yield* executeTool(
|
||||
registry,
|
||||
call(
|
||||
|
||||
@@ -97,7 +97,11 @@ describe("QuestionTool", () => {
|
||||
deny = true
|
||||
const registry = yield* ToolRegistry.Service
|
||||
|
||||
expect(yield* toolDefinitions(registry, [{ action: "question", resource: "*", effect: "deny" }])).toEqual([])
|
||||
expect(
|
||||
(yield* toolDefinitions(registry, [{ action: "question", resource: "*", effect: "deny" }])).map(
|
||||
(tool) => tool.name,
|
||||
),
|
||||
).toEqual(["execute"])
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
@@ -142,7 +146,7 @@ describe("QuestionTool", () => {
|
||||
},
|
||||
]
|
||||
|
||||
expect((yield* toolDefinitions(registry)).map((definition) => definition.name)).toEqual(["question"])
|
||||
expect((yield* toolDefinitions(registry)).map((definition) => definition.name)).toEqual(["question", "execute"])
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
|
||||
@@ -197,8 +197,12 @@ describe("ReadTool", () => {
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ToolRegistry.Service
|
||||
|
||||
expect(yield* toolDefinitions(registry)).toMatchObject([{ name: "read" }])
|
||||
expect(yield* toolDefinitions(registry, [{ action: "read", resource: "*", effect: "deny" }])).toEqual([])
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["read", "execute"])
|
||||
expect(
|
||||
(yield* toolDefinitions(registry, [{ action: "read", resource: "*", effect: "deny" }])).map(
|
||||
(tool) => tool.name,
|
||||
),
|
||||
).toEqual(["execute"])
|
||||
const execution = yield* executeTool(registry, {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
|
||||
@@ -92,7 +92,7 @@ describe("WebFetchTool registration", () => {
|
||||
const registry = yield* ToolRegistry.Service
|
||||
const url = "http://example.com/public"
|
||||
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["webfetch"])
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["webfetch", "execute"])
|
||||
expect(yield* executeTool(registry, call({ url, format: "text", timeout: 4 }))).toEqual({
|
||||
status: "completed",
|
||||
output: { url, contentType: "text/plain", format: "text", output: "hello" },
|
||||
|
||||
@@ -154,7 +154,7 @@ describe("WebSearchTool registration", () => {
|
||||
config = { provider: "exa", enableExa: false, enableParallel: false }
|
||||
const registry = yield* ToolRegistry.Service
|
||||
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["websearch"])
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["websearch", "execute"])
|
||||
expect(
|
||||
yield* executeTool(registry, {
|
||||
sessionID,
|
||||
|
||||
@@ -118,7 +118,7 @@ describe("WriteTool", () => {
|
||||
reset()
|
||||
return withTool(tmp.path, (registry) =>
|
||||
Effect.gen(function* () {
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["write"])
|
||||
expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["write", "execute"])
|
||||
const settled = yield* executeTool(registry, call({ path: "src/new.txt", content: "created" }))
|
||||
expect(settled).toEqual({
|
||||
status: "completed",
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { RGBA } from "@opentui/core"
|
||||
import { useTheme } from "../context/theme"
|
||||
import { Spinner } from "./spinner"
|
||||
|
||||
export function Reconnecting() {
|
||||
const { themeV2 } = useTheme().contextual("elevated")
|
||||
const { themeV2 } = useTheme()
|
||||
|
||||
return (
|
||||
<box
|
||||
@@ -13,23 +12,12 @@ export function Reconnecting() {
|
||||
right={0}
|
||||
bottom={0}
|
||||
left={0}
|
||||
backgroundColor={RGBA.fromInts(0, 0, 0, 150)}
|
||||
backgroundColor={themeV2.background.default}
|
||||
alignItems="center"
|
||||
justifyContent="center"
|
||||
>
|
||||
<box
|
||||
width={48}
|
||||
maxWidth="90%"
|
||||
flexDirection="column"
|
||||
backgroundColor={themeV2.background.default}
|
||||
paddingTop={1}
|
||||
paddingBottom={1}
|
||||
paddingLeft={2}
|
||||
paddingRight={2}
|
||||
gap={1}
|
||||
>
|
||||
<Spinner color={themeV2.text.default}>Restarting service...</Spinner>
|
||||
<text fg={themeV2.text.subdued}>Your session will resume automatically.</text>
|
||||
<box width={62} maxWidth="90%" flexDirection="column" alignItems="center" gap={1}>
|
||||
<Spinner color={themeV2.text.subdued}>Waiting for background service...</Spinner>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
|
||||
@@ -49,67 +49,6 @@ export const { use: useClient, provider: ClientProvider } = createSimpleContext(
|
||||
if (history.length > connectionHistoryLimit) history.shift()
|
||||
}
|
||||
|
||||
async function connect(signal: AbortSignal, attempt: number) {
|
||||
let connectedAt: number | undefined
|
||||
|
||||
// Bound the initial handshake and tie this request to the stream lifetime.
|
||||
const request = new AbortController()
|
||||
const cancel = () => request.abort(signal.reason)
|
||||
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout)
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
|
||||
try {
|
||||
// Open the event stream and validate its initial handshake.
|
||||
record(attempt === 0 ? "connecting" : "reconnecting", attempt)
|
||||
log.info("event stream connecting", { attempt })
|
||||
|
||||
const iterator = api.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
|
||||
const first = await iterator.next()
|
||||
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (first.done) {
|
||||
const error =
|
||||
request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected")
|
||||
return { error, connectedAt }
|
||||
}
|
||||
if (first.value.type !== "server.connected")
|
||||
return { error: new Error("Event stream did not start with server.connected"), connectedAt }
|
||||
|
||||
// Publish the connected state before forwarding live events.
|
||||
clearTimeout(timeout)
|
||||
record("connected", attempt)
|
||||
connectedAt = Date.now()
|
||||
log.info("event stream connected")
|
||||
events.emit(first.value.type, first.value)
|
||||
setConnection({ status: "connected", attempt: 0, error: undefined })
|
||||
|
||||
// Forward events until the stream closes or this connection is cancelled.
|
||||
while (!signal.aborted) {
|
||||
const event = await iterator.next()
|
||||
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (event.done) return { error: new Error("Event stream disconnected"), connectedAt }
|
||||
|
||||
if ("durable" in event.value)
|
||||
log.debug("event", {
|
||||
type: event.value.type,
|
||||
aggregateID: event.value.durable.aggregateID,
|
||||
seq: event.value.durable.seq,
|
||||
})
|
||||
|
||||
events.emit(event.value.type, event.value)
|
||||
}
|
||||
|
||||
return { error: undefined, connectedAt }
|
||||
} catch (error) {
|
||||
return { error, connectedAt }
|
||||
} finally {
|
||||
request.abort()
|
||||
clearTimeout(timeout)
|
||||
signal.removeEventListener("abort", cancel)
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
stream?.abort()
|
||||
const controller = new AbortController()
|
||||
@@ -117,11 +56,53 @@ export const { use: useClient, provider: ClientProvider } = createSimpleContext(
|
||||
void (async () => {
|
||||
let attempt = 0
|
||||
while (!abort.signal.aborted && !controller.signal.aborted) {
|
||||
const result = await connect(controller.signal, attempt)
|
||||
let connectedAt: number | undefined
|
||||
const request = new AbortController()
|
||||
const cancel = () => request.abort(controller.signal.reason)
|
||||
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout)
|
||||
controller.signal.addEventListener("abort", cancel, { once: true })
|
||||
const error = await (async () => {
|
||||
record(attempt === 0 ? "connecting" : "reconnecting", attempt)
|
||||
log.info("event stream connecting", { attempt })
|
||||
const iterator = api.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
|
||||
const first = await iterator.next()
|
||||
if (abort.signal.aborted || controller.signal.aborted) return undefined
|
||||
if (first.done)
|
||||
return request.signal.reason instanceof Error
|
||||
? request.signal.reason
|
||||
: new Error("Event stream disconnected")
|
||||
if (first.value.type !== "server.connected")
|
||||
return new Error("Event stream did not start with server.connected")
|
||||
clearTimeout(timeout)
|
||||
record("connected", attempt)
|
||||
connectedAt = Date.now()
|
||||
log.info("event stream connected")
|
||||
events.emit(first.value.type, first.value)
|
||||
setConnection({ status: "connected", attempt: 0, error: undefined })
|
||||
while (!abort.signal.aborted && !controller.signal.aborted) {
|
||||
const event = await iterator.next()
|
||||
if (abort.signal.aborted || controller.signal.aborted) return undefined
|
||||
if (event.done) return new Error("Event stream disconnected")
|
||||
if ("durable" in event.value)
|
||||
log.debug("event", {
|
||||
type: event.value.type,
|
||||
aggregateID: event.value.durable.aggregateID,
|
||||
seq: event.value.durable.seq,
|
||||
})
|
||||
events.emit(event.value.type, event.value)
|
||||
}
|
||||
return undefined
|
||||
})()
|
||||
.catch((error) => error)
|
||||
.finally(() => {
|
||||
request.abort()
|
||||
clearTimeout(timeout)
|
||||
controller.signal.removeEventListener("abort", cancel)
|
||||
})
|
||||
if (abort.signal.aborted || controller.signal.aborted) return
|
||||
if (result.connectedAt !== undefined && Date.now() - result.connectedAt >= 1_000) attempt = 0
|
||||
if (connectedAt !== undefined && Date.now() - connectedAt >= 1_000) attempt = 0
|
||||
attempt += 1
|
||||
const message = errorMessage(result.error)
|
||||
const message = errorMessage(error)
|
||||
record("disconnected", attempt, message)
|
||||
log.info("event stream disconnected", {
|
||||
attempt,
|
||||
|
||||
@@ -1,634 +0,0 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { afterAll, describe, expect, test } from "bun:test"
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "@opencode-ai/client"
|
||||
import { testRender } from "@opentui/solid"
|
||||
import { onMount } from "solid-js"
|
||||
import type { LogLevel, LogSink } from "../../../src/context/log"
|
||||
import { createApi, createFetch } from "../../fixture/tui-client"
|
||||
|
||||
const packageRoot = process.env.OPENCODE_TUI_ROOT
|
||||
const contextModule = packageRoot
|
||||
? await import(`${packageRoot}/src/context/client.tsx`)
|
||||
: await import("../../../src/context/client")
|
||||
const environmentModule = packageRoot
|
||||
? await import(`${packageRoot}/test/fixture/tui-environment.tsx`)
|
||||
: await import("../../fixture/tui-environment")
|
||||
const { ClientProvider, useClient } = contextModule as typeof import("../../../src/context/client")
|
||||
const { TestTuiContexts } = environmentModule as typeof import("../../fixture/tui-environment")
|
||||
|
||||
type Client = ReturnType<typeof useClient>
|
||||
type Service = {
|
||||
reconnect: (signal: AbortSignal) => Promise<{ api: OpenCodeClient }>
|
||||
restart: () => Promise<void>
|
||||
}
|
||||
type Observation = {
|
||||
scenario: string
|
||||
value: unknown
|
||||
}
|
||||
|
||||
const observations: Observation[] = []
|
||||
const connected = { id: "evt_connected", type: "server.connected", data: {} } as OpenCodeEvent
|
||||
|
||||
afterAll(async () => {
|
||||
const output = process.env.CLIENT_BEHAVIOR_OUTPUT
|
||||
if (output) await Bun.write(output, `${JSON.stringify(observations, null, 2)}\n`)
|
||||
})
|
||||
|
||||
function observe(scenario: string, value: unknown) {
|
||||
observations.push({ scenario, value })
|
||||
}
|
||||
|
||||
function normalizeError(error: unknown) {
|
||||
if (error instanceof Error) return `${error.name}:${error.message}`
|
||||
return String(error)
|
||||
}
|
||||
|
||||
function history(client: Client) {
|
||||
return client.connection.internal.history().map((event) => ({
|
||||
status: event.data.status,
|
||||
attempt: event.data.attempt,
|
||||
error: event.data.error,
|
||||
}))
|
||||
}
|
||||
|
||||
async function waitFor(check: () => boolean, timeout = 3_000) {
|
||||
const started = Date.now()
|
||||
while (!check()) {
|
||||
if (Date.now() - started > timeout) throw new Error("timed out waiting for condition")
|
||||
await Bun.sleep(5)
|
||||
}
|
||||
}
|
||||
|
||||
function event(type: "vcs" | "update" | "rename", suffix: string): OpenCodeEvent {
|
||||
if (type === "vcs") {
|
||||
return {
|
||||
id: `evt_vcs_${suffix}`,
|
||||
created: 1,
|
||||
type: "vcs.branch.updated",
|
||||
location: { directory: "/tmp/project" },
|
||||
data: { branch: suffix },
|
||||
}
|
||||
}
|
||||
if (type === "update") {
|
||||
return {
|
||||
id: `evt_update_${suffix}`,
|
||||
created: 2,
|
||||
type: "installation.update-available",
|
||||
data: { version: suffix },
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: `evt_rename_${suffix}`,
|
||||
created: 3,
|
||||
type: "session.renamed",
|
||||
durable: { aggregateID: "ses_test", seq: 1, version: 1 },
|
||||
location: { directory: "/tmp/project" },
|
||||
data: { sessionID: "ses_test", title: suffix },
|
||||
}
|
||||
}
|
||||
|
||||
function createStream(options?: { first?: OpenCodeEvent; closeBeforeHandshake?: boolean }) {
|
||||
const encoder = new TextEncoder()
|
||||
const controllers = new Set<ReadableStreamDefaultController<Uint8Array>>()
|
||||
const requests: Request[] = []
|
||||
const aborts: string[] = []
|
||||
let cancellations = 0
|
||||
|
||||
function response(request: Request) {
|
||||
requests.push(request)
|
||||
request.signal.addEventListener("abort", () => aborts.push(normalizeError(request.signal.reason)), { once: true })
|
||||
|
||||
let current: ReadableStreamDefaultController<Uint8Array> | undefined
|
||||
return new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
current = controller
|
||||
controllers.add(controller)
|
||||
if (options?.closeBeforeHandshake) {
|
||||
controllers.delete(controller)
|
||||
controller.close()
|
||||
return
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(options?.first ?? connected)}\n\n`))
|
||||
},
|
||||
cancel() {
|
||||
cancellations += 1
|
||||
if (current) controllers.delete(current)
|
||||
},
|
||||
}),
|
||||
{ headers: { "content-type": "text/event-stream" } },
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
response,
|
||||
emit(value: OpenCodeEvent) {
|
||||
const chunk = encoder.encode(`data: ${JSON.stringify(value)}\n\n`)
|
||||
for (const controller of controllers) controller.enqueue(chunk)
|
||||
},
|
||||
raw(value: string) {
|
||||
const chunk = encoder.encode(value)
|
||||
for (const controller of controllers) controller.enqueue(chunk)
|
||||
},
|
||||
close() {
|
||||
for (const controller of [...controllers]) {
|
||||
controllers.delete(controller)
|
||||
controller.close()
|
||||
}
|
||||
},
|
||||
fail(message: string) {
|
||||
for (const controller of [...controllers]) {
|
||||
controllers.delete(controller)
|
||||
controller.error(new Error(message))
|
||||
}
|
||||
},
|
||||
snapshot() {
|
||||
return {
|
||||
requests: requests.length,
|
||||
requestAborted: requests.map((request) => request.signal.aborted),
|
||||
aborts,
|
||||
cancellations,
|
||||
active: controllers.size,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function apiFor(stream: ReturnType<typeof createStream>) {
|
||||
return createApi(
|
||||
createFetch((url, request) => {
|
||||
if (url.pathname === "/api/event") return stream.response(request)
|
||||
}).fetch,
|
||||
)
|
||||
}
|
||||
|
||||
async function mount(input: {
|
||||
api: OpenCodeClient
|
||||
service?: Service
|
||||
throwOn?: OpenCodeEvent["type"]
|
||||
}) {
|
||||
const seen: Array<{ type: string; status: string }> = []
|
||||
const typed: string[] = []
|
||||
const logs: Array<{ level: LogLevel; message: string; tags: Record<string, unknown> }> = []
|
||||
let initialStatus = ""
|
||||
let client!: Client
|
||||
let ready!: () => void
|
||||
const mounted = new Promise<void>((resolve) => {
|
||||
ready = resolve
|
||||
})
|
||||
const log: LogSink = (level, message, tags) => {
|
||||
logs.push({ level, message, tags: { ...tags } })
|
||||
}
|
||||
|
||||
const app = await testRender(() => (
|
||||
<TestTuiContexts log={log}>
|
||||
<ClientProvider api={input.api} service={input.service}>
|
||||
<Probe
|
||||
onReady={(value) => {
|
||||
client = value
|
||||
initialStatus = value.connection.status()
|
||||
ready()
|
||||
}}
|
||||
onEvent={(value) => {
|
||||
seen.push({ type: value.type, status: client.connection.status() })
|
||||
if (value.type === input.throwOn) throw new Error(`listener failed for ${value.type}`)
|
||||
}}
|
||||
onBranch={(branch) => typed.push(branch)}
|
||||
/>
|
||||
</ClientProvider>
|
||||
</TestTuiContexts>
|
||||
))
|
||||
await mounted
|
||||
|
||||
return { app, client, initialStatus, seen, typed, logs }
|
||||
}
|
||||
|
||||
function Probe(props: {
|
||||
onReady: (client: Client) => void
|
||||
onEvent: (event: OpenCodeEvent) => void
|
||||
onBranch: (branch: string) => void
|
||||
}) {
|
||||
const client = useClient()
|
||||
onMount(() => {
|
||||
client.event.listen(({ details }) => props.onEvent(details))
|
||||
client.event.on("vcs.branch.updated", (value) => props.onBranch(value.data.branch ?? ""))
|
||||
props.onReady(client)
|
||||
})
|
||||
return <box />
|
||||
}
|
||||
|
||||
describe("ClientProvider connection characterization", () => {
|
||||
test("records handshake ordering, event delivery, logging, and active-stream cleanup", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.emit(event("vcs", "main"))
|
||||
stream.emit(event("rename", "renamed"))
|
||||
stream.emit(event("update", "2.0.0"))
|
||||
await waitFor(() => setup.seen.length === 4)
|
||||
|
||||
observe("healthy.connected", {
|
||||
initialStatus: setup.initialStatus,
|
||||
finalStatus: setup.client.connection.status(),
|
||||
seen: setup.seen,
|
||||
typed: setup.typed,
|
||||
logs: setup.logs,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
await waitFor(() => stream.snapshot().requestAborted[0] === true)
|
||||
await Bun.sleep(20)
|
||||
|
||||
observe("healthy.cleanup", {
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
expect(setup.seen.map((item) => item.type)).toEqual([
|
||||
"server.connected",
|
||||
"vcs.branch.updated",
|
||||
"session.renamed",
|
||||
"installation.update-available",
|
||||
])
|
||||
expect(setup.seen.map((item) => item.status)).toEqual(["connecting", "connected", "connected", "connected"])
|
||||
expect(setup.logs.filter((item) => item.message === "event")).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("records an invalid first event", async () => {
|
||||
const stream = createStream({ first: event("vcs", "invalid-handshake") })
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
observe("handshake.invalid", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("Event stream did not start with server.connected")
|
||||
})
|
||||
|
||||
test("records EOF before the handshake", async () => {
|
||||
const stream = createStream({ closeBeforeHandshake: true })
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
observe("handshake.eof", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("Event stream disconnected")
|
||||
})
|
||||
|
||||
test("records a fetch failure before the handshake", async () => {
|
||||
const calls = createFetch((url) => {
|
||||
if (url.pathname === "/api/event") throw new Error("network unavailable")
|
||||
return undefined
|
||||
})
|
||||
const setup = await mount({ api: createApi(calls.fetch) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
observe("handshake.fetch-error", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
logs: setup.logs,
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("Transport")
|
||||
})
|
||||
|
||||
test("records the initial connection timeout and request cancellation", async () => {
|
||||
const requests: Request[] = []
|
||||
const calls = createFetch((url, request) => {
|
||||
if (url.pathname !== "/api/event") return
|
||||
requests.push(request)
|
||||
return new Promise<Response>((_, reject) => {
|
||||
request.signal.addEventListener("abort", () => reject(request.signal.reason), { once: true })
|
||||
})
|
||||
})
|
||||
const setup = await mount({ api: createApi(calls.fetch) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting", 3_000)
|
||||
observe("handshake.timeout", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
requestCount: requests.length,
|
||||
requestAborted: requests.map((request) => request.signal.aborted),
|
||||
abortReasons: requests.map((request) => normalizeError(request.signal.reason)),
|
||||
history: history(setup.client),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("Transport")
|
||||
})
|
||||
|
||||
test("records static transport reconnection after a connected stream closes", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.close()
|
||||
await waitFor(() => stream.snapshot().requests === 2, 2_000)
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
|
||||
observe("reconnect.static", {
|
||||
status: setup.client.connection.status(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
logs: setup.logs.filter((item) => item.message !== "event"),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.seen.map((item) => item.type)).toEqual(["server.connected", "server.connected"])
|
||||
})
|
||||
|
||||
test("records immediate managed-service replacement", async () => {
|
||||
const initial = createStream()
|
||||
const replacement = createStream()
|
||||
const replacementApi = apiFor(replacement)
|
||||
const reconnectSignals: boolean[] = []
|
||||
const service: Service = {
|
||||
reconnect(signal) {
|
||||
reconnectSignals.push(signal.aborted)
|
||||
return Promise.resolve({ api: replacementApi })
|
||||
},
|
||||
restart: () => Promise.resolve(),
|
||||
}
|
||||
const setup = await mount({ api: apiFor(initial), service })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
initial.close()
|
||||
await waitFor(() => replacement.snapshot().requests === 1)
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
replacement.emit(event("vcs", "replacement"))
|
||||
await waitFor(() => setup.typed.includes("replacement"))
|
||||
|
||||
observe("reconnect.managed-replacement", {
|
||||
status: setup.client.connection.status(),
|
||||
apiReplaced: setup.client.api === replacementApi,
|
||||
reconnectSignals,
|
||||
seen: setup.seen,
|
||||
typed: setup.typed,
|
||||
history: history(setup.client),
|
||||
initial: initial.snapshot(),
|
||||
replacement: replacement.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.api).toBe(replacementApi)
|
||||
})
|
||||
|
||||
test("records managed-service resolution failure and delayed retry", async () => {
|
||||
const stream = createStream()
|
||||
let reconnects = 0
|
||||
const service: Service = {
|
||||
reconnect() {
|
||||
reconnects += 1
|
||||
return Promise.reject(new Error("service unavailable"))
|
||||
},
|
||||
restart: () => Promise.resolve(),
|
||||
}
|
||||
const setup = await mount({ api: apiFor(stream), service })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.close()
|
||||
await waitFor(() => stream.snapshot().requests === 2, 2_000)
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
|
||||
observe("reconnect.managed-failure", {
|
||||
reconnects,
|
||||
status: setup.client.connection.status(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
resolutionLogs: setup.logs.filter((item) => item.message === "server resolution failed"),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(reconnects).toBe(1)
|
||||
})
|
||||
|
||||
test("records cleanup while the initial fetch is pending", async () => {
|
||||
const requests: Request[] = []
|
||||
const aborts: string[] = []
|
||||
const calls = createFetch((url, request) => {
|
||||
if (url.pathname !== "/api/event") return
|
||||
requests.push(request)
|
||||
return new Promise<Response>((_, reject) => {
|
||||
request.signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
aborts.push(normalizeError(request.signal.reason))
|
||||
reject(request.signal.reason)
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
})
|
||||
})
|
||||
const setup = await mount({ api: createApi(calls.fetch) })
|
||||
|
||||
await waitFor(() => requests.length === 1)
|
||||
setup.app.renderer.destroy()
|
||||
await waitFor(() => requests[0].signal.aborted)
|
||||
await Bun.sleep(20)
|
||||
|
||||
observe("cleanup.pending-handshake", {
|
||||
status: setup.client.connection.status(),
|
||||
requestAborted: requests[0].signal.aborted,
|
||||
aborts,
|
||||
history: history(setup.client),
|
||||
logs: setup.logs,
|
||||
})
|
||||
|
||||
expect(history(setup.client).map((item) => item.status)).toEqual(["connecting"])
|
||||
})
|
||||
|
||||
test("records an event listener failure as a connection failure", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream), throwOn: "vcs.branch.updated" })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.emit(event("vcs", "throws"))
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
|
||||
observe("listener.failure", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
typed: setup.typed,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("listener failed for vcs.branch.updated")
|
||||
})
|
||||
|
||||
test("records stream reader failure after connection", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.fail("reader exploded")
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
|
||||
observe("stream.reader-failure", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("Transport")
|
||||
})
|
||||
|
||||
test("records malformed SSE data after connection", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.raw("data: not-json\n\n")
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
|
||||
observe("stream.malformed-data", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(setup.client.connection.error()).toBe("MalformedResponse")
|
||||
})
|
||||
|
||||
test("records a server.connected listener failure before connected state publication", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream), throwOn: "server.connected" })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
observe("listener.connected-failure", {
|
||||
status: setup.client.connection.status(),
|
||||
error: setup.client.connection.error(),
|
||||
seen: setup.seen,
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(history(setup.client).map((item) => item.status)).toEqual(["connecting", "connected", "disconnected"])
|
||||
})
|
||||
|
||||
test("records cleanup during static reconnect backoff", async () => {
|
||||
const stream = createStream()
|
||||
const setup = await mount({ api: apiFor(stream) })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.close()
|
||||
await waitFor(() => setup.client.connection.status() === "reconnecting")
|
||||
setup.app.renderer.destroy()
|
||||
await Bun.sleep(1_050)
|
||||
|
||||
observe("cleanup.reconnect-backoff", {
|
||||
status: setup.client.connection.status(),
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
})
|
||||
|
||||
expect(stream.snapshot().requests).toBe(1)
|
||||
})
|
||||
|
||||
test("records cleanup during managed-service resolution", async () => {
|
||||
const stream = createStream()
|
||||
let resolutionStarted = false
|
||||
let resolutionAborted = false
|
||||
const service: Service = {
|
||||
reconnect(signal) {
|
||||
resolutionStarted = true
|
||||
return new Promise((_, reject) => {
|
||||
signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
resolutionAborted = true
|
||||
reject(signal.reason)
|
||||
},
|
||||
{ once: true },
|
||||
)
|
||||
})
|
||||
},
|
||||
restart: () => Promise.resolve(),
|
||||
}
|
||||
const setup = await mount({ api: apiFor(stream), service })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
stream.close()
|
||||
await waitFor(() => resolutionStarted)
|
||||
setup.app.renderer.destroy()
|
||||
await waitFor(() => resolutionAborted)
|
||||
await Bun.sleep(20)
|
||||
|
||||
observe("cleanup.service-resolution", {
|
||||
resolutionStarted,
|
||||
resolutionAborted,
|
||||
status: setup.client.connection.status(),
|
||||
history: history(setup.client),
|
||||
stream: stream.snapshot(),
|
||||
logs: setup.logs,
|
||||
})
|
||||
|
||||
expect(resolutionAborted).toBe(true)
|
||||
})
|
||||
|
||||
test("records attempt reset after a stable connection", async () => {
|
||||
const streams = [createStream(), createStream(), createStream()]
|
||||
const apis = streams.map(apiFor)
|
||||
let reconnects = 0
|
||||
const service: Service = {
|
||||
reconnect() {
|
||||
const api = apis[Math.min(reconnects + 1, apis.length - 1)]
|
||||
reconnects += 1
|
||||
return Promise.resolve({ api })
|
||||
},
|
||||
restart: () => Promise.resolve(),
|
||||
}
|
||||
const setup = await mount({ api: apis[0], service })
|
||||
|
||||
await waitFor(() => setup.client.connection.status() === "connected")
|
||||
streams[0].close()
|
||||
await waitFor(() => streams[1].snapshot().requests === 1)
|
||||
streams[1].close()
|
||||
await waitFor(() => streams[2].snapshot().requests === 1)
|
||||
await Bun.sleep(1_050)
|
||||
streams[2].close()
|
||||
await waitFor(() => reconnects === 3)
|
||||
|
||||
observe("reconnect.stable-reset", {
|
||||
reconnects,
|
||||
status: setup.client.connection.status(),
|
||||
history: history(setup.client),
|
||||
streams: streams.map((stream) => stream.snapshot()),
|
||||
})
|
||||
|
||||
setup.app.renderer.destroy()
|
||||
expect(history(setup.client).filter((item) => item.status === "disconnected").map((item) => item.attempt)).toEqual([
|
||||
1, 2, 1,
|
||||
])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user