Compare commits

..

23 Commits

Author SHA1 Message Date
Shoubhit Dash a69f0ef2f8 refactor(ai): restore inline compaction beta handling 2026-08-31 20:01:57 +05:30
Shoubhit Dash 0934b9e01d refactor(ai): centralize anthropic beta selection 2026-08-31 19:52:15 +05:30
Shoubhit Dash 716393cdfa refactor(ai): separate conversation and generation lowering 2026-08-31 19:50:39 +05:30
Shoubhit Dash 48aedea579 refactor(ai): simplify response fragment guards 2026-08-31 19:30:04 +05:30
Shoubhit Dash 96c0f0d8c3 fix(ai): enforce exclusive checkpoint representations 2026-08-31 19:29:23 +05:30
Shoubhit Dash 4b7d49c9a4 fix(ai): preserve compacted image detail on replay 2026-08-31 19:27:34 +05:30
Shoubhit Dash 0e1081b0a5 fix(ai): apply cache policy to bedrock messages 2026-08-31 19:26:21 +05:30
Shoubhit Dash ce96bbe8a7 refactor(ai): share request preparation across operations 2026-08-31 19:25:28 +05:30
Shoubhit Dash 027f0e7cc9 fix(ai): reject order-unsafe checkpoint recovery 2026-08-31 19:23:58 +05:30
Shoubhit Dash 0a442fa2f8 chore: merge v2 into provider-compaction 2026-08-31 19:08:10 +05:30
Shoubhit Dash 59d1ab783c refactor(ai): make compaction conversion synchronous 2026-08-31 17:29:38 +05:30
Shoubhit Dash 6b4426bbd3 docs(ai): describe typed compaction history 2026-08-31 17:19:57 +05:30
Shoubhit Dash 1b9f762ea5 refactor(ai): model compaction as typed conversation parts 2026-08-31 17:19:45 +05:30
Shoubhit Dash c8b4963d98 refactor(ai): simplify compaction control flow 2026-08-31 16:24:01 +05:30
Shoubhit Dash 14a90331bc docs(ai): explain provider compaction and replay ownership 2026-08-31 16:11:38 +05:30
Shoubhit Dash cd2880075a test(ai): cover compaction across http and websocket flows 2026-08-31 16:11:17 +05:30
Shoubhit Dash af22c16249 fix(ai): validate compaction boundaries and incomplete blocks 2026-08-31 16:09:00 +05:30
Shoubhit Dash bc4db825a4 fix(core): reject unsupported compaction replay in ai sdk routes 2026-08-31 16:08:32 +05:30
Shoubhit Dash 4f0ba4f06e feat(ai): add bedrock messages route for claude compaction 2026-08-31 16:02:30 +05:30
Shoubhit Dash 8dd92e2d95 feat(ai): add explicit responses compaction calls 2026-08-31 15:58:29 +05:30
Shoubhit Dash cb5a6c7db4 feat(ai): support anthropic compaction and iteration usage 2026-08-31 15:53:57 +05:30
Shoubhit Dash eaa3dfe04e feat(ai): support automatic responses compaction 2026-08-31 15:51:01 +05:30
Shoubhit Dash 5fd800d169 feat(ai): preserve provider compaction in messages and events 2026-08-31 15:48:42 +05:30
117 changed files with 2436 additions and 3353 deletions
+4 -4
View File
@@ -1,8 +1,8 @@
{
"nodeModules": {
"x86_64-linux": "sha256-JStMvgtXBA5GrhyBJ5FtdqD8LWkcaPA9NXef+c2xUzw=",
"aarch64-linux": "sha256-WQxF+yS0ZImW0KW620XnZUBsKAJDoJ1jLDOMBaXI2/E=",
"aarch64-darwin": "sha256-km7G6s45dfFdW3Z6lFrs4NohD+vmwN1vR8PmEL0WCto=",
"x86_64-darwin": "sha256-YFbkcHpuspgTp+B+th3IJ3cnu5C2gEUSiy3NDXpD8UA="
"x86_64-linux": "sha256-fG6VYtNC0pce4VM9po7vVucPuJul42yuuijTjNSr7rk=",
"aarch64-linux": "sha256-3TznrmNqdt25cOxia6vcdi/5qKaeyLPIsNXGYBSJNrs=",
"aarch64-darwin": "sha256-8Kmagb5tfECSWZNsIJgrRP1d3X5tuEoWLEWkV3UENZo=",
"x86_64-darwin": "sha256-mIV+mDwIGD02BNYZVi37sY4ls1T01N6z76eBtH0sKiA="
}
}
+101
View File
@@ -249,6 +249,107 @@ The published legacy `Service`, `layer`, `clientLayer`, and module-level control
over the same implementation, including the legacy live `requests` array. New tests should use `Test` and
`testLayer`.
## Provider compaction
Compaction is opt-in. The package supports automatic compaction in OpenAI/Azure Responses and Anthropic Messages (including Claude on Vertex and Bedrock Messages), and explicit compaction calls in OpenAI/Azure/xAI Responses. Model and deployment support still depends on the provider.
This is different from prompt caching, server-side history storage, or truncation. Compaction returns provider-owned context that must be replayed to continue the conversation.
### Automatic compaction
Inside an `Effect.gen`, enable OpenAI compaction with typed provider options:
```ts
import { LLM, LLMClient, LLMRequest, Message } from "@opencode-ai/ai"
import { OpenAI } from "@opencode-ai/ai/providers"
const request = LLM.request({
model: OpenAI.configure({ apiKey }).responses("gpt-5.3-codex"),
messages,
providerOptions: {
contextManagement: [{ type: "compaction", compactThreshold: 200_000 }],
},
})
const response = yield * LLMClient.generate(request)
const next = LLMRequest.update(request, {
messages: [...request.messages, response.message, Message.user("Continue")],
})
```
`store: false` remains the default. Keep the entire `response.message`, not just `response.text`. Compaction events become ordered `CompactionPart`s alongside text and reasoning. The conversation contains everything needed to continue; there is no separate replay object or hidden provider transcript.
A compaction part has `provider` and exactly one representation: `encrypted` for Responses, or `text` for Anthropic. Responses also preserves the optional checkpoint `id`. These fields survive message serialization without becoming visible assistant text. Sending a checkpoint to another provider or an incompatible API fails rather than silently losing context.
```ts
import { CompactionPart, ProviderID } from "@opencode-ai/ai"
CompactionPart.make({ provider: ProviderID.make("openai"), id: "cmp_123", encrypted: "..." })
CompactionPart.make({ provider: ProviderID.make("anthropic"), text: "Summary of the conversation..." })
```
For Anthropic, use:
```ts
providerOptions: {
contextManagement: {
edits: [{
type: "compact_20260112",
trigger: { type: "input_tokens", value: 150_000 },
pauseAfterCompaction: true,
instructions: "Summarize the task and decisions. Do not call tools while summarizing.",
}],
},
}
```
- The trigger is optional (provider default: 150,000 tokens), with a minimum of 50,000.
- Custom instructions replace Anthropic's default summarization instructions.
- The route adds `compact-2026-01-12` to existing beta headers, including when replaying a checkpoint without enabling new compactions.
- A pause is exposed as `response.finishReason.raw === "compaction"`. The caller explicitly issues the next request; the package never automatically resumes.
- Anthropic can return a compaction block with `content: null` when summarization fails. This becomes a compaction part with `text: null`, which is **not** a successful replacement for prior history. The package never prunes history automatically.
- `Usage` totals include all reported Anthropic `usage.iterations`, including compaction. `contextTokens` separately reports the final message iteration's inclusive input size, when available. A compaction-only pause does not report a post-compaction context size. Raw iteration usage remains in `providerMetadata`.
Bedrock's Converse API does not support this feature. Select the native Claude Messages route explicitly; the default `.model(...)` remains Converse:
```ts
import { AmazonBedrock } from "@opencode-ai/ai/providers"
const model = AmazonBedrock.configure({ region: "us-east-1", credentials }).messages("us.anthropic.claude-opus-4-6-v1")
```
The corresponding package entrypoint is `@opencode-ai/ai/providers/amazon-bedrock/messages`. It uses InvokeModelWithResponseStream, AWS event-stream framing, bearer or SigV4 auth, and `anthropic_beta` in the request body.
### Explicit compaction
`LLMClient.compact(request)` performs exactly one HTTP call to `/responses/compact`, using the selected route's endpoint, credentials, query, and HTTP middleware. It returns a `CompactionResponse` containing replacement `messages` and usage, not a normal generation response.
```ts
const compacted = yield * LLMClient.compact(request)
const next = LLMRequest.update(request, {
messages: [...compacted.messages, Message.user("Continue")],
})
const response = yield * LLMClient.generate(next)
```
Replace the prior window with `compacted.messages`. Do not append it to the original transcript or extract only the encrypted item: the provider may retain additional messages in its output. Retained user and assistant messages remain ordinary messages with typed text, media, or reasoning parts, in their original order. Provider-specific message IDs, status, and phase use `providerMetadata`, not a raw output array hidden in an assistant message. Unsupported returned item types fail explicitly. Generation-only body overlays such as `stream` and `store` are not sent to the compact endpoint.
The input must still fit the model's context window. Explicit compaction is not an overflow-recovery operation. xAI supports this explicit path, not the automatic OpenAI option. Unsupported routes, including Bedrock Mantle, do not inherit an explicit compact endpoint simply because they use a Responses protocol.
### Ownership and verification
The AI package transports options and typed conversation parts. It does not schedule compaction, persist Session checkpoints, select history, switch providers, or replace Core's existing local compaction policy. Native compaction is not enabled for OpenCode Sessions by this feature; Session integration must persist these parts before enabling it. The AI SDK bridge rejects native compaction parts rather than dropping them. Provider-executed tool APIs and persistence changes are a separate follow-up.
Tests cover serialized round trips, real local HTTP plus a tool loop, AWS binary frames and signing, provider errors, malformed blocks, and usage accounting. Live provider tests are gated by `RECORD=true` and the relevant API keys:
```sh
# Run from packages/ai. Only records the selected new cassette group.
RECORD=true RECORDED_PREFIX=openai-compaction bun test test/provider/compaction.recorded.test.ts
RECORD=true RECORDED_PREFIX=xai-compaction bun test test/provider/compaction.recorded.test.ts
RECORD=true RECORDED_PREFIX=anthropic-compaction bun test test/provider/compaction.recorded.test.ts
```
Provider references: [OpenAI](https://developers.openai.com/api/docs/guides/compaction), [Azure](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/responses#server-side-compaction), [Anthropic](https://platform.claude.com/docs/en/build-with-claude/compaction), [Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-compaction.html), [xAI](https://docs.x.ai/developers/advanced-api-usage/context-compaction).
## Caching
Prompt caching is **on by default**. Every `LLMRequest` resolves to `cache: "auto"` unless the caller opts out with `cache: "none"`. Each protocol translates `CacheHint`s to its wire format (`cache_control` on Anthropic, `cachePoint` on Bedrock; OpenAI and Gemini do implicit caching server-side and don't need inline markers — auto is a no-op there).
+1
View File
@@ -40,6 +40,7 @@ const RESPECTS_INLINE_HINTS = new Set([
"anthropic-messages",
"google-vertex-messages",
"bedrock-converse",
"bedrock-messages",
"openrouter",
])
+179 -27
View File
@@ -6,8 +6,12 @@ import { Auth } from "../route/auth.js"
import { Endpoint } from "../route/endpoint.js"
import { Framing } from "../route/framing.js"
import { Protocol } from "../route/protocol.js"
import { Headers } from "effect/unstable/http"
import { HttpTransport } from "../route/transport/index.js"
import {
AIError,
HttpOptions,
LLMRequest,
LLMEvent,
mergeJsonRecords,
Usage,
@@ -15,7 +19,6 @@ import {
type FinishReasonDetails,
type FinishReason,
type JsonSchema,
type LLMRequest,
type MediaPart,
type ProviderMetadata,
type ToolCallPart,
@@ -61,6 +64,7 @@ export type ThinkingInput =
))
export interface OptionsInput {
readonly contextManagement?: ContextManagement
readonly [key: string]: unknown
readonly thinking?: ThinkingInput
readonly effort?: string
@@ -89,6 +93,23 @@ export interface OptionsInput {
export type ProviderOptionsInput = OptionsInput
export const ContextManagement = Schema.Struct({
edits: Schema.Array(
Schema.Struct({
type: Schema.Literal("compact_20260112"),
trigger: Schema.optional(
Schema.Struct({
type: Schema.Literal("input_tokens"),
value: Schema.Int.check(Schema.isGreaterThanOrEqualTo(50000)),
}),
),
pauseAfterCompaction: Schema.optional(Schema.Boolean),
instructions: Schema.optional(Schema.String),
}),
),
})
export type ContextManagement = typeof ContextManagement.Type
// =============================================================================
// Request Body Schema
// =============================================================================
@@ -236,7 +257,12 @@ const AnthropicUserBlock = Schema.Union([
AnthropicToolResultBlock,
])
type AnthropicUserBlock = Schema.Schema.Type<typeof AnthropicUserBlock>
const AnthropicCompactionBlock = Schema.Struct({
type: Schema.Literal("compaction"),
content: Schema.NullOr(Schema.String),
})
const AnthropicAssistantBlock = Schema.Union([
AnthropicCompactionBlock,
AnthropicTextBlock,
AnthropicThinkingBlock,
AnthropicRedactedThinkingBlock,
@@ -312,6 +338,18 @@ const AnthropicContainer = Schema.Union([
])
const AnthropicBodyFields = {
context_management: Schema.optional(
Schema.Struct({
edits: Schema.Array(
Schema.Struct({
type: Schema.Literal("compact_20260112"),
trigger: ContextManagement.fields.edits.value.fields.trigger,
pause_after_compaction: Schema.optional(Schema.Boolean),
instructions: Schema.optional(Schema.String),
}),
),
}),
),
model: Schema.String,
system: optionalArray(AnthropicTextBlock),
messages: Schema.Array(AnthropicMessage),
@@ -335,7 +373,7 @@ const AnthropicBodyFields = {
export const AnthropicMessagesBody = Schema.Struct(AnthropicBodyFields)
export type AnthropicMessagesBody = Schema.Schema.Type<typeof AnthropicMessagesBody>
const AnthropicUsage = Schema.StructWithRest(
const AnthropicIterationUsage = Schema.StructWithRest(
Schema.Struct({
input_tokens: optionalNull(Schema.Number),
output_tokens: Schema.optional(Schema.Number),
@@ -354,6 +392,13 @@ const AnthropicUsage = Schema.StructWithRest(
}),
[Schema.Record(Schema.String, Schema.Unknown)],
)
const AnthropicUsage = Schema.StructWithRest(
Schema.Struct({
...AnthropicIterationUsage.schema.fields,
iterations: Schema.optional(Schema.Array(AnthropicIterationUsage)),
}),
[JsonObject],
)
type AnthropicUsage = Schema.Schema.Type<typeof AnthropicUsage>
const AnthropicStreamBlock = Schema.Struct({
@@ -377,6 +422,7 @@ type AnthropicStreamBlock = Schema.Schema.Type<typeof AnthropicStreamBlock>
const decodeAnthropicStreamBlock = Schema.decodeUnknownOption(AnthropicStreamBlock)
const AnthropicStreamDelta = Schema.Struct({
content: optionalNull(Schema.String),
type: Schema.optional(Schema.String),
text: Schema.optional(Schema.String),
thinking: Schema.optional(Schema.String),
@@ -406,6 +452,8 @@ const AnthropicEvent = Schema.Struct({
type AnthropicEvent = Schema.Schema.Type<typeof AnthropicEvent>
interface ParserState {
readonly provider: LLMRequest["model"]["provider"]
readonly compactions: Readonly<Record<number, string | null>>
readonly providerMetadataKey: string
readonly tools: ToolStream.State<number>
readonly reasoningSignatures: Readonly<Record<number, string>>
@@ -848,6 +896,12 @@ const lowerMessages = Effect.fn("AnthropicMessages.lowerMessages")(function* (
if (message.role === "assistant") {
const content: AnthropicAssistantBlock[] = []
for (const part of message.content) {
if (part.type === "compaction") {
if (part.provider !== request.model.provider || part.text === undefined)
return yield* invalid("Compaction state must be replayed to its originating provider and API")
content.push({ type: "compaction", content: part.text })
continue
}
if (part.type === "text") {
if (part.text.trim().length === 0) continue
content.push({ type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) })
@@ -1003,6 +1057,9 @@ const resolveThinking = Effect.fn("AnthropicMessages.resolveThinking")(function*
})
const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (request: LLMRequest) {
const management = yield* ProviderShared.validateWith(
Schema.decodeUnknownEffect(Schema.UndefinedOr(ContextManagement)),
)(request.providerOptions?.contextManagement)
const generation = request.generation
const toolSchemaCompatibility = request.model.compatibility?.toolSchema
// Allocate the 4-breakpoint budget in invalidation order: tools → system →
@@ -1037,7 +1094,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
)
}
const options = yield* resolveOptions(request)
return {
const body = {
model: request.model.id,
system,
messages,
@@ -1058,6 +1115,18 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
metadata: options.metadata,
service_tier: options.service_tier,
}
if (!management) return body
return {
...body,
context_management: {
edits: management.edits.map((edit) => ({
type: edit.type,
trigger: edit.trigger,
pause_after_compaction: edit.pauseAfterCompaction,
instructions: edit.instructions,
})),
},
}
})
// =============================================================================
@@ -1079,18 +1148,31 @@ const mapFinishReason = (reason: string | null | undefined): FinishReason => {
// expose that subset through `output_tokens_details.thinking_tokens`.
const mapUsage = (usage: AnthropicUsage | undefined, providerMetadataKey: string): Usage | undefined => {
if (!usage) return undefined
const nonCached = usage.input_tokens ?? undefined
const cacheRead = usage.cache_read_input_tokens ?? undefined
const cacheWrite = usage.cache_creation_input_tokens ?? undefined
const iterations = usage.iterations?.length ? usage.iterations : [usage]
const last = usage.iterations?.at(-1)
const nonCached = ProviderShared.sumTokens(...iterations.map((item) => item.input_tokens ?? undefined))
const cacheRead = ProviderShared.sumTokens(...iterations.map((item) => item.cache_read_input_tokens ?? undefined))
const cacheWrite = ProviderShared.sumTokens(
...iterations.map((item) => item.cache_creation_input_tokens ?? undefined),
)
const inputTokens = ProviderShared.sumTokens(nonCached, cacheRead, cacheWrite)
const outputTokens = ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens))
return new Usage({
inputTokens,
outputTokens: usage.output_tokens,
outputTokens,
contextTokens:
last?.type === "message"
? ProviderShared.sumTokens(
last.input_tokens ?? undefined,
last.cache_read_input_tokens ?? undefined,
last.cache_creation_input_tokens ?? undefined,
)
: undefined,
nonCachedInputTokens: nonCached,
cacheReadInputTokens: cacheRead,
cacheWriteInputTokens: cacheWrite,
reasoningTokens: usage.output_tokens_details?.thinking_tokens,
totalTokens: ProviderShared.totalTokens(inputTokens, usage.output_tokens, undefined),
reasoningTokens: ProviderShared.sumTokens(...iterations.map((item) => item.output_tokens_details?.thinking_tokens)),
totalTokens: ProviderShared.totalTokens(inputTokens, outputTokens, undefined),
providerMetadata: { [providerMetadataKey]: usage },
})
}
@@ -1112,6 +1194,7 @@ const mergeUsage = (left: Usage | undefined, right: Usage | undefined, providerM
return new Usage({
inputTokens,
outputTokens,
contextTokens: right.contextTokens ?? left.contextTokens,
nonCachedInputTokens,
cacheReadInputTokens,
cacheWriteInputTokens,
@@ -1170,7 +1253,6 @@ const onContentBlockStart = (
event: AnthropicEvent & { readonly content_block: AnthropicStreamBlock },
): StepResult => {
const block = event.content_block
if (!block) return [state, NO_EVENTS]
if (block.type === "tool_use" || block.type === "server_tool_use") {
if (event.index === undefined || !block.id) return [state, NO_EVENTS]
@@ -1265,7 +1347,16 @@ const onContentBlockDelta = Effect.fn("AnthropicMessages.onContentBlockDelta")(f
) {
const delta = event.delta
if (delta?.type === "text_delta" && delta.text) {
if (delta.type === "compaction_delta") {
if (event.index === undefined || !(event.index in state.compactions) || delta.content === undefined)
return yield* ProviderShared.eventError(ADAPTER, "Compaction delta is missing its block or content")
return [
{ ...state, compactions: { ...state.compactions, [event.index]: delta.content } },
NO_EVENTS,
] satisfies StepResult
}
if (delta.type === "text_delta" && delta.text) {
if (!state.lifecycle.text.has(`text-${event.index ?? 0}`)) return [state, NO_EVENTS] satisfies StepResult
const events: LLMEvent[] = []
return [
@@ -1274,7 +1365,7 @@ const onContentBlockDelta = Effect.fn("AnthropicMessages.onContentBlockDelta")(f
] satisfies StepResult
}
if (delta?.type === "thinking_delta" && delta.thinking) {
if (delta.type === "thinking_delta" && delta.thinking) {
if (!state.lifecycle.reasoning.has(`reasoning-${event.index ?? 0}`)) return [state, NO_EVENTS] satisfies StepResult
const events: LLMEvent[] = []
return [
@@ -1286,7 +1377,7 @@ const onContentBlockDelta = Effect.fn("AnthropicMessages.onContentBlockDelta")(f
] satisfies StepResult
}
if (delta?.type === "signature_delta" && delta.signature) {
if (delta.type === "signature_delta" && delta.signature) {
const index = event.index ?? 0
if (!state.lifecycle.reasoning.has(`reasoning-${index}`)) return [state, NO_EVENTS] satisfies StepResult
return [
@@ -1298,7 +1389,7 @@ const onContentBlockDelta = Effect.fn("AnthropicMessages.onContentBlockDelta")(f
] satisfies StepResult
}
if (delta?.type === "input_json_delta" && event.index !== undefined) {
if (delta.type === "input_json_delta" && event.index !== undefined) {
if (!delta.partial_json) return [state, NO_EVENTS] satisfies StepResult
if (!state.tools[event.index]) return [state, NO_EVENTS] satisfies StepResult
const result = ToolStream.appendExisting(
@@ -1323,6 +1414,18 @@ const onContentBlockStop = Effect.fn("AnthropicMessages.onContentBlockStop")(fun
event: AnthropicEvent,
) {
if (event.index === undefined) return [state, NO_EVENTS] satisfies StepResult
if (event.index in state.compactions) {
const { [event.index]: content, ...compactions } = state.compactions
const events: LLMEvent[] = []
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
events.push(
LLMEvent.compaction({
provider: state.provider,
text: content,
}),
)
return [{ ...state, compactions, lifecycle }, events] satisfies StepResult
}
const result = yield* ToolStream.finish(ADAPTER, state.tools, event.index)
const events: LLMEvent[] = []
const resultEvents = result.events ?? []
@@ -1374,6 +1477,8 @@ const onMessageDelta = (
}
const onMessageStop = Effect.fn("AnthropicMessages.onMessageStop")(function* (state: ParserState) {
if (Object.keys(state.compactions).length)
return yield* ProviderShared.eventError(ADAPTER, "Response ended with an incomplete compaction block")
const result = yield* ToolStream.finishAll(ADAPTER, state.tools)
const events: LLMEvent[] = []
const lifecycle = result.events.length ? Lifecycle.stepStart(state.lifecycle, events) : state.lifecycle
@@ -1418,16 +1523,21 @@ const onError = (event: AnthropicEvent) => {
)
}
const isKnownStreamBlockType = (type: string) =>
type === "text" ||
type === "thinking" ||
type === "redacted_thinking" ||
type === "tool_use" ||
type === "server_tool_use" ||
isServerToolResultType(type)
const isKnownStreamDeltaType = (type: string) =>
type === "text_delta" || type === "thinking_delta" || type === "signature_delta" || type === "input_json_delta"
const STREAM_BLOCK_TYPES = new Set([
"compaction",
"text",
"thinking",
"redacted_thinking",
"tool_use",
"server_tool_use",
])
const STREAM_DELTA_TYPES = new Set([
"compaction_delta",
"text_delta",
"thinking_delta",
"signature_delta",
"input_json_delta",
])
const invalidStreamEvent = (event: AnthropicEvent) =>
Effect.fail(
@@ -1456,7 +1566,16 @@ const step = (state: ParserState, event: AnthropicEvent) => {
if (event.type === "content_block_start") {
if (!ProviderShared.isRecord(event.content_block) || typeof event.content_block.type !== "string")
return invalidStreamEvent(event)
if (!isKnownStreamBlockType(event.content_block.type)) return Effect.succeed<StepResult>([state, NO_EVENTS])
if (event.content_block.type === "compaction") {
const decoded = Schema.decodeUnknownOption(AnthropicCompactionBlock)(event.content_block)
if (event.index === undefined || Option.isNone(decoded)) return invalidStreamEvent(event)
return Effect.succeed<StepResult>([
{ ...state, compactions: { ...state.compactions, [event.index]: decoded.value.content } },
NO_EVENTS,
])
}
if (!STREAM_BLOCK_TYPES.has(event.content_block.type) && !isServerToolResultType(event.content_block.type))
return Effect.succeed<StepResult>([state, NO_EVENTS])
const decoded = decodeAnthropicStreamBlock(event.content_block)
if (Option.isNone(decoded)) return invalidStreamEvent(event)
const block = decoded.value
@@ -1470,7 +1589,7 @@ const step = (state: ParserState, event: AnthropicEvent) => {
}
if (event.type === "content_block_delta") {
if (!ProviderShared.isRecord(event.delta)) return invalidStreamEvent(event)
if (typeof event.delta.type === "string" && !isKnownStreamDeltaType(event.delta.type))
if (typeof event.delta.type === "string" && !STREAM_DELTA_TYPES.has(event.delta.type))
return Effect.succeed<StepResult>([state, NO_EVENTS])
const decoded = decodeAnthropicStreamDelta(event.delta)
if (Option.isNone(decoded)) return invalidStreamEvent(event)
@@ -1504,6 +1623,8 @@ export const protocol = Protocol.make({
stream: {
event: Protocol.jsonEvent(AnthropicEvent),
initial: (request) => ({
provider: request.model.provider,
compactions: {},
providerMetadataKey: request.model.route.providerMetadataKey ?? String(request.model.provider),
tools: ToolStream.empty<number>(),
reasoningSignatures: {},
@@ -1513,6 +1634,37 @@ export const protocol = Protocol.make({
},
})
export const transport = <Body extends Pick<AnthropicMessagesBody, "messages" | "context_management">>() => {
const http = HttpTransport.httpJson<Body, string>({ framing })
return {
...http,
prepare: (input: Parameters<typeof http.prepare>[0]) => {
if (
!input.body.context_management?.edits.length &&
!input.body.messages.some((message) => message.content.some((block) => block.type === "compaction"))
)
return http.prepare(input)
const headers = Headers.fromInput(input.request.http?.headers)
const betas = new Set(
(headers["anthropic-beta"] ?? "")
.split(",")
.map((item) => item.trim())
.filter(Boolean),
)
betas.add("compact-2026-01-12")
return http.prepare({
...input,
request: LLMRequest.update(input.request, {
http: new HttpOptions({
...input.request.http,
headers: { ...headers, "anthropic-beta": [...betas].join(",") },
}),
}),
})
},
}
}
export const route = Route.make({
id: ADAPTER,
provider: "anthropic",
@@ -1522,7 +1674,7 @@ export const route = Route.make({
baseURL: DEFAULT_BASE_URL,
}),
auth: Auth.none,
framing,
transport: transport<AnthropicMessagesBody>(),
headers: () => ({ "anthropic-version": "2023-06-01" }),
})
@@ -0,0 +1,96 @@
import { Effect, Encoding, Schema, Struct } from "effect"
import { Headers } from "effect/unstable/http"
import { AIError } from "../schema/index.js"
import { Route } from "../route/client.js"
import { Endpoint } from "../route/endpoint.js"
import { Protocol } from "../route/protocol.js"
import { classifyProviderFailure } from "../provider-error.js"
import { AnthropicMessages } from "./anthropic-messages.js"
import { BedrockEventStream } from "./bedrock-event-stream.js"
import { BedrockAuth } from "./utils/bedrock-auth.js"
import { JsonObject, ProviderShared } from "./shared.js"
const ID = "bedrock-messages"
const VERSION = "bedrock-2023-05-31"
const Body = Schema.Struct({
...Struct.omit(AnthropicMessages.AnthropicMessagesBody.fields, ["model", "stream"]),
anthropic_version: Schema.Literal(VERSION),
anthropic_beta: Schema.optional(Schema.Array(Schema.String)),
})
const Event = Schema.Struct({
chunk: Schema.optional(Schema.Struct({ bytes: Schema.String })),
exception: Schema.optional(
Schema.Struct({
type: Schema.String,
details: Schema.StructWithRest(
Schema.Struct({ message: Schema.optional(Schema.String), originalMessage: Schema.optional(Schema.String) }),
[JsonObject],
),
}),
),
})
export const protocol = Protocol.make({
id: ID,
body: {
schema: Body,
from: Effect.fn("BedrockMessages.fromRequest")(function* (request) {
const body = yield* AnthropicMessages.protocol.body.from(request)
const headers = Headers.fromInput(request.http?.headers)
const betas = new Set(
(headers["anthropic-beta"] ?? "")
.split(",")
.map((value) => value.trim())
.filter(Boolean),
)
if (
body.context_management?.edits.length ||
body.messages.some((message) => message.content.some((block) => block.type === "compaction"))
)
betas.add("compact-2026-01-12")
return {
...Struct.omit(body, ["model", "stream"]),
anthropic_version: VERSION,
anthropic_beta: betas.size ? [...betas] : undefined,
} satisfies typeof Body.Type
}),
},
stream: {
event: Event,
initial: AnthropicMessages.protocol.stream.initial,
step: Effect.fn("BedrockMessages.step")(function* (state, event) {
if (event.exception)
return yield* new AIError({
reason: classifyProviderFailure({
message: event.exception.details.message ?? event.exception.details.originalMessage ?? event.exception.type,
rawBody: ProviderShared.encodeJson(event),
}),
})
if (!event.chunk) return yield* ProviderShared.eventError(ID, "Bedrock Messages event is missing its chunk")
const text = yield* Effect.fromResult(Encoding.decodeBase64String(event.chunk.bytes)).pipe(
Effect.mapError((cause) =>
ProviderShared.eventError(ID, "Invalid Bedrock Messages chunk encoding", undefined, cause),
),
)
const decoded = yield* Schema.decodeUnknownEffect(AnthropicMessages.protocol.stream.event)(text).pipe(
Effect.mapError((cause) => ProviderShared.eventError(ID, "Invalid Bedrock Messages event", undefined, cause)),
)
return yield* AnthropicMessages.protocol.stream.step(state, decoded)
}),
},
})
export const route = Route.make({
id: ID,
provider: "amazon-bedrock",
providerMetadataKey: "anthropic",
protocol,
endpoint: Endpoint.path(
({ request }) => `/model/${encodeURIComponent(request.model.id)}/invoke-with-response-stream`,
{ baseURL: "https://bedrock-runtime.us-east-1.amazonaws.com" },
),
auth: BedrockAuth.auth,
framing: BedrockEventStream.framing(ID),
})
export * as BedrockMessages from "./bedrock-messages.js"
+1
View File
@@ -1,5 +1,6 @@
export * as AnthropicMessages from "./anthropic-messages.js"
export * as BedrockConverse from "./bedrock-converse.js"
export { BedrockMessages } from "./bedrock-messages.js"
export * as Gemini from "./gemini.js"
export * as MistralChat from "./mistral-chat.js"
export * as OpenAIChat from "./openai-chat.js"
+123 -40
View File
@@ -32,13 +32,14 @@ export const PATH = "/responses"
// =============================================================================
// Request Body Schema
// =============================================================================
const OpenResponsesInputText = Schema.Struct({
export const OpenResponsesInputText = Schema.Struct({
type: Schema.tag("input_text"),
text: Schema.String,
})
const OpenResponsesInputImage = Schema.Struct({
export const OpenResponsesInputImage = Schema.Struct({
type: Schema.tag("input_image"),
image_url: Schema.String,
detail: Schema.optional(Schema.String),
})
const OpenResponsesInputFile = Schema.Struct({
type: Schema.tag("input_file"),
@@ -54,7 +55,7 @@ const MediaInput = Schema.Union([OpenResponsesInputImage, OpenResponsesInputFile
export type MediaInput = Schema.Schema.Type<typeof MediaInput>
const OpenResponsesInputContent = Schema.Union([OpenResponsesInputText, MediaInput])
const OpenResponsesOutputText = Schema.Struct({
export const OpenResponsesOutputText = Schema.Struct({
type: Schema.tag("output_text"),
text: Schema.String,
})
@@ -62,6 +63,13 @@ const OpenResponsesOutputText = Schema.Struct({
export const MessagePhase = Schema.NullOr(Schema.Literals(["commentary", "final_answer"]))
type MessagePhase = Schema.Schema.Type<typeof MessagePhase>
export const MessageMetadata = Schema.Struct({
itemId: Schema.optional(Schema.String),
type: Schema.optional(Schema.Literal("message")),
status: Schema.optional(Schema.String),
phase: Schema.optional(MessagePhase),
})
const messagePhase = (value: unknown): MessagePhase | undefined => {
if (value === null || value === "commentary" || value === "final_answer") return value
return undefined
@@ -72,7 +80,7 @@ const OpenResponsesReasoningSummaryText = Schema.Struct({
text: Schema.String,
})
const OpenResponsesReasoningItem = Schema.Struct({
export const OpenResponsesReasoningItem = Schema.Struct({
type: Schema.tag("reasoning"),
id: Schema.optionalKey(Schema.String),
summary: Schema.Array(OpenResponsesReasoningSummaryText),
@@ -149,16 +157,30 @@ const OpenResponsesFunctionCallOutput = Schema.Union([
Schema.Array(OpenResponsesFunctionCallOutputContent),
])
export const CompactionItem = Schema.Struct({
type: Schema.Literal("compaction"),
id: optionalNull(Schema.String),
encrypted_content: Schema.String,
})
export const InputItem = Schema.Union([
CompactionItem,
Schema.Struct({ role: Schema.tag("system"), content: Schema.String }),
Schema.Struct({ role: Schema.tag("developer"), content: Schema.String }),
Schema.Struct({ role: Schema.tag("user"), content: Schema.Array(OpenResponsesInputContent) }),
Schema.Struct({
role: Schema.tag("user"),
content: Schema.Array(OpenResponsesInputContent),
type: Schema.optional(Schema.Literal("message")),
id: Schema.optional(Schema.String),
status: Schema.optional(Schema.String),
}),
Schema.Struct({
type: Schema.tag("message"),
id: Schema.optionalKey(Schema.String),
role: Schema.tag("assistant"),
content: Schema.Array(OpenResponsesOutputText),
phase: Schema.optionalKey(MessagePhase),
status: Schema.optional(Schema.String),
}),
OpenResponsesReasoningItem,
Schema.Struct({
@@ -267,7 +289,7 @@ const OpenResponsesBody = Schema.Struct({
})
export type OpenResponsesBody = Schema.Schema.Type<typeof OpenResponsesBody>
const OpenResponsesUsage = Schema.Struct({
export const OpenResponsesUsage = Schema.Struct({
input_tokens: Schema.optional(Schema.Number),
input_tokens_details: optionalNull(
Schema.Struct({
@@ -387,6 +409,8 @@ export interface Extension {
const BASE: Extension = { id: ADAPTER, name: NAME }
export interface ParserState {
readonly provider: LLMRequest["model"]["provider"]
readonly completedCompactions: ReadonlySet<string>
readonly id: string
readonly name: string
readonly providerMetadataKey: string
@@ -501,7 +525,13 @@ const lowerMedia = Effect.fn("OpenResponses.lowerMedia")(function* (
...(url ? { file_url: url } : { file_data: media.dataUrl }),
}
}
return { type: "input_image" as const, image_url: url ?? media.dataUrl }
return {
type: "input_image" as const,
image_url: url ?? media.dataUrl,
detail: yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(OpenResponsesInputImage.fields.detail))(
part.providerMetadata?.[request.model.route.providerMetadataKey ?? "openresponses"]?.detail,
),
}
})
const lowerUserContent = Effect.fnUntraced(function* (
@@ -568,6 +598,9 @@ const lowerMessages = Effect.fn("OpenResponses.lowerMessages")(function* (reques
const providerMetadataKey = request.model.route.providerMetadataKey ?? "openresponses"
for (const message of request.messages) {
const metadata = yield* ProviderShared.validateWith(
Schema.decodeUnknownEffect(Schema.UndefinedOr(MessageMetadata)),
)(message.providerMetadata?.[providerMetadataKey])
if (message.role === "system") {
input.push({
role: "developer",
@@ -578,7 +611,8 @@ const lowerMessages = Effect.fn("OpenResponses.lowerMessages")(function* (reques
if (message.role === "user") {
const content = yield* Effect.forEach(message.content, (part) => lowerUserContent(part, request, extension))
if (content.length > 0) input.push({ role: "user", content })
if (content.length > 0)
input.push({ role: "user", content, type: metadata?.type, id: metadata?.itemId, status: metadata?.status })
continue
}
@@ -591,9 +625,10 @@ const lowerMessages = Effect.fn("OpenResponses.lowerMessages")(function* (reques
const groups = content.reduce<
Array<{ id: string | undefined; phase: MessagePhase | null | undefined; parts: TextPart[] }>
>((groups, part) => {
const metadata = part.providerMetadata?.[providerMetadataKey]
const id = itemID(part.providerMetadata, providerMetadataKey)
const phase = ProviderShared.isRecord(metadata) ? messagePhase(metadata.phase) : undefined
const partMetadata = part.providerMetadata?.[providerMetadataKey]
const id = itemID(part.providerMetadata, providerMetadataKey) ?? metadata?.itemId
const partPhase = messagePhase(partMetadata?.phase)
const phase = partPhase === undefined ? metadata?.phase : partPhase
const group = groups.at(-1)
if (group && group.id === id && group.phase === phase) group.parts.push(part)
else groups.push({ id, phase, parts: [part] })
@@ -604,6 +639,7 @@ const lowerMessages = Effect.fn("OpenResponses.lowerMessages")(function* (reques
type: "message" as const,
...(group.id === undefined ? {} : { id: group.id }),
role: "assistant" as const,
status: metadata?.status,
content: group.parts.map((part) => ({ type: "output_text" as const, text: part.text })),
...(group.phase === undefined ? {} : { phase: group.phase }),
})),
@@ -611,6 +647,15 @@ const lowerMessages = Effect.fn("OpenResponses.lowerMessages")(function* (reques
content.splice(0, content.length)
}
for (const part of message.content) {
if (part.type === "compaction") {
flushText()
if (part.provider !== request.model.provider || part.encrypted === undefined)
return yield* ProviderShared.invalidRequest(
"Compaction state must be replayed to its originating provider and API",
)
input.push({ type: "compaction", id: part.id, encrypted_content: part.encrypted })
continue
}
if (part.type === "text") {
content.push(part)
continue
@@ -689,13 +734,30 @@ const lowerMessages = Effect.fn("OpenResponses.lowerMessages")(function* (reques
return input
})
const lowerOptions = (request: LLMRequest) => {
const options = OpenResponsesOptions.resolve(request)
export const lowerConversation = Effect.fn("OpenResponses.lowerConversation")(function* (
request: LLMRequest,
extension: Extension,
) {
const instructions = ProviderShared.joinText(request.system)
return {
model: request.model.id,
input: yield* lowerMessages(request, extension),
...(instructions ? { instructions } : {}),
}
})
export const lowerGeneration = (request: LLMRequest) => {
const options = OpenResponsesOptions.resolve(request)
const generation = request.generation
const cacheKey = ProviderShared.promptCacheKey(request)
const parallelToolCalls = resolveParallelToolCalls(request)
return {
...(instructions ? { instructions } : {}),
stream: true as const,
max_output_tokens: generation?.maxTokens,
temperature: generation?.temperature,
top_p: generation?.topP,
presence_penalty: generation?.presencePenalty,
frequency_penalty: generation?.frequencyPenalty,
...(options.store !== undefined ? { store: options.store } : {}),
...(options.metadata ? { metadata: options.metadata } : {}),
...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}),
@@ -723,7 +785,7 @@ export const resolveParallelToolCalls = (request: LLMRequest) => {
return disabled === undefined ? undefined : !disabled
}
const allowedToolChoice = (request: LLMRequest) => {
export const allowedToolChoice = (request: LLMRequest) => {
const allowed = OpenResponsesOptions.resolve(request).allowedTools
if (!allowed) return undefined
return {
@@ -737,11 +799,10 @@ export const fromRequestWithExtension = Effect.fn("OpenResponses.fromRequestWith
request: LLMRequest,
extension: Extension,
) {
const generation = request.generation
const toolSchemaCompatibility = request.model.compatibility?.toolSchema
return {
model: request.model.id,
input: yield* lowerMessages(request, extension),
...(yield* lowerConversation(request, extension)),
...lowerGeneration(request),
tools:
request.tools.length === 0
? undefined
@@ -755,13 +816,6 @@ export const fromRequestWithExtension = Effect.fn("OpenResponses.fromRequestWith
tool_choice:
allowedToolChoice(request) ??
(request.toolChoice ? yield* lowerToolChoice(extension.name, request.toolChoice) : undefined),
stream: true as const,
max_output_tokens: generation?.maxTokens,
temperature: generation?.temperature,
top_p: generation?.topP,
presence_penalty: generation?.presencePenalty,
frequency_penalty: generation?.frequencyPenalty,
...lowerOptions(request),
}
})
@@ -778,7 +832,7 @@ export const fromRequest = Effect.fn("OpenResponses.fromRequest")(function* (req
// cached-read and cache-write subsets, and `output_tokens` (inclusive total)
// with a `reasoning_tokens` subset. Pass the totals through and derive the
// non-cached breakdown.
const mapUsage = (usage: OpenResponsesUsage | null | undefined, providerMetadataKey: string) => {
export const mapUsage = (usage: OpenResponsesUsage | null | undefined, providerMetadataKey: string) => {
if (!usage) return undefined
const cached = usage.input_tokens_details?.cached_tokens
const cacheWrite = usage.input_tokens_details?.cache_write_tokens
@@ -1084,6 +1138,25 @@ const onOutputItemDone = Effect.fn("OpenResponses.onOutputItemDone")(function* (
) {
if (!item) return [state, NO_EVENTS] satisfies StepResult
if (item.type === "compaction") {
if (!item.id || typeof item.encrypted_content !== "string")
return yield* ProviderShared.eventError(state.id, "Compaction output is missing its id or encrypted content")
if (state.completedCompactions.has(item.id)) return [state, NO_EVENTS] satisfies StepResult
const events: LLMEvent[] = []
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
events.push(
LLMEvent.compaction({
provider: state.provider,
id: item.id,
encrypted: item.encrypted_content,
}),
)
return [
{ ...state, lifecycle, completedCompactions: new Set([...state.completedCompactions, item.id]) },
events,
] satisfies StepResult
}
if (item.type === "message" && item.id !== undefined) {
const message = state.message?.id === item.id ? state.message : undefined
const itemPhase = messagePhase(item.phase)
@@ -1243,26 +1316,34 @@ const onResponseFinish = Effect.fn("OpenResponses.onResponseFinish")(function* (
const events: LLMEvent[] = []
if (event.type === "response.completed") {
for (const item of event.response?.output ?? []) {
const id = item.id ?? (item.type === "function_call" ? item.call_id : undefined)
if (id === undefined) continue
if (item.type !== "function_call" || !current.tools[id]) continue
if (item.type !== "compaction" && item.type !== "function_call") continue
if (item.type === "compaction") {
// Terminal recovery cannot insert a checkpoint before already-emitted content.
if (state.lifecycle.stepStarted && !state.completedCompactions.has(item.id ?? ""))
return yield* ProviderShared.eventError(
state.id,
"Cannot recover a compaction checkpoint after output has been emitted",
)
}
if (item.type === "function_call" && !current.tools[item.id ?? item.call_id ?? ""]) continue
const [next, emitted] = yield* onOutputItemDone(current, item)
current = next
events.push(...emitted)
}
// Some compatible providers omit output_item.done even after completing the response.
const pending = yield* ToolStream.finishAll(current.id, current.tools)
current = {
...current,
tools: pending.tools,
hasFunctionCall:
current.hasFunctionCall ||
pending.events.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)),
}
events.push(...pending.events)
}
// Some compatible providers omit output_item.done even after completing the response.
const pending =
event.type === "response.completed"
? yield* ToolStream.finishAll(current.id, current.tools)
: { tools: current.tools, events: NO_EVENTS }
events.push(...pending.events)
const hasFunctionCall =
pending.events.some((event) => LLMEvent.is.toolCall(event) || LLMEvent.is.toolInputError(event)) ||
current.hasFunctionCall
const lifecycle = Lifecycle.finish(current.lifecycle, events, {
reason: {
normalized: mapFinishReason(event, hasFunctionCall),
normalized: mapFinishReason(event, current.hasFunctionCall),
raw: event.response?.incomplete_details?.reason,
},
usage: mapUsage(event.response?.usage, current.providerMetadataKey),
@@ -1274,7 +1355,7 @@ const onResponseFinish = Effect.fn("OpenResponses.onResponseFinish")(function* (
})
: undefined,
})
return [{ ...current, lifecycle, hasFunctionCall, tools: pending.tools }, events] satisfies StepResult
return [{ ...current, lifecycle }, events] satisfies StepResult
})
// Build the prettiest summary available from whatever the provider supplied.
@@ -1409,6 +1490,8 @@ export const step = (state: ParserState, input: Event) => {
* implementations compose this baseline with their own tools and event variants.
*/
export const initial = (request: LLMRequest, extension: Extension = BASE): ParserState => ({
provider: request.model.provider,
completedCompactions: new Set<string>(),
id: extension.id,
name: extension.name,
providerMetadataKey: request.model.route.providerMetadataKey ?? "openresponses",
+27 -9
View File
@@ -5,13 +5,14 @@ import { Auth } from "../route/auth.js"
import { Endpoint } from "../route/endpoint.js"
import { Protocol } from "../route/protocol.js"
import { HttpTransport } from "../route/transport/index.js"
import { LLMRequest, type JsonSchema, type ToolDefinition } from "../schema/index.js"
import type { LLMRequest, JsonSchema, ToolDefinition } from "../schema/index.js"
import { OpenResponses } from "./open-responses.js"
import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
import { OpenAIImage } from "./utils/openai-image.js"
import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js"
import { ToolSchemaProjection } from "./utils/tool-schema.js"
import { OpenResponsesChannel } from "./open-responses-channel.js"
import { ResponsesCompaction } from "./utils/responses-compaction.js"
const ADAPTER = "openai-responses"
const NAME = "OpenAI Responses"
@@ -20,6 +21,14 @@ const WEBSOCKET_ROTATE_AFTER_MS = 55 * 60 * 1000
export const DEFAULT_BASE_URL = "https://api.openai.com/v1"
export const PATH = OpenResponses.PATH
export const ContextManagement = Schema.Array(
Schema.Struct({
type: Schema.Literal("compaction"),
compactThreshold: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
}),
)
export type ContextManagement = typeof ContextManagement.Type
const OpenAIResponsesImageGenerationTool = Schema.Struct({
type: Schema.tag("image_generation"),
action: Schema.optional(Schema.Literals(["auto", "generate", "edit"])),
@@ -78,6 +87,14 @@ const OpenAIResponsesCoreFields = {
input: Schema.Array(Schema.Union([OpenResponses.InputItem, OpenAIResponsesHostedToolItem])),
tools: optionalArray(OpenAIResponsesTools),
tool_choice: Schema.optional(OpenAIResponsesToolChoice),
context_management: Schema.optional(
Schema.Array(
Schema.Struct({
type: Schema.Literal("compaction"),
compact_threshold: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
}),
),
),
}
const OpenAIResponsesBody = Schema.Struct({
@@ -125,15 +142,14 @@ const lowerToolChoice = (toolChoice: NonNullable<LLMRequest["toolChoice"]>, tool
const decodeBody = ProviderShared.validateWith(Schema.decodeUnknownEffect(OpenAIResponsesBody))
const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request: LLMRequest) {
const body = yield* OpenResponses.fromRequestWithExtension(
LLMRequest.update(request, { tools: [], toolChoice: undefined }),
extension,
)
const management = yield* ProviderShared.validateWith(
Schema.decodeUnknownEffect(Schema.UndefinedOr(ContextManagement)),
)(request.providerOptions?.contextManagement)
const toolSchemaCompatibility = request.model.compatibility?.toolSchema
const parallelToolCalls = OpenResponses.resolveParallelToolCalls(request)
return yield* decodeBody({
...body,
...(parallelToolCalls === undefined ? {} : { parallel_tool_calls: parallelToolCalls }),
...(yield* OpenResponses.lowerConversation(request, extension)),
...OpenResponses.lowerGeneration(request),
context_management: management?.map((edit) => ({ type: edit.type, compact_threshold: edit.compactThreshold })),
tools:
request.tools.length === 0
? undefined
@@ -141,7 +157,8 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
lowerTool(tool, ToolSchemaProjection.modelCompatibility(tool.inputSchema, toolSchemaCompatibility)),
),
tool_choice:
body.tool_choice ?? (request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined),
OpenResponses.allowedToolChoice(request) ??
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools) : undefined),
})
})
@@ -223,6 +240,7 @@ export const transport = channelTransport({
})
export const route = Route.make({
compact: ResponsesCompaction.make(extension),
id: ADAPTER,
provider: "openai",
providerMetadataKey: "openai",
@@ -0,0 +1,152 @@
import { Effect, Schema, Stream } from "effect"
import {
AIError,
InvalidProviderOutputError,
CompactionPart,
CompactionResponse,
HttpOptions,
LLMRequest,
Message,
type ContentPart,
mergeJsonRecords,
} from "../../schema/index.js"
import type { CompactOperation } from "../../route/client.js"
import { Endpoint } from "../../route/endpoint.js"
import { RequestExecutor } from "../../route/executor.js"
import { HttpTransport } from "../../route/transport/index.js"
import { OpenResponses } from "../open-responses.js"
import { JsonObject, ProviderShared } from "../shared.js"
const Body = Schema.Struct({
model: Schema.String,
input: Schema.Array(Schema.Unknown),
instructions: Schema.optional(Schema.String),
previous_response_id: Schema.optional(Schema.String),
})
const Text = Schema.Union([OpenResponses.OpenResponsesInputText, OpenResponses.OpenResponsesOutputText])
const File = Schema.Union([
Schema.Struct({ type: Schema.Literal("input_file"), filename: Schema.String, file_url: Schema.String }),
Schema.Struct({ type: Schema.Literal("input_file"), filename: Schema.String, file_data: Schema.String }),
])
const MessageFields = {
type: Schema.Literal("message"),
id: Schema.optional(Schema.String),
status: Schema.optional(Schema.String),
phase: Schema.optional(OpenResponses.MessagePhase),
}
const Response = Schema.Struct({
object: Schema.Literal("response.compaction"),
output: Schema.Array(
Schema.Union([
OpenResponses.CompactionItem,
OpenResponses.OpenResponsesReasoningItem,
Schema.Struct({
...MessageFields,
role: Schema.Literal("user"),
content: Schema.Array(Schema.Union([Text, OpenResponses.OpenResponsesInputImage, File])).check(
Schema.isMinLength(1),
),
}),
Schema.Struct({
...MessageFields,
role: Schema.Literal("assistant"),
content: Schema.Array(Text).check(Schema.isMinLength(1)),
}),
]),
),
usage: Schema.optional(Schema.StructWithRest(OpenResponses.OpenResponsesUsage, [JsonObject])),
})
export const make = (extension: OpenResponses.Extension): CompactOperation =>
Effect.fn("ResponsesCompaction.execute")(function* (request, executor, options) {
const route = request.model.route
const native = yield* OpenResponses.lowerConversation(request, extension)
const body = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Body))(
mergeJsonRecords(native, request.http?.body),
)
const url = Endpoint.render(route.endpoint, { request, body: native })
url.pathname = `${url.pathname.replace(/\/$/, "")}/compact`
const parts = yield* HttpTransport.jsonRequestParts({
request: LLMRequest.update(request, {
http: request.http === undefined ? undefined : new HttpOptions({ ...request.http, body: undefined }),
}),
body,
endpoint: Endpoint.path(url.toString()),
auth: route.auth,
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
})
const response = yield* executor.execute(
ProviderShared.jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
options?.http,
)
const text = yield* RequestExecutor.responseStream(response).pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(text, chunk) => text + chunk,
),
)
const invalid = (message: string, cause?: unknown) =>
new AIError({
reason: new InvalidProviderOutputError({
route: route.id,
message,
body: text,
cause,
http: RequestExecutor.responseHttp(response),
}),
})
const result = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Response))(text).pipe(
Effect.mapError((cause) => invalid("Invalid compaction response", cause)),
)
if (!result.output.some((item) => item.type === "compaction"))
return yield* invalid("Compaction response did not contain a checkpoint")
return new CompactionResponse({
messages: result.output.map((item) => toMessage(item, request.model)),
usage: OpenResponses.mapUsage(result.usage, route.providerMetadataKey ?? String(request.model.provider)),
})
})
function toMessage(item: (typeof Response.Type.output)[number], model: LLMRequest["model"]): Message {
if (item.type === "compaction")
return Message.assistant(
CompactionPart.make({ provider: model.provider, id: item.id ?? undefined, encrypted: item.encrypted_content }),
)
const key = model.route.providerMetadataKey ?? String(model.provider)
if (item.type === "reasoning") {
const summary = item.summary.length ? item.summary : [{ text: "" }]
return Message.assistant(
summary.map((part) => ({
type: "reasoning" as const,
text: part.text,
providerMetadata: { [key]: { itemId: item.id, reasoningEncryptedContent: item.encrypted_content } },
})),
)
}
return Message.make({
role: item.role,
providerMetadata: { [key]: { itemId: item.id, type: item.type, status: item.status, phase: item.phase } },
content: item.content.map((part): ContentPart => {
if (part.type === "input_text" || part.type === "output_text") return { type: "text", text: part.text }
if (part.type === "input_image")
return {
type: "media",
data: part.image_url,
mediaType: /^data:([^;,]+)/.exec(part.image_url)?.[1] ?? "image/*",
providerMetadata: part.detail === undefined ? undefined : { [key]: { detail: part.detail } },
}
const data = "file_url" in part ? part.file_url : part.file_data
return {
type: "media",
data,
filename: part.filename,
mediaType: /^data:([^;,]+)/.exec(data)?.[1] ?? "application/octet-stream",
}
}),
})
}
export * as ResponsesCompaction from "./responses-compaction.js"
@@ -4,6 +4,7 @@ import type { LLMRequest } from "../schema/index.js"
import { OpenResponses } from "./open-responses.js"
import { JsonObject, optionalNull, ProviderShared } from "./shared.js"
import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js"
import { ResponsesCompaction } from "./utils/responses-compaction.js"
const ADAPTER = "xai-responses"
const NAME = "xAI Responses"
@@ -44,6 +45,10 @@ const extension = {
const decodeBody = ProviderShared.validateWith(Schema.decodeUnknownEffect(XAIResponsesBody))
const fromRequest = Effect.fn("XAIResponses.fromRequest")(function* (request: LLMRequest) {
if (request.providerOptions?.contextManagement !== undefined)
return yield* ProviderShared.invalidRequest(
"xAI requires explicit compaction through LLMClient.compact; automatic context management is not supported",
)
return yield* decodeBody(yield* OpenResponses.fromRequestWithExtension(request, extension))
})
@@ -84,4 +89,6 @@ export const protocol = Protocol.make({
},
})
export const compact = ResponsesCompaction.make(extension)
export * as XAIResponses from "./xai-responses.js"
+21 -9
View File
@@ -1,9 +1,11 @@
import type { RouteDefaultsInput } from "../route/client.js"
import type { Route, RouteDefaultsInput } from "../route/client.js"
import { Auth } from "../route/auth.js"
import type { ProviderPackage } from "../provider-package.js"
import { ProviderID, type ModelID } from "../schema/index.js"
import * as BedrockConverse from "../protocols/bedrock-converse.js"
import type { BedrockCredentials } from "../protocols/bedrock-converse.js"
import { BedrockMessages } from "../protocols/bedrock-messages.js"
import type { AnthropicMessages } from "../protocols/anthropic-messages.js"
export const id = ProviderID.make("amazon-bedrock")
@@ -25,38 +27,40 @@ export interface Settings extends ProviderPackage.Settings {
readonly region?: string
readonly topP?: number
}
export const routes = [BedrockConverse.route]
export const routes = [BedrockConverse.route, BedrockMessages.route]
const bedrockBaseURL = (region: string) => `https://bedrock-runtime.${region}.amazonaws.com`
const configuredRoute = (input: Config) => {
const configuredRoute = <Body, Prepared>(route: Route<Body, Prepared>, input: Config) => {
const { apiKey, credentials, region, baseURL, ...rest } = input
const resolvedRegion = region ?? credentials?.region ?? "us-east-1"
return BedrockConverse.route.with({
return route.with({
...rest,
provider: id,
providerMetadataKey: "bedrock",
providerMetadataKey: route.providerMetadataKey,
endpoint: { baseURL: baseURL ?? bedrockBaseURL(resolvedRegion) },
auth: apiKey === undefined ? BedrockConverse.sigV4Auth(credentials) : Auth.bearer(apiKey),
})
}
export const configure = (input: Config = {}) => {
const route = configuredRoute(input)
const route = configuredRoute(BedrockConverse.route, input)
const messages = configuredRoute(BedrockMessages.route, input)
return {
id,
model: (modelID: string | ModelID) => route.model({ id: modelID }),
messages: (modelID: string | ModelID) => messages.model<AnthropicMessages.ProviderOptionsInput>({ id: modelID }),
configure,
}
}
export const provider = configure()
export const model: ProviderPackage.Definition<Settings>["model"] = (modelID, settings) => {
const config = (settings: Settings): Config => {
if (settings.auth === "bearer" && settings.apiKey === undefined)
throw new Error("Amazon Bedrock bearer auth requires apiKey")
if (settings.auth === "sigv4" && settings.apiKey !== undefined)
throw new Error("Amazon Bedrock SigV4 auth does not accept apiKey")
return configure({
return {
apiKey: settings.auth === "sigv4" ? undefined : settings.apiKey,
baseURL: settings.baseURL,
credentials: settings.credentials,
@@ -64,5 +68,13 @@ export const model: ProviderPackage.Definition<Settings>["model"] = (modelID, se
headers: settings.headers === undefined ? undefined : { ...settings.headers },
http: settings.body === undefined ? undefined : { body: { ...settings.body } },
region: settings.region,
}).model(modelID)
}
}
export const model: ProviderPackage.Definition<Settings>["model"] = (modelID, settings) =>
configure(config(settings)).model(modelID)
export const messagesModel: ProviderPackage.Definition<
Settings & { readonly providerOptions?: AnthropicMessages.ProviderOptionsInput },
AnthropicMessages.ProviderOptionsInput
>["model"] = (modelID, settings) =>
configure({ ...config(settings), providerOptions: settings.providerOptions }).messages(modelID)
@@ -0,0 +1 @@
export { messagesModel as model } from "../amazon-bedrock.js"
@@ -57,7 +57,9 @@ const route = Route.make({
}),
endpoint: Endpoint.path(({ request }) => `/${request.model.id}:streamRawPredict`),
auth: Auth.none,
framing: AnthropicMessages.framing,
transport: AnthropicMessages.transport<
Omit<AnthropicMessages.AnthropicMessagesBody, "model"> & { readonly anthropic_version: typeof VERSION }
>(),
headers: () => ({ "anthropic-version": HEADER_VERSION }),
})
@@ -1,10 +1,12 @@
import { mergeProviderOptions, type ProviderOptions } from "../schema/index.js"
import type { OpenAIServiceTier } from "../protocols/utils/openai-options.js"
import type { Options } from "../protocols/utils/open-responses-options.js"
import type { ContextManagement } from "../protocols/openai-responses.js"
export type { OpenAIResponseIncludable, OpenAIServiceTier } from "../protocols/utils/openai-options.js"
export type OpenAIOptionsInput = Omit<Options, "serviceTier"> & {
readonly contextManagement?: ContextManagement
readonly serviceTier?: OpenAIServiceTier
readonly [key: string]: unknown
}
+2 -1
View File
@@ -13,7 +13,7 @@ import type { ProviderPackage } from "../provider-package.js"
export const id = ProviderID.make("xai")
export type XAIProviderOptionsInput = OpenAIOptionsInput
export type XAIProviderOptionsInput = OpenAIOptionsInput & { readonly contextManagement?: never }
export type LanguageModelOptions = Omit<RouteDefaultsInput, "providerOptions"> &
ProviderAuthOption<"optional"> & {
@@ -32,6 +32,7 @@ export type { XAIImageOptions } from "../protocols/xai-images.js"
const RESPONSES_WEBSOCKET_ROTATE_AFTER_MS = 24 * 60 * 1000
const responsesRoute = Route.make({
compact: XAIResponses.compact,
id: "openai-responses",
provider: id,
providerMetadataKey: "xai",
+52 -5
View File
@@ -13,6 +13,7 @@ import * as ProviderShared from "../protocols/shared.js"
import type { ProtocolID, ProviderOptions } from "../schema/index.js"
import {
AIError,
CompactionResponse,
AIErrorReason,
GenerationOptions,
HttpOptions,
@@ -35,6 +36,7 @@ export interface RouteBody<Body> {
}
export interface Route<Body, Prepared = unknown> {
readonly compact?: CompactOperation
readonly id: string
readonly provider?: ProviderID
/** ProviderMetadata namespace emitted and consumed by this route. */
@@ -42,6 +44,8 @@ export interface Route<Body, Prepared = unknown> {
readonly protocol: ProtocolID
readonly endpoint: Endpoint.Definition<Body>
readonly auth: Auth.Definition
/** Deployment headers resolved once for every operation, before transport authentication. */
readonly headers?: (input: { readonly request: LLMRequest }) => Record<string, string>
readonly transport: Transport<Body, Prepared, unknown>
readonly defaults: RouteDefaults
readonly body: RouteBody<Body>
@@ -150,6 +154,10 @@ export const httpOptions = (input: HttpOptionsInput | undefined) => {
}
export interface Interface {
readonly compact: (
request: LLMRequest,
options?: Pick<StreamOptions, "http">,
) => Effect.Effect<CompactionResponse, AIError>
readonly stream: StreamMethod
readonly generate: GenerateMethod
}
@@ -167,6 +175,12 @@ export interface GenerateMethod {
(request: LLMRequest, options?: StreamOptions): Effect.Effect<LLMResponse, AIError>
}
export type CompactOperation = (
request: LLMRequest,
executor: RequestExecutor.Interface,
options?: Pick<StreamOptions, "http">,
) => Effect.Effect<CompactionResponse, AIError>
export class Service extends Context.Service<Service, Interface>()("@opencode/LLMClient") {}
const resolveRequestOptions = (request: LLMRequest) => {
@@ -187,6 +201,7 @@ const resolveRequestOptions = (request: LLMRequest) => {
}
export interface MakeInput<Body, Frame, Event, State> {
readonly compact?: CompactOperation
/** Route id used in diagnostics and prepared request metadata. */
readonly id: string
/** Provider identity for route-owned model construction. */
@@ -208,6 +223,7 @@ export interface MakeInput<Body, Frame, Event, State> {
}
export interface MakeTransportInput<Body, Prepared, Frame, Event, State> {
readonly compact?: CompactOperation
/** Route id used in diagnostics and prepared request metadata. */
readonly id: string
/** Provider identity for route-owned model construction. */
@@ -283,12 +299,14 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
const build = (routeInput: BuiltRouteInput): Route<Body, Prepared> => {
const route: Route<Body, Prepared> = {
compact: routeInput.compact,
id: routeInput.id,
provider: routeInput.provider === undefined ? undefined : ProviderID.make(routeInput.provider),
providerMetadataKey: routeInput.providerMetadataKey,
protocol: protocol.id,
endpoint: routeInput.endpoint,
auth: routeInput.auth ?? Auth.none,
headers: routeInput.headers,
transport: routeInput.transport,
defaults: routeInput.defaults ?? {},
body: protocol.body,
@@ -318,7 +336,6 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
endpoint: routeInput.endpoint,
auth: routeInput.auth ?? Auth.none,
encodeBody,
headers: routeInput.headers,
middleware: options?.http,
webSocket: options?.webSocket,
}),
@@ -435,6 +452,7 @@ export function make<Body, Prepared, Frame, Event, State>(
if ("transport" in input) return makeFromTransport(input)
const protocol = input.protocol
return makeFromTransport({
compact: input.compact,
id: input.id,
provider: input.provider,
providerMetadataKey: input.providerMetadataKey,
@@ -447,11 +465,19 @@ export function make<Body, Prepared, Frame, Event, State>(
})
}
const compile = Effect.fn("LLM.compile")(function* (request: LLMRequest, options?: StreamOptions) {
const prepareRequest = (request: LLMRequest) => {
const original = applyCachePolicy(resolveRequestOptions(request))
const sanitized = LLMRequest.update(original, sanitizeSurrogates({ ...LLMRequest.input(original), model: undefined }))
const tools = [...new Map(sanitized.tools.map((tool) => [tool.name, tool])).values()]
const resolved = tools.length === sanitized.tools.length ? sanitized : LLMRequest.update(sanitized, { tools })
const headers = resolved.model.route.headers?.({ request: resolved })
return headers === undefined
? resolved
: LLMRequest.update(resolved, { http: mergeHttpOptions(new HttpOptions({ headers }), resolved.http) })
}
const compile = Effect.fn("LLM.compile")(function* (request: LLMRequest, options?: StreamOptions) {
const resolved = prepareRequest(request)
const route = resolved.model.route
const body = yield* route.body
@@ -510,6 +536,15 @@ export function generate(request: LLMRequest, options?: StreamOptions): Effect.E
})
}
export const compact = (
request: LLMRequest,
options?: Pick<StreamOptions, "http">,
): Effect.Effect<CompactionResponse, AIError, Service> =>
Effect.gen(function* () {
const client = yield* Service
return yield* client.compact(request, options)
})
export const streamRequest = (request: LLMRequest, options?: StreamOptions) =>
Stream.unwrap(
Effect.gen(function* () {
@@ -520,16 +555,28 @@ export const streamRequest = (request: LLMRequest, options?: StreamOptions) =>
export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer.effect(
Service,
Effect.gen(function* () {
const stream = streamRequestWith({
http: yield* RequestExecutor.Service,
const executor = yield* RequestExecutor.Service
const stream = streamRequestWith({ http: executor })
return Service.of({
stream,
generate: generateWith(stream),
compact: (request, options) =>
Effect.suspend(() => {
const operation = request.model.route.compact
if (!operation)
return ProviderShared.invalidRequest(
`${request.model.provider}/${request.model.route.id} does not support explicit compaction`,
)
return operation(prepareRequest(request), executor, options)
}),
})
return Service.of({ stream, generate: generateWith(stream) })
}),
)
export const Route = { make } as const
export const LLMClient = {
compact,
Service,
layer,
stream,
+18 -4
View File
@@ -3,6 +3,7 @@ import { LLM } from "@opencode-ai/schema/llm"
import { ContentBlockID, ToolCallID } from "./ids.js"
import {
Message,
CompactionPart,
ProviderMetadata,
ToolCallPart,
ToolOutput,
@@ -62,6 +63,8 @@ export { ProviderMetadata } from "./messages.js"
* Matches the same escape-hatch field on `LLMEvent`.
*/
export class Usage extends Schema.Class<Usage>("AI.Usage")({
/** Effective input size of the final message iteration, when reported; not billed totals. */
contextTokens: Schema.optional(Schema.Number),
inputTokens: Schema.optional(Schema.Number),
outputTokens: Schema.optional(Schema.Number),
nonCachedInputTokens: Schema.optional(Schema.Number),
@@ -72,7 +75,7 @@ export class Usage extends Schema.Class<Usage>("AI.Usage")({
providerMetadata: Schema.optional(ProviderMetadata),
}) {
/**
* Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
* Non-reasoning output tokens (including compaction summaries) — `outputTokens` minus `reasoningTokens`, clamped
* to zero. The one place subtraction happens in this contract; the clamp
* means a provider reporting `reasoningTokens > outputTokens` produces a
* harmless zero rather than a negative that crashes downstream schemas.
@@ -88,6 +91,12 @@ export class Usage extends Schema.Class<Usage>("AI.Usage")({
export type UsageInput = Usage | ConstructorParameters<typeof Usage>[0]
/** A replacement context window. Replace prior history with these messages. */
export class CompactionResponse extends Schema.Class<CompactionResponse>("LLM.CompactionResponse")({
messages: Schema.Array(Message),
usage: Schema.optional(Usage),
}) {}
export const StepStart = Schema.Struct({
type: Schema.tag("step-start"),
index: Schema.Number,
@@ -241,6 +250,7 @@ export const ProviderErrorEvent = Schema.Struct({
export type ProviderErrorEvent = Schema.Schema.Type<typeof ProviderErrorEvent>
const llmEventTagged = Schema.Union([
CompactionPart,
StepStart,
TextStart,
TextDelta,
@@ -274,6 +284,7 @@ const toolCallID = (value: ToolCallID | string) => ToolCallID.make(value)
* `events.filter(LLMEvent.guards["tool-call"])`.
*/
export const LLMEvent = Object.assign(llmEventTagged, {
compaction: CompactionPart.make,
stepStart: StepStart.make,
textStart: (input: WithID<TextStart, ContentBlockID>) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
textDelta: (input: WithID<TextDelta, ContentBlockID>) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
@@ -311,6 +322,7 @@ export const LLMEvent = Object.assign(llmEventTagged, {
}),
providerError: ProviderErrorEvent.make,
is: {
compaction: llmEventTagged.guards.compaction,
stepStart: llmEventTagged.guards["step-start"],
textStart: llmEventTagged.guards["text-start"],
textDelta: llmEventTagged.guards["text-delta"],
@@ -333,10 +345,10 @@ export const LLMEvent = Object.assign(llmEventTagged, {
export type LLMEvent = Schema.Schema.Type<typeof llmEventTagged>
/** Joins deltas per fragment, letting an authoritative end value replace that fragment's accumulated deltas. */
const joinFragments = <Delta extends { id: string; text: string }, End extends { id: string; text?: string }>(
const joinFragments = (
events: ReadonlyArray<LLMEvent>,
isDelta: (event: LLMEvent) => event is Extract<LLMEvent, Delta>,
isEnd: (event: LLMEvent) => event is Extract<LLMEvent, End>,
isDelta: (event: LLMEvent) => event is LLMEvent & { id: string; text: string },
isEnd: (event: LLMEvent) => event is LLMEvent & { id: string; text?: string },
) => {
const order: string[] = []
const parts = new Map<string, string>()
@@ -563,6 +575,8 @@ const reduceToolCall = (state: ResponseState, event: ToolCall): ResponseState =>
const reduceResponseState = (state: ResponseState, event: LLMEvent): ResponseState => {
const next = appendEvent(state, event)
switch (event.type) {
case "compaction":
return appendContent(next, event)
case "text-start":
return ensureText(next, event.id, event.providerMetadata)
case "text-delta":
+37 -3
View File
@@ -9,6 +9,7 @@ import {
LanguageModelSchema,
ProviderOptions,
} from "./options.js"
import { ProviderID } from "./ids.js"
export const MessageRole = Schema.Literals(["system", "user", "assistant", "tool"])
export type MessageRole = Schema.Schema.Type<typeof MessageRole>
@@ -52,6 +53,7 @@ export const MediaPart = Schema.Struct({
filename: Schema.optional(Schema.String),
cache: Schema.optional(CacheHint),
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
providerMetadata: Schema.optional(ProviderMetadata),
}).annotate({ identifier: "LLM.Content.Media" })
export type MediaPart = Schema.Schema.Type<typeof MediaPart>
@@ -185,9 +187,40 @@ export const ReasoningPart = Schema.Struct({
}).annotate({ identifier: "LLM.Content.Reasoning" })
export type ReasoningPart = Schema.Schema.Type<typeof ReasoningPart>
export const ContentPart = Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
Schema.toTaggedUnion("type"),
)
/** A provider-generated context checkpoint, distinct from visible assistant text. */
type CompactionContent =
| { readonly encrypted: string; readonly text?: never }
| { readonly text: string | null; readonly encrypted?: never }
const compactionPartSchema = Schema.Struct({
type: Schema.Literal("compaction"),
provider: ProviderID,
id: Schema.optional(Schema.String),
encrypted: Schema.optional(Schema.String),
/** Null means the provider failed to produce a summary; prior history must be retained. */
text: Schema.optional(Schema.NullOr(Schema.String)),
})
.pipe(
Schema.refine(
(part): part is typeof part & CompactionContent => (part.encrypted !== undefined) !== (part.text !== undefined),
{ message: "Compaction requires either encrypted content or a summary" },
),
)
.annotate({ identifier: "LLM.Content.Compaction" })
export type CompactionPart = typeof compactionPartSchema.Type
export const CompactionPart = Object.assign(compactionPartSchema, {
make: (input: Omit<CompactionPart, "type" | "encrypted" | "text"> & CompactionContent): CompactionPart =>
Schema.decodeUnknownSync(compactionPartSchema)({ type: "compaction", ...input }),
})
export const ContentPart = Schema.Union([
TextPart,
MediaPart,
ToolCallPart,
ToolResultPart,
ReasoningPart,
CompactionPart,
]).pipe(Schema.toTaggedUnion("type"))
export type ContentPart = Schema.Schema.Type<typeof ContentPart>
export class Message extends Schema.Class<Message>("LLM.Message")({
@@ -195,6 +228,7 @@ export class Message extends Schema.Class<Message>("LLM.Message")({
role: MessageRole,
content: Schema.Array(ContentPart),
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
providerMetadata: Schema.optional(ProviderMetadata),
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
}) {}
+1 -1
View File
@@ -267,7 +267,7 @@ export const CachePolicyObject = Schema.Struct({
Schema.Union([
Schema.Literal("latest-user-message"),
Schema.Literal("latest-assistant"),
Schema.Struct({ tail: Schema.Natural }),
Schema.Struct({ tail: Schema.Number }),
]),
),
ttlSeconds: Schema.optional(Schema.Number),
+11
View File
@@ -4,6 +4,7 @@ import { LLMClient } from "./route/client.js"
import {
LLMEvent,
LLMResponse,
CompactionResponse,
type FinishReasonDetails,
type AIError,
type LLMRequest,
@@ -133,6 +134,16 @@ const make = (options: LayerOptions) =>
}
})
const test = Test.of({
compact: (request) =>
stream(request).pipe(
Stream.runFold(LLMResponse.empty, LLMResponse.reduce),
Effect.flatMap((state) => {
const response = LLMResponse.complete(state)
if (!response?.message.content.some((part) => part.type === "compaction"))
return Effect.die("TestLLM compaction response must contain a checkpoint and terminal finish event")
return Effect.succeed(new CompactionResponse({ messages: [response.message], usage: response.usage }))
}),
),
stream,
generate: (request) =>
stream(request).pipe(
+1
View File
@@ -56,6 +56,7 @@ function normalizeToolMessage(message: Message, pending: Map<string, ToolCallPar
role: message.role,
content,
metadata: message.metadata,
providerMetadata: message.providerMetadata,
native: message.native,
})
}
+32
View File
@@ -126,6 +126,38 @@ describe("applyCachePolicy", () => {
}),
)
for (const fixture of [
{ name: "default", cache: undefined, control: { type: "ephemeral" } },
{ name: "auto", cache: "auto", control: { type: "ephemeral" } },
{
name: "explicit one-hour",
cache: { tools: true, system: true, messages: { tail: 1 }, ttlSeconds: 3600 },
control: { type: "ephemeral", ttl: "1h" },
},
{ name: "disabled", cache: "none", control: undefined },
] as const) {
it.effect(`Bedrock Messages respects ${fixture.name} caching`, () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: AmazonBedrock.configure({ apiKey: "test" }).messages("anthropic.claude-opus-4-6-v1"),
system: "Stable instructions",
tools: [
{ name: "lookup", description: "Look up a value", inputSchema: { type: "object", properties: {} } },
],
prompt: "hello",
cache: fixture.cache,
}),
)
expect(prepared.body).toMatchObject({
tools: [{ name: "lookup", cache_control: fixture.control }],
system: [{ type: "text", text: "Stable instructions", cache_control: fixture.control }],
messages: [{ role: "user", content: [{ type: "text", text: "hello", cache_control: fixture.control }] }],
})
}),
)
}
it.effect("'auto' is a no-op on Gemini (out-of-band caching protocol)", () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
+97
View File
@@ -0,0 +1,97 @@
import { expect } from "bun:test"
import { Effect } from "effect"
import { FetchHttpClient } from "effect/unstable/http"
import { LLM, LLMRequest, Message } from "../src/index.js"
import { LLMClient } from "../src/route/client.js"
import { OpenAI } from "../src/providers.js"
import { testEffect } from "./lib/effect.js"
import { runtimeLayer } from "./lib/http.js"
import { sseEvents } from "./lib/sse.js"
testEffect(runtimeLayer(FetchHttpClient.layer)).live("compaction and a tool loop work end to end over HTTP", () =>
Effect.gen(function* () {
const checkpoint = { type: "compaction", id: "cmp_local", encrypted_content: "opaque-local-state" }
const calls: string[] = []
const server = yield* Effect.acquireRelease(
Effect.sync(() =>
Bun.serve({
hostname: "127.0.0.1",
port: 0,
async fetch(request) {
const path = new URL(request.url).pathname
calls.push(path)
const body = await request.json()
expect(request.headers.get("authorization")).toBe("Bearer fixture")
if (path === "/v1/responses/compact") {
expect(body.stream).toBeUndefined()
return Response.json({
object: "response.compaction",
output: [checkpoint],
usage: { input_tokens: 100, output_tokens: 10, total_tokens: 110 },
})
}
expect(body.input[0]).toEqual(checkpoint)
expect(body.stream).toBe(true)
if (calls.length === 2)
return new Response(
sseEvents(
{
type: "response.output_item.done",
item: { type: "function_call", id: "fc_1", call_id: "call_1", name: "lookup", arguments: "{}" },
},
{ type: "response.completed", response: { id: "resp_1" } },
),
{ headers: { "content-type": "text/event-stream" } },
)
expect(body.input.at(-2)).toMatchObject({ type: "function_call", call_id: "call_1" })
expect(body.input.at(-1)).toEqual({ type: "function_call_output", call_id: "call_1", output: "42" })
const output = sseEvents(
{ type: "response.output_item.added", item: { type: "message", id: "msg_1" } },
{ type: "response.output_text.delta", item_id: "msg_1", delta: "The answer is 42." },
{
type: "response.output_item.done",
item: { type: "message", id: "msg_1", content: [{ type: "output_text", text: "The answer is 42." }] },
},
{ type: "response.completed", response: { id: "resp_2" } },
)
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(output.slice(0, 37)))
controller.enqueue(new TextEncoder().encode(output.slice(37)))
controller.close()
},
}),
{ headers: { "content-type": "text/event-stream" } },
)
},
}),
),
(server) => Effect.sync(() => server.stop(true)),
)
const model = OpenAI.configure({ apiKey: "fixture", baseURL: `http://127.0.0.1:${server.port}/v1` }).responses(
"fixture",
)
const request = LLM.request({
model,
prompt: "original",
tools: [{ name: "lookup", description: "Lookup a number", inputSchema: { type: "object", properties: {} } }],
})
const compacted = yield* LLMClient.compact(request)
const messages = [...compacted.messages, Message.user("Look up the answer")]
const first = yield* LLMClient.generate(LLMRequest.update(request, { messages }))
expect(first.toolCalls).toHaveLength(1)
const call = first.toolCalls[0]!
const last = yield* LLMClient.generate(
LLMRequest.update(request, {
messages: [
...messages,
first.message,
Message.tool({ id: call.id, name: call.name, result: "42", resultType: "text" }),
],
}),
)
expect(last.text).toBe("The answer is 42.")
expect(calls).toEqual(["/v1/responses/compact", "/v1/responses", "/v1/responses"])
}),
)
+49
View File
@@ -0,0 +1,49 @@
import { expect, test } from "bun:test"
import { Schema } from "effect"
import { CompactionPart, LLMEvent, LLMResponse, Message, ProviderID } from "../src/schema/index.js"
test("compaction survives event assembly and message serialization without becoming text", () => {
const part = CompactionPart.make({
provider: ProviderID.make("openai"),
id: "cmp_1",
encrypted: "opaque",
})
const response = LLMResponse.fromEvents([
LLMEvent.textStart({ id: "before" }),
LLMEvent.textDelta({ id: "before", text: "Before" }),
LLMEvent.textEnd({ id: "before" }),
part,
LLMEvent.textStart({ id: "after" }),
LLMEvent.textDelta({ id: "after", text: "After" }),
LLMEvent.textEnd({ id: "after" }),
LLMEvent.finish({ reason: { normalized: "stop" } }),
])!
expect(response.message.content.map((part) => part.type)).toEqual(["text", "compaction", "text"])
expect(response.text).toBe("BeforeAfter")
expect(response.reasoning).toBe("")
expect(response.events.filter(LLMEvent.is.compaction)).toEqual([part])
const codec = Schema.fromJsonString(Message)
expect(Schema.decodeSync(codec)(Schema.encodeSync(codec)(response.message))).toEqual(response.message)
})
test("compaction requires exactly one typed representation", () => {
const provider = ProviderID.make("anthropic")
expect(CompactionPart.make({ provider, text: null })).toEqual({ type: "compaction", provider, text: null })
const decode = Schema.decodeUnknownSync(CompactionPart)
expect(() => decode({ type: "compaction", provider })).toThrow()
expect(() => decode({ type: "compaction", provider, text: "summary", encrypted: "opaque" })).toThrow()
})
test("tagged content and event guards accept both checkpoint representations", () => {
for (const part of [
CompactionPart.make({ provider: ProviderID.make("openai"), encrypted: "opaque" }),
CompactionPart.make({ provider: ProviderID.make("anthropic"), text: "summary" }),
CompactionPart.make({ provider: ProviderID.make("anthropic"), text: null }),
]) {
expect(LLMEvent.is.compaction(part)).toBe(true)
expect(LLMEvent.guards.compaction(part)).toBe(true)
const codec = Schema.fromJsonString(Message)
const message = Message.assistant(part)
expect(Schema.decodeSync(codec)(Schema.encodeSync(codec)(message))).toEqual(message)
}
})
@@ -0,0 +1,69 @@
import { Effect } from "effect"
import { CompactionPart, LLM, LLMClient, LLMEvent, Message, ProviderID } from "../../src/index.js"
import { OpenAI, Anthropic, AmazonBedrock } from "../../src/providers.js"
const openai = OpenAI.configure({
apiKey: "test",
providerOptions: { contextManagement: [{ type: "compaction", compactThreshold: 100000 }] },
}).responses("gpt-5.3-codex")
LLMClient.compact(LLM.request({ model: openai, prompt: "hello" }))
const checkpoint = CompactionPart.make({ provider: ProviderID.make("openai"), id: "cmp_1", encrypted: "opaque" })
const provider = ProviderID.make("anthropic")
CompactionPart.make({ provider, text: "summary" })
CompactionPart.make({ provider, text: null })
// @ts-expect-error A checkpoint must have a representation.
CompactionPart.make({ provider })
// @ts-expect-error Encrypted and summary representations are mutually exclusive.
CompactionPart.make({ provider, encrypted: "opaque", text: "summary" })
// @ts-expect-error A failed summary cannot also carry encrypted content.
LLMEvent.compaction({ provider, encrypted: "opaque", text: null })
// @ts-expect-error The canonical message type also enforces the invariant.
Message.assistant({ type: "compaction", provider })
if (checkpoint.encrypted !== undefined) {
checkpoint.encrypted satisfies string
checkpoint.text satisfies undefined
}
if (checkpoint.text !== undefined) {
checkpoint.text satisfies string | null
checkpoint.encrypted satisfies undefined
}
checkpoint.encrypted
// @ts-expect-error Compaction parts do not contain a generic provider payload.
checkpoint.value
LLMClient.compact(LLM.request({ model: openai, prompt: "hello" })).pipe(
Effect.map((result) => {
result.messages
// @ts-expect-error Compaction returns replacement history, not a synthetic assistant message.
result.message
}),
)
LLM.request({
model: openai,
providerOptions: {
// @ts-expect-error A token threshold is numeric.
contextManagement: [{ type: "compaction", compactThreshold: "100000" }],
},
})
for (const model of [
Anthropic.configure().model("claude-opus-4-6"),
AmazonBedrock.configure().messages("anthropic.claude-opus-4-6-v1"),
]) {
LLM.request({
model,
providerOptions: {
contextManagement: {
edits: [
{ type: "compact_20260112", pauseAfterCompaction: true, instructions: "Summarize without using tools" },
],
},
},
})
LLM.request({
model,
providerOptions: {
// @ts-expect-error A pause setting is boolean.
contextManagement: { edits: [{ type: "compact_20260112", pauseAfterCompaction: "yes" }] },
},
})
}
@@ -0,0 +1,170 @@
import { expect } from "bun:test"
import { Effect, Schema } from "effect"
import { LLM, LLMRequest, Message } from "../../src/index.js"
import { LLMClient } from "../../src/route/client.js"
import { Anthropic, GoogleVertexMessages } from "../../src/providers/index.js"
import { testEffect } from "../lib/effect.js"
import { dynamicResponse, fixedResponse } from "../lib/http.js"
import { sseEvents } from "../lib/sse.js"
for (const fixture of [
{
name: "empty iterations fall back to top-level usage",
usage: { input_tokens: 2, output_tokens: 3, cache_read_input_tokens: null, iterations: [] },
expected: { inputTokens: 2, outputTokens: 3, totalTokens: 5, contextTokens: undefined },
},
{
name: "compaction-only usage has no post-compaction context size",
usage: {
input_tokens: 0,
output_tokens: 0,
iterations: [{ type: "compaction", input_tokens: 7, cache_read_input_tokens: 3, output_tokens: 2 }],
},
expected: { inputTokens: 10, outputTokens: 2, totalTokens: 12, contextTokens: undefined },
},
{
name: "partially reported iterations preserve known totals",
usage: {
iterations: [
{ type: "compaction", input_tokens: 7, cache_creation_input_tokens: 2 },
{ type: "message", output_tokens: 3 },
],
},
expected: { inputTokens: 9, outputTokens: 3, totalTokens: 12, contextTokens: undefined },
},
{
name: "missing counters remain unknown rather than zero",
usage: { iterations: [{ type: "message" }] },
expected: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined, contextTokens: undefined },
},
]) {
testEffect(
fixedResponse(
sseEvents(
{ type: "message_start", message: { usage: fixture.usage } },
{ type: "message_delta", delta: { stop_reason: "end_turn" } },
{ type: "message_stop" },
),
),
).effect(fixture.name, () =>
Effect.gen(function* () {
const result = yield* LLMClient.generate(
LLM.request({
model: Anthropic.configure({ apiKey: "test" }).model("claude-opus-4-6"),
prompt: "hello",
}),
)
expect(result.usage).toMatchObject(fixture.expected)
}),
)
}
for (const model of [
Anthropic.configure({ apiKey: "test" }).model("claude-opus-4-6"),
GoogleVertexMessages.configure({ accessToken: "test", project: "test" }).model("claude-opus-4-6"),
]) {
for (const summary of ["Summary of the conversation", null]) {
const block = { type: "compaction", content: summary }
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
const body = JSON.parse(text)
expect(request.headers["anthropic-beta"]).toBe("existing-beta,compact-2026-01-12")
if (body.messages.length === 1) {
expect(body.context_management.edits).toEqual([
{
type: "compact_20260112",
trigger: { type: "input_tokens", value: 50000 },
pause_after_compaction: true,
},
])
}
if (body.messages.length > 1) {
expect(body.messages[1].content).toEqual([block])
expect(body.context_management).toBeUndefined()
}
return respond(
sseEvents(
{ type: "message_start", message: { usage: { input_tokens: 50000, output_tokens: 0 } } },
{ type: "content_block_start", index: 0, content_block: { type: "compaction", content: null } },
{ type: "content_block_delta", index: 0, delta: { type: "compaction_delta", content: summary } },
{ type: "content_block_stop", index: 0 },
{
type: "message_delta",
delta: { stop_reason: "compaction" },
usage: {
input_tokens: 1000,
output_tokens: 5,
iterations: [
{ type: "compaction", input_tokens: 50000, output_tokens: 1000, cache_read_input_tokens: 10 },
{ type: "message", input_tokens: 1000, output_tokens: 5 },
],
},
},
{ type: "message_stop" },
),
{ headers: { "content-type": "text/event-stream" } },
)
}),
),
).effect(
`${model.provider} replays ${summary === null ? "failed" : "successful"} compaction with billing and context usage`,
() =>
Effect.gen(function* () {
const request = LLM.request({
model,
prompt: "hello",
http: { headers: { "anthropic-beta": "existing-beta" } },
providerOptions: {
contextManagement: {
edits: [
{
type: "compact_20260112",
trigger: { type: "input_tokens", value: 50000 },
pauseAfterCompaction: true,
},
],
},
},
})
const first = yield* LLMClient.generate(request)
expect(first.finishReason.raw).toBe("compaction")
expect(first.message.content).toEqual([{ type: "compaction", provider: model.provider, text: summary }])
expect(first.text).toBe("")
expect(first.usage?.inputTokens).toBe(51010)
expect(first.usage?.outputTokens).toBe(1005)
expect(first.usage?.totalTokens).toBe(52015)
expect(first.usage?.contextTokens).toBe(1000)
const codec = Schema.fromJsonString(Message)
const message = Schema.decodeSync(codec)(Schema.encodeSync(codec)(first.message))
yield* LLMClient.generate(
LLMRequest.update(request, {
providerOptions: {},
messages: [...request.messages, message, Message.user("continue")],
}),
)
}),
)
}
}
for (const events of [
[{ type: "content_block_start", index: 0, content_block: { type: "compaction", content: 42 } }],
[{ type: "content_block_delta", index: 0, delta: { type: "compaction_delta", content: "no start" } }],
[
{ type: "content_block_start", index: 0, content_block: { type: "compaction", content: null } },
{ type: "message_stop" },
],
]) {
testEffect(fixedResponse(sseEvents(...events))).effect(
`rejects malformed compaction lifecycle: ${JSON.stringify(events)}`,
() =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(
LLM.request({ model: Anthropic.configure({ apiKey: "test" }).model("claude-opus-4-6"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.reason.http?.status).toBe(200)
}),
)
}
@@ -0,0 +1,89 @@
import { EventStreamCodec } from "@smithy/eventstream-codec"
import { fromUtf8, toUtf8 } from "@smithy/util-utf8"
import { expect } from "bun:test"
import { Effect } from "effect"
import { LLM, LLMRequest, Message } from "../../src/index.js"
import { LLMClient } from "../../src/route/client.js"
import { AmazonBedrock } from "../../src/providers/index.js"
import { testEffect } from "../lib/effect.js"
import { dynamicResponse, fixedResponse } from "../lib/http.js"
const codec = new EventStreamCodec(toUtf8, fromUtf8)
const frame = (event: object) =>
codec.encode({
headers: { ":message-type": { type: "string", value: "event" }, ":event-type": { type: "string", value: "chunk" } },
body: new TextEncoder().encode(JSON.stringify({ bytes: Buffer.from(JSON.stringify(event)).toString("base64") })),
})
const response = Buffer.concat(
[
{ type: "message_start", message: { usage: { input_tokens: 60000 } } },
{ type: "content_block_start", index: 0, content_block: { type: "compaction", content: null } },
{ type: "content_block_delta", index: 0, delta: { type: "compaction_delta", content: "Summary" } },
{ type: "content_block_stop", index: 0 },
{ type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
{ type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "Hello" } },
{ type: "content_block_stop", index: 1 },
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 10 } },
{ type: "message_stop" },
].map(frame),
)
for (const auth of [
{ apiKey: "test" },
{ credentials: { accessKeyId: "test", secretAccessKey: "test", region: "us-west-2" } },
]) {
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
expect(request.url).toBe(
"https://bedrock-runtime.us-west-2.amazonaws.com/model/anthropic.claude-opus-4-6-v1%3A0/invoke-with-response-stream",
)
expect(request.headers.authorization).toStartWith(auth.apiKey ? "Bearer test" : "AWS4-HMAC-SHA256")
const body = JSON.parse(text)
expect(body.model).toBeUndefined()
expect(body.stream).toBeUndefined()
expect(body.anthropic_version).toBe("bedrock-2023-05-31")
expect(body.anthropic_beta).toEqual(["compact-2026-01-12"])
expect(body.context_management.edits).toEqual([{ type: "compact_20260112" }])
if (body.messages.length > 1)
expect(body.messages[1].content[0]).toEqual({ type: "compaction", content: "Summary" })
return respond(response, { headers: { "content-type": "application/vnd.amazon.eventstream" } })
}),
),
).effect(`Bedrock Messages compaction round trip with ${auth.apiKey ? "bearer" : "SigV4"} authentication`, () =>
Effect.gen(function* () {
const model = AmazonBedrock.configure({ ...auth, region: "us-west-2" }).messages("anthropic.claude-opus-4-6-v1:0")
const request = LLM.request({
model,
prompt: "hello",
providerOptions: { contextManagement: { edits: [{ type: "compact_20260112" }] } },
})
const first = yield* LLMClient.generate(request)
expect(first.text).toBe("Hello")
expect(first.message.content.map((part) => part.type)).toEqual(["compaction", "text"])
yield* LLMClient.generate(
LLMRequest.update(request, { messages: [...request.messages, first.message, Message.user("continue")] }),
)
}),
)
}
testEffect(
fixedResponse(
codec.encode({
headers: {
":message-type": { type: "string", value: "exception" },
":exception-type": { type: "string", value: "throttlingException" },
},
body: new TextEncoder().encode(JSON.stringify({ message: "Too many requests", trace: "keep-original" })),
}),
),
).effect("Bedrock Messages retains the original exception frame", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(
LLM.request({ model: AmazonBedrock.configure({ apiKey: "test" }).messages("claude"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason.body).toContain("keep-original")
expect(error.reason.http?.status).toBe(200)
}),
)
@@ -0,0 +1,50 @@
import { expect } from "bun:test"
import { Effect, Stream } from "effect"
import { LLM, LLMRequest, Message } from "../../src/index.js"
import { LLMClient, WebSocketTransport } from "../../src/route.js"
import { OpenAI } from "../../src/providers.js"
import { testEffect } from "../lib/effect.js"
import { fixedResponse } from "../lib/http.js"
testEffect(fixedResponse("unexpected HTTP fallback")).effect(
"WebSocket responses preserve compaction options and replay state",
() =>
Effect.gen(function* () {
const checkpoint = { type: "compaction", id: "cmp_ws", encrypted_content: "opaque" }
const sent: unknown[] = []
const webSocket = WebSocketTransport.makeDirect({
open: () =>
Effect.succeed({
sendText: (message) =>
Effect.sync(() => {
const body = JSON.parse(message)
expect(body.context_management).toEqual([{ type: "compaction", compact_threshold: 100000 }])
expect(body.stream).toBeUndefined()
if (sent.length) expect(body.input[1]).toEqual(checkpoint)
sent.push(body)
}),
messages: Stream.fromIterable(
[
{ type: "response.created", response: { id: "resp_ws" } },
{ type: "response.output_item.done", item: checkpoint },
{ type: "response.completed", response: { id: "resp_ws", output: [checkpoint] } },
].map((event) => JSON.stringify(event)),
),
close: Effect.void,
}),
})
const request = LLM.request({
model: OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"),
prompt: "hello",
providerOptions: { contextManagement: [{ type: "compaction", compactThreshold: 100000 }] },
})
const first = yield* LLMClient.generate(request, { webSocket })
expect(first.message.content).toHaveLength(1)
expect(first.message.content[0]?.type).toBe("compaction")
yield* LLMClient.generate(
LLMRequest.update(request, { messages: [...request.messages, first.message, Message.user("continue")] }),
{ webSocket },
)
expect(sent).toHaveLength(2)
}),
)
@@ -0,0 +1,91 @@
import { expect } from "bun:test"
import { Effect } from "effect"
import { LLM, LLMRequest, Message } from "../../src/index.js"
import { LLMClient } from "../../src/route/client.js"
import { OpenAI, XAI, Anthropic } from "../../src/providers.js"
import { recordedTests } from "../recorded-test.js"
const history = [
Message.user("Remember the project codename COPPER-ORBIT-42."),
Message.assistant(
"The project codename is COPPER-ORBIT-42. " + "We reviewed the implementation and tests. ".repeat(1000),
),
]
for (const provider of [
{
id: "openai",
key: "OPENAI_API_KEY",
model: OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY ?? "fixture" }).responses("gpt-5.3-codex"),
},
{
id: "xai",
key: "XAI_API_KEY",
model: XAI.configure({ apiKey: process.env.XAI_API_KEY ?? "fixture" }).responses("grok-4.6"),
},
]) {
recordedTests({ prefix: `${provider.id}-compaction`, provider: provider.id, requires: [provider.key] }).effect(
"compacts and continues with the provider checkpoint",
() =>
Effect.gen(function* () {
const request = LLM.request({ model: provider.model, messages: history, generation: { maxTokens: 1024 } })
const compacted = yield* LLMClient.compact(request)
const result = yield* LLMClient.generate(
LLMRequest.update(request, {
messages: [
...compacted.messages,
Message.user("What is the project codename? Reply only with the codename."),
],
}),
)
expect(result.text).toContain("COPPER-ORBIT-42")
}),
120000,
)
}
recordedTests({
prefix: "anthropic-compaction",
provider: "anthropic",
requires: ["ANTHROPIC_API_KEY"],
options: { redact: { allowRequestHeaders: ["anthropic-version", "anthropic-beta"] } },
}).effect(
"automatically compacts and continues after a pause",
() =>
Effect.gen(function* () {
const model = Anthropic.configure({ apiKey: process.env.ANTHROPIC_API_KEY ?? "fixture" }).model(
"claude-sonnet-4-6",
)
const request = LLM.request({
model,
messages: [
Message.user(
"Remember the project codename COPPER-ORBIT-42. " +
"The implementation and tests were reviewed. ".repeat(10000),
),
],
generation: { maxTokens: 4096 },
providerOptions: {
contextManagement: {
edits: [
{ type: "compact_20260112", trigger: { type: "input_tokens", value: 50000 }, pauseAfterCompaction: true },
],
},
},
})
const first = yield* LLMClient.generate(request)
expect(first.finishReason.raw).toBe("compaction")
expect(first.message.content.some((part) => part.type === "compaction")).toBe(true)
const result = yield* LLMClient.generate(
LLMRequest.update(request, {
messages: [
...request.messages,
first.message,
Message.user("What is the project codename? Reply only with the codename."),
],
}),
)
expect(result.text).toContain("COPPER-ORBIT-42")
}),
120000,
)
@@ -0,0 +1,136 @@
import { expect } from "bun:test"
import { Effect, Schema } from "effect"
import { LLM, LLMRequest, Message } from "../../src/index.js"
import { LLMClient } from "../../src/route/client.js"
import { OpenAI, Azure, XAI } from "../../src/providers/index.js"
import { testEffect } from "../lib/effect.js"
import { dynamicResponse, fixedResponse } from "../lib/http.js"
import { sseEvents } from "../lib/sse.js"
const checkpoint = { type: "compaction", id: "cmp_1", encrypted_content: "opaque" }
const response = sseEvents(
{ type: "response.output_item.done", item: checkpoint },
{
type: "response.completed",
response: { id: "resp_1", output: [checkpoint], usage: { input_tokens: 10, output_tokens: 2, total_tokens: 12 } },
},
)
for (const model of [
OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"),
Azure.configure({ apiKey: "test", resourceName: "test" }).responses("deployment"),
]) {
testEffect(
dynamicResponse(({ text, respond }) =>
Effect.sync(() => {
const body = JSON.parse(text)
expect(body.context_management).toEqual([{ type: "compaction", compact_threshold: 100000 }])
expect(body.store).toBe(false)
if (body.input.length > 1) expect(body.input[1]).toEqual(checkpoint)
return respond(response, { headers: { "content-type": "text/event-stream" } })
}),
),
).effect(`${model.provider} compaction survives generation, serialization, and a second request`, () =>
Effect.gen(function* () {
const request = LLM.request({
model,
prompt: "hello",
providerOptions: { contextManagement: [{ type: "compaction", compactThreshold: 100000 }] },
})
const first = yield* LLMClient.generate(request)
expect(first.message.content).toHaveLength(1)
expect(first.message.content[0]?.type).toBe("compaction")
expect(first.text).toBe("")
const codec = Schema.fromJsonString(Message)
const message = Schema.decodeSync(codec)(Schema.encodeSync(codec)(first.message))
yield* LLMClient.generate(
LLMRequest.update(request, { messages: [...request.messages, message, Message.user("continue")] }),
)
const rejected = yield* LLMClient.generate(
LLMRequest.update(request, {
model: XAI.configure({ apiKey: "test" }).responses("grok-4.6"),
providerOptions: {},
messages: [message],
}),
).pipe(Effect.flip)
expect(rejected.reason._tag).toBe("InvalidRequest")
}),
)
}
testEffect(fixedResponse(sseEvents({ type: "response.completed", response: { output: [checkpoint] } }))).effect(
"recovers compaction from the terminal output when item completion is absent",
() =>
Effect.gen(function* () {
const result = yield* LLMClient.generate(
LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"), prompt: "hello" }),
)
expect(result.message.content).toHaveLength(1)
expect(result.message.content[0]?.type).toBe("compaction")
}),
)
testEffect(
fixedResponse(sseEvents({ type: "response.output_item.done", item: { type: "compaction", id: "cmp_bad" } })),
).effect("rejects incomplete compaction payloads without publishing a checkpoint", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(
LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.reason.body).toContain("cmp_bad")
}),
)
const textItem = {
type: "message",
id: "msg_after",
role: "assistant",
content: [{ type: "output_text", text: "After checkpoint" }],
}
for (const completed of [false, true]) {
testEffect(
fixedResponse(
sseEvents(
{ type: "response.output_item.added", output_index: 0, item: { type: "compaction", id: checkpoint.id } },
...(completed ? [{ type: "response.output_item.done", output_index: 0, item: checkpoint }] : []),
{ type: "response.output_item.added", output_index: 1, item: textItem },
{ type: "response.output_text.delta", output_index: 1, item_id: textItem.id, delta: "After checkpoint" },
{ type: "response.output_item.done", output_index: 1, item: textItem },
{ type: "response.completed", response: { id: "resp_1", output: [checkpoint, textItem] } },
),
),
).effect(completed ? "keeps streamed checkpoints before later text" : "rejects order-unsafe terminal recovery", () =>
Effect.gen(function* () {
const request = LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("fixture"), prompt: "hello" })
if (completed) {
const response = yield* LLMClient.generate(request)
expect(response.message.content.map((part) => part.type)).toEqual(["compaction", "text"])
return
}
const error = yield* LLMClient.generate(request).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.message).toContain("Cannot recover a compaction checkpoint")
expect(error.reason.body).toContain("response.completed")
expect(error.reason.http?.status).toBe(200)
}),
)
}
testEffect(
fixedResponse(
sseEvents({
type: "response.completed",
response: { output: [{ type: "compaction", encrypted_content: "opaque" }] },
}),
),
).effect("rejects terminal checkpoints missing an id", () =>
Effect.gen(function* () {
const error = yield* LLMClient.generate(
LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("fixture"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.message).toContain("missing its id")
}),
)
@@ -0,0 +1,377 @@
import { expect } from "bun:test"
import { Effect, Schema } from "effect"
import { LLM, LLMRequest, Message } from "../../src/index.js"
import { LLMClient, Route } from "../../src/route/client.js"
import { Auth } from "../../src/route/auth.js"
import { Endpoint } from "../../src/route/endpoint.js"
import { OpenAIResponses } from "../../src/protocols/openai-responses.js"
import { OpenAI, Azure, XAI, Anthropic, AmazonBedrockMantle } from "../../src/providers/index.js"
import { testEffect } from "../lib/effect.js"
import { dynamicResponse, fixedResponse } from "../lib/http.js"
import { sseEvents } from "../lib/sse.js"
const checkpoint = { type: "compaction", id: "cmp_1", encrypted_content: "opaque" }
const retained = {
type: "message",
role: "user",
id: "msg_1",
status: "completed",
content: [{ type: "input_text", text: "retained" }],
}
const output = [retained, checkpoint]
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
expect(request.headers["x-deployment"]).toBe("fixture")
expect(request.headers["x-override"]).toBe("request")
expect(request.headers["x-default"]).toBe("configured")
expect(request.headers.authorization).toBe("Bearer test")
expect(new URL(request.url).searchParams.get("api-version")).toBe("fixture")
expect(new URL(request.url).searchParams.get("trace")).toBe("request")
if (new URL(request.url).pathname.endsWith("/compact")) {
expect(JSON.parse(text)).toEqual({
model: "overlaid",
input: [{ role: "user", content: [{ type: "input_text", text: "hello" }] }],
instructions: "request instructions",
previous_response_id: "resp_previous",
})
return respond(JSON.stringify({ object: "response.compaction", output }))
}
return respond(sseEvents({ type: "response.completed", response: { id: "resp_1" } }))
}),
),
).effect("generation and compaction share deployment headers, defaults, auth, query, and middleware", () =>
Effect.gen(function* () {
const headers: string[] = []
const middleware: string[] = []
const route = Route.make({
id: "compaction-headers",
provider: "openai",
protocol: OpenAIResponses.protocol,
compact: OpenAIResponses.route.compact,
transport: OpenAIResponses.httpTransport,
endpoint: Endpoint.path(({ body }) => `/${body.model}/responses`, {
baseURL: "https://example.com",
query: { "api-version": "fixture" },
}),
auth: Auth.bearer("test"),
headers: ({ request }) => {
expect(request.providerOptions?.store).toBe(false)
headers.push(String(request.model.id))
return { "x-deployment": "fixture", "x-override": "route" }
},
defaults: {
headers: { "x-default": "configured", "x-override": "configured" },
providerOptions: { store: false },
http: { body: { instructions: "default instructions" } },
},
})
const request = LLM.request({
model: route.model({ id: "fixture" }),
prompt: "hello",
system: "system instructions",
http: {
headers: { "x-override": "request" },
query: { trace: "request" },
body: {
model: "overlaid",
instructions: "request instructions",
previous_response_id: "resp_previous",
store: false,
stream: true,
},
},
})
const options: Parameters<typeof LLMClient.compact>[1] = {
http: (request, next) => {
middleware.push(new URL(request.url).pathname)
return next(request)
},
}
yield* LLMClient.generate(request, options)
yield* LLMClient.compact(request, options)
expect(headers).toEqual(["fixture", "fixture"])
expect(middleware).toEqual(["/fixture/responses", "/fixture/responses/compact"])
}),
)
for (const model of [
OpenAI.configure({ apiKey: "test" }).responses("fixture"),
Azure.configure({ apiKey: "test", resourceName: "test" }).responses("fixture"),
XAI.configure({ apiKey: "test" }).responses("fixture"),
]) {
const item = {
type: model.provider === "xai" ? "x_search_call" : "computer_call",
id: "hosted_1",
status: "completed",
}
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
expect(new URL(request.url).pathname).toEndWith("/responses/compact")
expect(JSON.parse(text)).toEqual({ model: "fixture", input: [item], instructions: "Keep the context" })
return respond(JSON.stringify({ object: "response.compaction", output: [checkpoint] }))
}),
),
).effect(`${model.provider} compacts provider-specific history without lowering generation settings`, () =>
Effect.gen(function* () {
const request = LLM.request({
model,
system: "Keep the context",
messages: [
Message.assistant({
type: "tool-result",
id: item.id,
name: item.type,
result: { type: "json", value: item },
providerExecuted: true,
providerMetadata: { [model.route.providerMetadataKey ?? model.provider]: { itemId: item.id } },
}),
],
})
for (const candidate of [
LLMRequest.update(request, {
tools: [
{ name: "unsupported", description: "Generation only", inputSchema: {}, native: { unsupported: {} } },
],
}),
LLMRequest.update(request, { providerOptions: { contextManagement: "invalid-generation-option" } }),
]) {
const error = yield* LLMClient.generate(candidate).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidRequest")
const response = yield* LLMClient.compact(candidate)
expect(response.messages[0]?.content[0]?.type).toBe("compaction")
}
}),
)
}
const retainedItems = [
retained,
{
type: "message",
id: "msg_assistant",
role: "assistant",
status: "completed",
phase: "commentary",
content: [
{ type: "output_text", text: "First" },
{ type: "output_text", text: "Second" },
],
},
{
type: "reasoning",
id: "rs_1",
summary: [
{ type: "summary_text", text: "Thinking" },
{ type: "summary_text", text: "More thinking" },
],
encrypted_content: "reasoning-state",
},
{ type: "reasoning", id: "rs_2", summary: [], encrypted_content: "hidden-reasoning" },
{
type: "message",
id: "msg_media",
role: "user",
content: [
{ type: "input_image", image_url: "https://example.com/image.png" },
{ type: "input_file", filename: "report.pdf", file_data: "data:application/pdf;base64,cGRm" },
{ type: "input_file", filename: "other.pdf", file_url: "https://example.com/report.pdf" },
],
},
checkpoint,
]
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
if (new URL(request.url).pathname.endsWith("/compact"))
return respond(JSON.stringify({ object: "response.compaction", output: retainedItems }))
expect(JSON.parse(text).input).toEqual(retainedItems)
return respond(sseEvents({ type: "response.completed", response: { id: "resp_1" } }), {
headers: { "content-type": "text/event-stream" },
})
}),
),
).effect("retained messages, reasoning, and media are ordinary typed conversation parts", () =>
Effect.gen(function* () {
const request = LLM.request({
model: OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"),
prompt: "hello",
})
const compacted = yield* LLMClient.compact(request)
expect(compacted.messages.map((message) => message.role)).toEqual([
"user",
"assistant",
"assistant",
"assistant",
"user",
"assistant",
])
expect(compacted.messages[1]?.content).toEqual([
{ type: "text", text: "First" },
{ type: "text", text: "Second" },
])
expect(compacted.messages[2]?.content.map((part) => part.type)).toEqual(["reasoning", "reasoning"])
expect(compacted.messages[4]?.content.map((part) => part.type)).toEqual(["media", "media", "media"])
const codec = Schema.fromJsonString(Schema.Array(Message))
const messages = Schema.decodeSync(codec)(Schema.encodeSync(codec)(compacted.messages))
yield* LLMClient.generate(LLMRequest.update(request, { messages }))
}),
)
for (const item of [
{ type: "unknown_provider_item", data: "do not hide in a compaction part" },
{
type: "message",
role: "user",
content: [{ type: "input_image", image_url: "https://example.com/image.png", detail: 42 }],
},
{ type: "message", role: "user", content: [] },
{
type: "message",
role: "assistant",
content: [{ type: "input_image", image_url: "https://example.com/image.png" }],
},
{ type: "message", role: "user", content: [{ type: "input_file", filename: "missing.pdf" }] },
]) {
testEffect(fixedResponse(JSON.stringify({ object: "response.compaction", output: [item, checkpoint] }))).effect(
`rejects unsupported compact output: ${JSON.stringify(item)}`,
() =>
Effect.gen(function* () {
const error = yield* LLMClient.compact(
LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.reason.body).toContain(JSON.stringify(item))
expect(error.reason.http?.status).toBe(200)
}),
)
}
for (const model of [
OpenAI.configure({ apiKey: "test" }).responses("fixture"),
Azure.configure({ apiKey: "test", resourceName: "test" }).responses("fixture"),
XAI.configure({ apiKey: "test" }).responses("fixture"),
]) {
const images = [undefined, "low", "high", "auto"].map((detail) => ({
type: "input_image",
image_url: "https://example.com/image.png",
...(detail === undefined ? {} : { detail }),
}))
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
if (new URL(request.url).pathname.endsWith("/compact"))
return respond(
JSON.stringify({
object: "response.compaction",
output: [{ type: "message", role: "user", content: images }, checkpoint],
}),
)
expect(JSON.parse(text).input[0].content).toEqual(images)
return respond(sseEvents({ type: "response.completed", response: { id: "resp_1" } }))
}),
),
).effect(`${model.provider} preserves retained image detail through serialization and replay`, () =>
Effect.gen(function* () {
const request = LLM.request({ model, prompt: "hello" })
const compacted = yield* LLMClient.compact(request)
const codec = Schema.fromJsonString(Schema.Array(Message))
const messages = Schema.decodeSync(codec)(Schema.encodeSync(codec)(compacted.messages))
yield* LLMClient.generate(LLMRequest.update(request, { messages }))
}),
)
}
testEffect(fixedResponse("must not execute")).effect("xAI rejects automatic compaction options", () =>
Effect.gen(function* () {
const request = LLMRequest.update(
LLM.request({ model: XAI.configure({ apiKey: "test" }).responses("grok-4.6"), prompt: "hello" }),
{ providerOptions: { contextManagement: [{ type: "compaction" }] } },
)
const error = yield* LLMClient.generate(request).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidRequest")
expect(error.message).toContain("LLMClient.compact")
}),
)
for (const model of [
OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"),
Azure.configure({ apiKey: "test", resourceName: "test" }).responses("deployment"),
XAI.configure({ apiKey: "test" }).responses("grok-4.6"),
]) {
testEffect(
dynamicResponse(({ request, text, respond }) =>
Effect.sync(() => {
const body = JSON.parse(text)
expect(request.method).toBe("POST")
expect(request.headers[model.provider === "azure" ? "api-key" : "authorization"]).toBe(
model.provider === "azure" ? "test" : "Bearer test",
)
if (new URL(request.url).pathname.endsWith("/responses/compact")) {
expect(body).toEqual({
model: model.id,
input: [{ role: "user", content: [{ type: "input_text", text: "original" }] }],
instructions: "system",
})
return respond(
JSON.stringify({
object: "response.compaction",
output,
usage: { input_tokens: 1000, output_tokens: 10, total_tokens: 1010 },
}),
{ headers: { "content-type": "application/json" } },
)
}
expect(new URL(request.url).pathname.endsWith("/responses")).toBe(true)
expect(body.input).toEqual([...output, { role: "user", content: [{ type: "input_text", text: "continue" }] }])
return respond(sseEvents({ type: "response.completed", response: { id: "resp_1", output: [] } }), {
headers: { "content-type": "text/event-stream" },
})
}),
),
).effect(`${model.provider} explicitly compacts and replays the entire canonical window`, () =>
Effect.gen(function* () {
const request = LLM.request({ model, prompt: "original", system: "system", http: { body: { store: false } } })
const compacted = yield* LLMClient.compact(request)
expect(compacted.usage?.totalTokens).toBe(1010)
expect(compacted.messages.map((message) => message.role)).toEqual(["user", "assistant"])
expect(compacted.messages[0]?.content).toEqual([{ type: "text", text: "retained" }])
expect(compacted.messages[1]?.content).toEqual([
{ type: "compaction", provider: model.provider, id: "cmp_1", encrypted: "opaque" },
])
const codec = Schema.fromJsonString(Schema.Array(Message))
const messages = Schema.decodeSync(codec)(Schema.encodeSync(codec)(compacted.messages))
yield* LLMClient.generate(LLMRequest.update(request, { messages: [...messages, Message.user("continue")] }))
}),
)
}
for (const model of [
Anthropic.configure({ apiKey: "test" }).model("claude-opus-4-6"),
AmazonBedrockMantle.configure({ apiKey: "test" }).responses("model"),
]) {
testEffect(fixedResponse("must not execute")).effect(
`${model.route.id} does not inherit an unsupported compact endpoint`,
() =>
Effect.gen(function* () {
const error = yield* LLMClient.compact(LLM.request({ model, prompt: "hello" })).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidRequest")
}),
)
}
testEffect(
fixedResponse(JSON.stringify({ object: "response.compaction", output: [retained], debug: "original payload" })),
).effect("invalid explicit compaction preserves the original response and HTTP context", () =>
Effect.gen(function* () {
const error = yield* LLMClient.compact(
LLM.request({ model: OpenAI.configure({ apiKey: "test" }).responses("gpt-5.3-codex"), prompt: "hello" }),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidProviderOutput")
expect(error.reason.body).toContain("original payload")
expect(error.reason.http?.status).toBe(200)
}),
)
@@ -8,30 +8,6 @@ story.beforeEach(async ({ mount }) => {
await expect(component.getByRole("textbox", { name: "Prompt", exact: true })).toBeVisible()
})
story("spaces the first mobile message without changing desktop spacing", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
await page.evaluate(async (fixture) => {
const { mountTimelineVirtualizer } = await import(fixture)
mountTimelineVirtualizer({ count: 1, rowHeight: 60, immediate: true })
}, fixture)
const root = page.getByTestId("timeline-virtualizer-fixture")
await root.getByRole("button", { name: "Complete Markdown", exact: true }).click()
const content = root.locator("[data-timeline-virtual-content]")
await expect(content).toHaveCSS("visibility", "visible")
const gap = () =>
root.locator('[data-timeline-key="user-message:message-0"]').evaluate((element) => {
const viewport = element.closest("[data-scrollable]")!
return element.getBoundingClientRect().top - viewport.getBoundingClientRect().top
})
await expect.poll(gap).toBe(16)
await root.evaluate((element) => element.setAttribute("dir", "rtl"))
await expect.poll(gap).toBe(16)
await page.setViewportSize({ width: 1280, height: 900 })
await expect.poll(gap).toBe(0)
await page.setViewportSize({ width: 390, height: 844 })
await expect.poll(gap).toBe(16)
})
story("bounds the cheap suffix and reveals only ready measured rows", async ({ page }) => {
await page.evaluate(async (fixture) => {
const { mountTimelineVirtualizer } = await import(fixture)
@@ -1,110 +0,0 @@
import { expect, test } from "@playwright/test"
import { fixture, pageMessages } from "../performance/timeline/session-timeline-stress.fixture"
import { stressSessionHref } from "../performance/timeline/timeline-test-helpers"
import { mockOpenCodeServer } from "../utils/mock-server"
for (const direction of ["ltr", "rtl"] as const) {
test(`mobile files browse, search, switch, and close shared file tabs in ${direction}`, async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: fixture.project,
sessions: fixture.sessions,
provider: fixture.provider,
pageMessages,
fileList: (path) =>
path
? []
: ["first.ts", "second.ts"].map((name) => ({
name,
path: name,
absolute: `${fixture.directory}/${name}`,
type: "file",
ignored: false,
})),
fileContent: (path) => `contents:${path}`,
findFiles: ({ query }) => ["first.ts", "second.ts"].filter((path) => path.includes(query)),
})
await page.goto(stressSessionHref(fixture.targetID))
const navigation = page.getByRole("tablist", { name: "Session view", exact: true })
await navigation.getByRole("tab", { name: "Files", exact: true }).click()
const files = page.locator('[data-slot="session-mobile-files"]')
await expect(files.getByRole("button", { name: "first.ts", exact: true })).toBeVisible()
await page.evaluate((direction) => (document.documentElement.dir = direction), direction)
await expect(files.locator('[data-slot="session-mobile-files-header"]')).toHaveCSS("border-bottom-width", "0px")
await expect
.poll(() =>
files.getByRole("tablist", { name: "Open files", exact: true }).evaluate((element) => {
const header = element.closest('[data-slot="session-mobile-files-header"]')!
const separator = getComputedStyle(element, "::before")
return {
height: separator.height,
fullWidth: parseFloat(separator.width) === header.clientWidth,
start: separator.insetInlineStart,
bottom: separator.bottom,
}
}),
)
.toEqual({ height: "1px", fullWidth: true, start: "0px", bottom: "0px" })
await files.getByRole("button", { name: "first.ts", exact: true }).click()
await expect(files.getByText("contents:first.ts", { exact: true })).toBeVisible()
await files.locator('[data-column-number="1"]').click()
const editor = files.locator('[data-component="line-comment-v2"][data-variant="editor"]')
await expect(editor.getByRole("textbox")).toBeVisible()
for (const width of [390, 700]) {
await page.setViewportSize({ width, height: 844 })
await expect
.poll(async () => {
const panel = await files.boundingBox()
const comment = await editor.boundingBox()
if (!panel || !comment) return false
return Math.abs(comment.x - panel.x - 12) < 2 && Math.abs(comment.width - panel.width + 24) < 2
})
.toBe(true)
}
await editor.getByRole("textbox").fill("Full-width file comment")
await editor.getByRole("button", { name: "Comment", exact: true }).click()
const comment = files.locator('[data-component="line-comment-v2"][data-variant="display"]')
await expect(comment).toContainText("Full-width file comment")
await expect
.poll(async () => {
const panel = await files.boundingBox()
const card = await comment.boundingBox()
if (!panel || !card) return false
return Math.abs(card.x - panel.x - 12) < 2 && Math.abs(card.width - panel.width + 24) < 2
})
.toBe(true)
await page.setViewportSize({ width: 390, height: 844 })
await expect(files.getByRole("combobox", { name: "Filter files", exact: true })).toBeHidden()
await files.getByRole("button", { name: "All files", exact: true }).click()
await files.getByRole("combobox", { name: "Filter files", exact: true }).fill("second")
await files.getByRole("option", { name: "second.ts", exact: true }).click()
await expect(files.getByText("contents:second.ts", { exact: true })).toBeVisible()
const openTabs = files.getByRole("tablist", { name: "Open files", exact: true })
await expect(openTabs.getByRole("tab")).toHaveText(["first.ts", "second.ts"])
await expect
.poll(() =>
openTabs.getByRole("tab", { name: "second.ts", exact: true }).evaluate((element) => {
const tab = element.closest('[data-slot="tabs-v2-trigger-wrapper"]')!
const header = element.closest('[data-slot="session-mobile-files-header"]')!
return Math.abs(tab.getBoundingClientRect().bottom - header.getBoundingClientRect().bottom) < 1
}),
)
.toBe(true)
await openTabs.getByRole("tab", { name: "first.ts", exact: true }).click()
await expect(files.getByText("contents:first.ts", { exact: true })).toBeVisible()
await navigation.getByRole("tab", { name: "Session", exact: true }).click()
await navigation.getByRole("tab", { name: "Files", exact: true }).click()
await expect(files.getByText("contents:first.ts", { exact: true })).toBeVisible()
await files
.locator('[data-slot="tabs-v2-trigger-wrapper"]')
.filter({ has: page.getByRole("tab", { name: "first.ts", exact: true }) })
.getByRole("button", { name: "Close tab", exact: true })
.click()
await expect(openTabs.getByRole("tab")).toHaveText(["second.ts"])
await expect(files.getByText("contents:second.ts", { exact: true })).toBeVisible()
await files.getByRole("button", { name: "Close tab", exact: true }).click()
await expect(files.getByRole("combobox", { name: "Filter files", exact: true })).toBeVisible()
await expect(openTabs.getByRole("tab")).toHaveCount(0)
})
}
@@ -1,43 +0,0 @@
import { expect, test } from "@playwright/test"
import { fixture, pageMessages } from "../performance/timeline/session-timeline-stress.fixture"
import { stressSessionHref } from "../performance/timeline/timeline-test-helpers"
import { mockOpenCodeServer } from "../utils/mock-server"
test("opening changed files selects the requested tab before file loading completes", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
const loading = Promise.withResolvers<void>()
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: fixture.project,
sessions: fixture.sessions,
provider: fixture.provider,
pageMessages,
fileList: () => [],
fileContent: async (path) => {
if (path === "second.ts") await loading.promise
return `contents:${path}`
},
vcsDiff: ["first.ts", "second.ts"].map((file) => ({
file,
status: "modified",
additions: 1,
deletions: 1,
patch: `diff --git a/${file} b/${file}\n--- a/${file}\n+++ b/${file}\n@@ -1 +1 @@\n-before\n+after\n`,
})),
})
await page.goto(stressSessionHref(fixture.targetID))
const navigation = page.getByRole("tablist", { name: "Session view", exact: true })
const files = page.locator('[data-slot="session-mobile-files"]')
for (const file of ["first.ts", "second.ts", "first.ts", "second.ts"]) {
await navigation.getByRole("tab", { name: "Changes", exact: true }).click()
const diff = page.locator(`[data-component="session-review"] [data-file="${file}"]`)
const header = diff.getByRole("button", { name: file, exact: true })
await expect(header).toBeEnabled()
if ((await header.getAttribute("aria-expanded")) === "false") await header.click()
await diff.getByRole("button", { name: "Open file", exact: true }).click()
await expect(navigation.getByRole("tab", { name: "Files", exact: true })).toHaveAttribute("aria-selected", "true")
await expect(files.getByRole("tab", { name: file, exact: true })).toHaveAttribute("aria-selected", "true")
if (file === "second.ts") loading.resolve()
await expect(files.getByText(`contents:${file}`, { exact: true })).toBeVisible()
}
})
@@ -1,138 +0,0 @@
import { expect, test } from "@playwright/test"
import { fixture } from "../performance/timeline/session-timeline-stress.fixture"
import { mockStressTimeline, stressSessionHref } from "../performance/timeline/timeline-test-helpers"
for (const direction of ["ltr", "rtl"] as const) {
test(`mobile change summaries appear only for expanded diffs in ${direction}`, async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
await mockStressTimeline(page, {
vcsDiff: [
{
file: "added.ts",
status: "added",
additions: 1,
deletions: 0,
patch:
"diff --git a/added.ts b/added.ts\n--- /dev/null\n+++ b/added.ts\n@@ -0,0 +1 @@\n+export const added = 1\n",
},
{
file: "removed.ts",
status: "deleted",
additions: 0,
deletions: 1,
patch:
"diff --git a/removed.ts b/removed.ts\n--- a/removed.ts\n+++ /dev/null\n@@ -1 +0,0 @@\n-export const removed = 1\n",
},
{
file: "modified.ts",
status: "modified",
additions: 1,
deletions: 1,
patch: `diff --git a/modified.ts b/modified.ts\n--- a/modified.ts\n+++ b/modified.ts\n@@ -1 +1 @@\n-export const value = 1\n+export const value = "${"long content ".repeat(30)}"\n`,
},
],
})
await page.goto(stressSessionHref(fixture.targetID))
await page.getByRole("tab", { name: "Changes", exact: true }).click()
const review = page.locator('[data-component="session-review"]')
await expect(review.getByRole("button", { name: "Expand all", exact: true })).toBeVisible()
await page.evaluate((direction) => (document.documentElement.dir = direction), direction)
await expect(review.locator('[data-file="added.ts"] [data-slot="accordion-trigger"]')).toHaveCSS(
"border-top-width",
"0px",
)
await expect(review.locator('[data-file="modified.ts"] [data-slot="accordion-trigger"]')).toHaveCSS(
"border-bottom-width",
"0px",
)
for (const change of [
{ file: "added.ts", status: "Added", additions: "+1", deletions: "-0" },
{ file: "removed.ts", status: "Removed", additions: "+0", deletions: "-1" },
{ file: "modified.ts", status: undefined, additions: "+1", deletions: "-1" },
]) {
const item = review.locator(`[data-file="${change.file}"]`)
const trigger = item.getByRole("button", { name: change.file, exact: true })
const summary = item.locator('[data-slot="session-review-change-summary"]')
await expect(trigger).toHaveAttribute("aria-expanded", "false")
await expect(trigger.locator('[data-component="diff-changes"]')).toHaveCount(0)
await expect(trigger.locator('[data-slot="session-review-change"]')).toHaveCount(0)
await expect(summary).toHaveCount(0)
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", "true")
if (change.file === "modified.ts") {
await expect(item.locator('[data-slot="accordion-content"]')).toHaveCSS("border-bottom-width", "0px")
await expect(trigger).not.toHaveCSS("border-bottom-width", "0px")
}
await expect(summary).toBeVisible()
await expect(summary.getByRole("button", { name: "Open file", exact: true })).toBeVisible()
await expect(summary.locator('[data-slot="diff-changes-additions"]')).toHaveText(change.additions)
await expect(summary.locator('[data-slot="diff-changes-deletions"]')).toHaveText(change.deletions)
if (change.status) await expect(summary.getByText(change.status, { exact: true })).toBeVisible()
await trigger.click()
await expect(trigger).toHaveAttribute("aria-expanded", "false")
await expect(summary).toHaveCount(0)
}
await expect(review.locator('[data-slot="session-review-view-button"]')).toHaveCount(0)
const modified = review.locator('[data-file="modified.ts"]')
await modified.getByRole("button", { name: "modified.ts", exact: true }).click()
await expect(modified.locator("[data-line-number-content]")).toHaveText(["1", "1"])
await expect(modified.locator("[data-diff]")).not.toHaveAttribute("data-disable-line-numbers")
await expect(modified.locator("[data-diff]")).toHaveAttribute("data-overflow", "wrap")
await expect(review.getByRole("button", { name: "Diff options", exact: true })).toHaveCount(0)
await page.keyboard.press("Control+,")
const settings = page.getByTestId("settings-screen")
const wrap = settings.getByRole("switch", { name: "Wrap lines", exact: true })
const wrapControl = settings.locator('[data-action="settings-mobile-diff-wrap"] [data-slot="switch-control"]')
await expect(wrap).toBeChecked()
await wrapControl.click()
await expect(wrap).not.toBeChecked()
await expect
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("settings.v3") ?? "{}").general?.mobileDiffWrap))
.toBe(false)
await settings.getByRole("button", { name: "Back to app", exact: true }).click()
await expect(modified.locator("[data-diff]")).toHaveAttribute("data-overflow", "scroll")
await expect
.poll(() => modified.locator("[data-code]").evaluate((element) => element.scrollWidth > element.clientWidth))
.toBe(true)
await modified.locator("[data-code]").evaluate((element) => {
element.scrollLeft = 100
})
await expect
.poll(() => modified.locator("[data-code]").evaluate((element) => Math.abs(element.scrollLeft)))
.toBeGreaterThan(0)
const navigation = page.getByRole("tablist", { name: "Session view", exact: true })
await navigation.getByRole("tab", { name: "Session", exact: true }).click()
await navigation.getByRole("tab", { name: "Changes", exact: true }).click()
await expect(modified.locator("[data-diff]")).toHaveAttribute("data-overflow", "scroll")
await page.keyboard.press("Control+,")
await expect(wrap).not.toBeChecked()
await wrapControl.click()
await expect(wrap).toBeChecked()
await expect
.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem("settings.v3") ?? "{}").general?.mobileDiffWrap))
.toBe(true)
await settings.getByRole("button", { name: "Back to app", exact: true }).click()
await expect(modified.locator("[data-diff]")).toHaveAttribute("data-overflow", "wrap")
const openFile = modified.getByRole("button", { name: "Open file", exact: true })
await expect(openFile).toBeVisible()
await expect
.poll(async () => {
const button = await openFile.boundingBox()
const summary = await modified.locator('[data-slot="session-review-change-summary"]').boundingBox()
if (!button || !summary) return false
return direction === "ltr"
? button.x > summary.x + summary.width / 2
: button.x + button.width < summary.x + summary.width / 2
})
.toBe(true)
await openFile.click()
await expect(
page.getByRole("tablist", { name: "Session view", exact: true }).getByRole("tab", { name: "Files", exact: true }),
).toHaveAttribute("aria-selected", "true")
const files = page.locator('[data-slot="session-mobile-files"]')
await expect(files.getByRole("tab", { name: "modified.ts", exact: true })).toHaveAttribute("aria-selected", "true")
await expect(files).toHaveAttribute("data-browsing", "false")
})
}
@@ -1,186 +0,0 @@
import { expect, test } from "@playwright/test"
import { fixture, pageMessages } from "../performance/timeline/session-timeline-stress.fixture"
import { installStressSessionTabs, stressSessionHref } from "../performance/timeline/timeline-test-helpers"
import { mockOpenCodeServer } from "../utils/mock-server"
for (const position of ["top", "bottom"] as const) {
test(`mobile session tabs switch views and keep the terminal cached with ${position} navigation`, async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 })
await mockOpenCodeServer(page, {
directory: fixture.directory,
project: fixture.project,
sessions: fixture.sessions,
provider: fixture.provider,
pageMessages,
fileList: () => [],
})
await installStressSessionTabs(page)
await page.addInitScript(
(position) =>
localStorage.setItem("settings.v3", JSON.stringify({ general: { mobileTitlebarPosition: position } })),
position,
)
await page.route("**/api/pty*", (route) =>
route.fulfill({
json: {
location: { directory: fixture.directory, project: { id: fixture.project.id, directory: fixture.directory } },
data: {
id: "pty_mobile_views",
title: "Terminal 1",
command: "sh",
args: [],
cwd: fixture.directory,
status: "running",
pid: 1,
},
},
}),
)
await page.routeWebSocket("**/api/pty/pty_mobile_views/connect", () => undefined)
await page.route("**/api/pty/pty_mobile_views/connect-token*", (route) =>
route.fulfill({
json: {
location: { directory: fixture.directory, project: { id: fixture.project.id, directory: fixture.directory } },
data: { ticket: "e2e-ticket", expires_in: 60 },
},
}),
)
await page.goto(stressSessionHref(fixture.targetID))
const tabs = page.getByRole("tablist", { name: "Session view", exact: true })
const navigation = page.locator('[data-slot="session-mobile-view-navigation"]')
const more = navigation.getByRole("button", { name: "More options", exact: true })
const picker = tabs.getByRole("tab", { selected: true })
const message = page.locator(
`[data-timeline-row="UserMessage"][data-message-id="${fixture.expected.targetMessageIDs.at(-1)}"]`,
)
const composer = page.getByRole("textbox", { name: "Prompt", exact: true })
await expect(picker).toHaveText("Session")
await expect(message).toBeVisible()
await expect(composer).toBeVisible()
await expect(tabs.getByRole("tab")).toHaveText(["Session", "Changes", "Files", "Terminal"])
await expect(tabs).toHaveCSS("padding-left", "0px")
await expect(tabs).toHaveCSS("padding-right", "0px")
await expect
.poll(async () => {
const bounds = await navigation.boundingBox()
return !!bounds && bounds.x >= 8 && bounds.x <= 9 && bounds.width >= 372 && bounds.width <= 374
})
.toBe(true)
await expect
.poll(async () => {
const bar = await tabs.boundingBox()
const input = await composer.boundingBox()
const panel = await page.locator('[data-slot="session-chat-panel"]').boundingBox()
return !!bar && !!input && !!panel && Math.abs(bar.y - panel.y) <= 1 && bar.y + bar.height <= input.y
})
.toBe(true)
await expect(page.locator("[data-session-title]")).toHaveCount(0)
await expect(page.locator('[data-slot="mobile-tabs-trigger"]')).toContainText(fixture.expected.targetTitle)
await page.getByRole("button", { name: "Tabs", exact: true }).click()
const drawer = page.getByRole("dialog", { name: "Tabs", exact: true })
await expect(drawer).toHaveAttribute("data-open", "")
await expect(drawer).not.toHaveAttribute("data-transitioning")
await expect(drawer.getByRole("button", { name: "Settings", exact: true })).toBeInViewport()
await drawer.getByRole("button", { name: "Settings", exact: true }).click()
await expect(page.getByTestId("settings-screen")).toBeVisible()
await page.getByRole("button", { name: "Back to app", exact: true }).click()
await page.getByRole("button", { name: "Tabs", exact: true }).click()
await expect(drawer).not.toHaveAttribute("data-transitioning")
await expect(drawer.getByRole("button", { name: "Settings", exact: true })).toBeInViewport()
await page.keyboard.press("Escape")
await expect(drawer).toBeHidden()
await more.click()
await page.getByRole("menuitem", { name: "Usage", exact: true }).click()
await expect(picker).toHaveCount(0)
await expect(page.getByText("Total Cost", { exact: true })).toBeVisible()
const usage = page.locator('[data-slot="session-usage-content"]')
await expect(usage).toHaveCSS("padding-top", "16px")
await expect(usage).toHaveCSS("padding-inline-start", "16px")
await expect(usage).toHaveCSS("padding-inline-end", "16px")
await expect(composer).toBeHidden()
await more.click()
await page.getByRole("menuitem", { name: "Status", exact: true }).click()
const status = page.getByRole("dialog", { name: "Status", exact: true })
await expect(status.getByRole("tab", { name: "MCP", exact: true })).toBeVisible()
await status.getByRole("tab", { name: "Plugins", exact: true }).click()
await expect(status.getByText("opencode.json", { exact: true })).toBeVisible()
await status.getByRole("button", { name: "Close", exact: true }).click()
await expect(status).toBeHidden()
await expect(more).toBeFocused()
await more.click()
await page.getByRole("menuitem", { name: "Session details", exact: true }).click()
const details = page.getByRole("dialog", { name: "Session details", exact: true })
await expect(details.getByText(fixture.project.name, { exact: true })).toBeVisible()
await expect(details.getByRole("button", { name: "No changes", exact: true })).toBeVisible()
await details.getByRole("button", { name: "Close", exact: true }).click()
await expect(details).toBeHidden()
await expect(more).toBeFocused()
await more.click()
await page.getByRole("menuitem", { name: "Session details", exact: true }).click()
await expect(details.getByRole("button", { name: "No changes", exact: true })).toBeVisible()
await expect(details).not.toHaveAttribute("data-transitioning")
await page.keyboard.press("Escape")
await expect(details).toBeHidden()
await expect(more).toBeFocused()
await more.click()
await page.getByRole("menuitem", { name: "Session details", exact: true }).click()
await details.getByRole("button", { name: "No changes", exact: true }).click()
await expect(details).toBeHidden()
await expect(picker).toHaveText("Changes")
await expect(page.getByText("No uncommitted changes yet", { exact: true })).toBeVisible()
await expect(page.locator('[data-slot="session-review-header"]')).toHaveCSS("height", "40px")
await expect(page.locator('[data-slot="session-review-header"]')).toHaveCSS("padding-left", "8px")
await expect(composer).toBeHidden()
await tabs.getByRole("tab", { name: "Files", exact: true }).click()
await expect(picker).toHaveText("Files")
await expect(page.getByRole("combobox", { name: "Filter files", exact: true })).toBeVisible()
await expect(composer).toBeHidden()
await tabs.getByRole("tab", { name: "Terminal", exact: true }).click()
const panel = page.locator("#terminal-panel")
await expect(panel).toHaveAttribute("data-opened", "true")
await expect(panel.getByRole("tab", { name: /Terminal 1/ })).toBeVisible()
await expect(panel.locator('[data-component="terminal"]')).toBeVisible()
await expect(panel.locator("textarea")).toBeEditable()
await expect(panel).toHaveCount(1)
await panel.evaluate((element) => element.setAttribute("data-cache-probe", "original"))
await expect(composer).toBeHidden()
await tabs.getByRole("tab", { name: "Session", exact: true }).click()
await expect(message).toBeVisible()
await expect(panel).toBeHidden()
await expect(panel).toHaveAttribute("inert", "")
await expect(panel).toHaveAttribute("data-cache-probe", "original")
await page.keyboard.press("Control+Backquote")
await expect(picker).toHaveText("Terminal")
await expect(panel).toBeVisible()
await expect(panel).toHaveAttribute("data-cache-probe", "original")
await page.keyboard.press("Control+Backquote")
await expect(picker).toHaveText("Session")
await page.keyboard.press("Control+Backquote")
await expect(picker).toHaveText("Terminal")
await panel.getByRole("button", { name: "Close terminal", exact: true }).click()
await expect(picker).toHaveText("Session")
await expect(panel).toBeHidden()
await more.click()
await page.getByRole("menuitem", { name: "Usage", exact: true }).click()
await expect(page.getByText("Total Cost", { exact: true })).toBeVisible()
await page.goto(stressSessionHref(fixture.sourceID))
await expect(picker).toHaveText("Session")
await expect(page.locator('[data-slot="mobile-tabs-trigger"]')).toContainText(fixture.expected.sourceTitle)
await page.setViewportSize({ width: 1280, height: 900 })
await expect(picker).toBeHidden()
await expect(page.locator("[data-session-title]")).toBeVisible()
})
}
@@ -1,37 +0,0 @@
import { expect, test } from "@playwright/test"
import { fixture } from "../performance/timeline/session-timeline-stress.fixture"
import { mockStressTimeline, stressSessionHref } from "../performance/timeline/timeline-test-helpers"
test("status drawer dismisses and reopens after button, backdrop, Escape, and drag", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 })
await mockStressTimeline(page)
await page.goto(stressSessionHref(fixture.targetID))
const more = page
.locator('[data-slot="session-mobile-view-navigation"]')
.getByRole("button", { name: "More options", exact: true })
const drawer = page.getByRole("dialog", { name: "Status", exact: true })
const overlay = page.locator('[data-slot="mobile-status-overlay"]')
for (const dismissal of ["button", "backdrop", "escape", "drag", "button"] as const) {
await more.click()
await page.getByRole("menuitem", { name: "Status", exact: true }).click()
await expect(drawer.getByRole("tab", { name: "MCP", exact: true })).toBeVisible()
await expect(drawer).not.toHaveAttribute("data-transitioning")
if (dismissal === "button") await drawer.getByRole("button", { name: "Close", exact: true }).click()
if (dismissal === "backdrop") await overlay.click({ position: { x: 10, y: 10 } })
if (dismissal === "escape") await page.keyboard.press("Escape")
if (dismissal === "drag") {
const handle = drawer.locator('[data-slot="mobile-status-drag-handle"]')
const bounds = await handle.boundingBox()
expect(bounds).not.toBeNull()
await page.mouse.move(bounds!.x + bounds!.width / 2, bounds!.y + bounds!.height / 2)
await page.mouse.down()
await page.mouse.move(bounds!.x + bounds!.width / 2, bounds!.y + bounds!.height / 2 + 1)
await page.mouse.move(bounds!.x + bounds!.width / 2, 843)
await page.mouse.up()
}
await expect(drawer, `dismissal: ${dismissal}`).toBeHidden()
await expect(overlay).toHaveCount(0)
await expect(more).toBeFocused()
}
})
@@ -89,7 +89,7 @@ async function openReview(page: Page) {
)
await changes.click()
expect((await (await diffResponse).json()).data).toHaveLength(1)
await expect(changes).toHaveAttribute("aria-selected", "true")
await expect(page.getByRole("tab", { selected: true })).toHaveAccessibleName(/Files Changed/)
const review = page.locator('[data-component="session-review"]')
await expectAppVisible(review)
-6
View File
@@ -8,12 +8,6 @@ export async function expectAppVisible(locator: Locator) {
}
export async function expectSessionTitle(page: Page, title: string) {
if ((page.viewportSize()?.width ?? 1280) < 768) {
const trigger = page.locator('[data-slot="mobile-tabs-trigger"]')
await expectAppVisible(trigger)
await expect(trigger.locator('span[dir="auto"]')).toHaveText(title, { timeout: APP_READY_TIMEOUT })
return
}
await expectAppVisible(page.getByRole("heading", { name: title }))
}
+1 -3
View File
@@ -114,10 +114,8 @@ export function ComposerEditor(props: ComposerEditorProps) {
<form
data-component="composer"
data-dock-border-underlay={props.borderUnderlay ? "true" : undefined}
class="group/composer relative min-h-[96px] w-full overflow-clip rounded-xl"
class="group/composer relative min-h-[96px] w-full overflow-clip rounded-xl bg-v2-background-bg-base"
classList={{
"bg-v2-background-bg-layer-01": props.borderUnderlay,
"bg-v2-background-bg-base": !props.borderUnderlay,
"shadow-[var(--v2-elevation-raised)]": !props.borderUnderlay,
"border border-v2-icon-icon-info border-dashed": state.drag === "active",
}}
+1 -6
View File
@@ -6,7 +6,6 @@ import { AppBaseProviders, AppInterface } from "@/app"
import { loadInitialLocale } from "@/runtime/i18n/language"
import { PlatformProvider } from "@/runtime/platform/platform"
import { createWebPlatform } from "@/runtime/platform/web"
import { isStandalone, PwaRoutePersistence, restorePwaRoute } from "@/runtime/platform/pwa"
import en from "@/runtime/i18n/en"
import zh from "@/runtime/i18n/zh"
import { authFromToken } from "@/runtime/server/api"
@@ -72,8 +71,6 @@ if (root instanceof HTMLElement && root.dataset.opencodeMounted === undefined) {
void loadInitialLocale().then((locale) => {
const auth = authFromToken(new URLSearchParams(location.search).get("auth_token"))
clearAuthToken()
const standalone = isStandalone()
if (standalone) restorePwaRoute()
const server: ServerConnection.Http = {
type: "http",
authToken: !!auth,
@@ -90,9 +87,7 @@ if (root instanceof HTMLElement && root.dataset.opencodeMounted === undefined) {
defaultServer={ServerConnection.Key.make(web.defaultServerUrl)}
canonicalLocalServer={ServerConnection.key(server)}
servers={[server]}
>
{standalone && <PwaRoutePersistence />}
</AppInterface>
/>
</AppBaseProviders>
</PlatformProvider>
),
+1 -8
View File
@@ -660,10 +660,6 @@ export const dict = {
"home.providerTip": "Connect to 75+ providers to use other models, including Claude, GPT, Gemini, etc",
"session.tab.session": "Session",
"session.tab.files": "Files",
"session.files.openTabs": "Open files",
"session.tab.usage": "Usage",
"session.view.select": "Session view",
"session.tab.review": "Review",
"session.tab.context": "Context",
"session.tab.unknown": "Unknown Session",
@@ -702,7 +698,6 @@ export const dict = {
"session.review.change.one": "Change",
"session.review.change.other": "Changes",
"session.review.loadingChanges": "Loading changes...",
"session.review.wrapLines": "Wrap lines",
"session.review.empty": "No changes in this session yet",
"session.review.noVcs": "No Git Version Control System detected, changes not displayed",
"session.review.noVcs.createGit.title": "Create a Git repository",
@@ -983,9 +978,7 @@ export const dict = {
"settings.general.row.showProjectIcon.description": "Show the project icon in the session header",
"settings.general.row.mobileTitlebarBottom.title": "Bottom navigation",
"settings.general.row.mobileTitlebarBottom.description":
"Place the title bar at the bottom of the screen on mobile",
"settings.general.row.mobileDiffWrap.description":
"Wrap long lines in mobile diffs instead of scrolling horizontally",
"Place the title bar and session tabs at the bottom of the screen on mobile",
"settings.general.row.showCustomAgents.title": "Show agent",
"settings.general.row.showCustomAgents.description":
"Switch between agents in the composer. When hidden, defaults to Build agent.",
-43
View File
@@ -1,43 +0,0 @@
import { useLocation } from "@solidjs/router"
import { createEffect } from "solid-js"
const LAST_ROUTE_KEY = "opencode.pwa.last-route"
export function isStandalone() {
return (
window.matchMedia("(display-mode: standalone)").matches ||
("standalone" in navigator && navigator.standalone === true)
)
}
export function restorePwaRoute() {
if (location.pathname !== "/" || location.search || location.hash) return
try {
const value = localStorage.getItem(LAST_ROUTE_KEY)
if (!value) return
const url = new URL(value, location.origin)
if (url.origin !== location.origin || url.searchParams.has("auth_token")) return
if (
url.pathname !== "/" &&
url.pathname !== "/new-session" &&
!/^\/server\/[^/]+\/session\/[^/]+$/.test(url.pathname)
)
return
history.replaceState(history.state, "", url.pathname + url.search + url.hash)
} catch {
// Storage may be unavailable; keep the launch URL in that case.
}
}
export function PwaRoutePersistence() {
const location = useLocation()
createEffect(() => {
const value = location.pathname + location.search + location.hash
try {
localStorage.setItem(LAST_ROUTE_KEY, value)
} catch {
// Navigation must still work when storage is unavailable or full.
}
})
return null
}
@@ -11,7 +11,14 @@ type SessionComposerRegionState = Pick<
export type SessionComposerRegionViewController = Pick<
SessionComposerRegionController,
"centered" | "onResponseSubmit" | "openParent" | "setPromptRef" | "setDockRef" | "parentID" | "child" | "showComposer"
| "centered"
| "onResponseSubmit"
| "openParent"
| "setPromptRef"
| "setDockRef"
| "parentID"
| "child"
| "showComposer"
> & { state: SessionComposerRegionState }
export function SessionComposerRegion(props: {
@@ -61,7 +68,10 @@ export function SessionComposerRegion(props: {
"relative z-[70]": true,
}}
>
<Show when={controller.child()} fallback={<Show when={!controller.state.blocked()}>{props.composer}</Show>}>
<Show
when={controller.child()}
fallback={<Show when={!controller.state.blocked()}>{props.composer}</Show>}
>
<div
ref={controller.setPromptRef}
class="w-full rounded-[12px] border border-border-weak-base bg-background-base p-3 text-16-regular text-text-weak"
@@ -271,7 +271,7 @@ export function SessionContextTab() {
}}
onScroll={handleScroll}
>
<div data-slot="session-usage-content" class="px-4 pt-4 pb-6 flex flex-col gap-6 md:px-6 md:pb-10 md:gap-10">
<div class="px-6 pt-4 pb-10 flex flex-col gap-10">
<div class="grid grid-cols-1 @[32rem]:grid-cols-2 gap-4">
<For each={stats}>
{(stat) => <Stat label={language.t(stat.label as Parameters<typeof language.t>[0])} value={stat.value()} />}
@@ -1,5 +1,4 @@
import { createMemo, createUniqueId, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { createMemo, createSignal, createUniqueId, Show } from "solid-js"
import { createQuery } from "@tanstack/solid-query"
import { Icon } from "@opencode-ai/ui/icon"
import { SessionFilePanelV2, SessionFilePanelV2Empty } from "@opencode-ai/session-ui/v2/session-file-panel-v2"
@@ -35,7 +34,6 @@ export function SessionFileBrowserTab(props: {
onSelect: (path: string) => void
onSelectPermanent: (path: string) => void
filterRef?: (element: HTMLInputElement) => void
mobile?: boolean
}) {
const file = useFile()
const language = useLanguage()
@@ -44,10 +42,8 @@ export function SessionFileBrowserTab(props: {
const serverSDK = useServerSDK()
const { workspaceKey } = useSessionLayout()
const resultsID = `session-file-browser-results-${createUniqueId()}`
const [store, setStore] = createStore({ filter: "", explicitHighlight: undefined as string | undefined })
const filter = () => store.filter
const setFilter = (value: string) => setStore("filter", value)
const setExplicitHighlight = (value: string) => setStore("explicitHighlight", value)
const [filter, setFilter] = createSignal("")
const [explicitHighlight, setExplicitHighlight] = createSignal<string>()
const sidebarOpened = () => props.placeholder || props.state.sidebarOpened()
const query = createMemo(() => filter().trim())
const search = createQuery(() => {
@@ -65,7 +61,7 @@ export function SessionFileBrowserTab(props: {
const highlighted = createMemo(() => {
const values = files()
if (values.length === 0) return undefined
const explicit = store.explicitHighlight
const explicit = explicitHighlight()
if (explicit && values.includes(explicit)) return explicit
return values[0]
})
@@ -109,13 +105,13 @@ export function SessionFileBrowserTab(props: {
filter={filter()}
onFilterChange={setFilter}
onFilterKeyDown={onFilterKeyDown}
filterAutofocus={props.placeholder && !props.mobile}
filterRef={(element) => props.filterRef?.(element)}
filterAutofocus={props.placeholder}
filterRef={props.filterRef}
filterControls={resultsID}
filterActiveDescendant={highlighted() ? optionID(highlighted()!) : undefined}
filterExpanded={query().length > 0 && files().length > 0}
width={props.state.sidebarWidth()}
onWidthChange={props.mobile ? undefined : props.state.resizeSidebar}
onWidthChange={props.state.resizeSidebar}
>
<Show
when={query()}
@@ -123,7 +119,6 @@ export function SessionFileBrowserTab(props: {
<FileTreeV2
active={props.active}
kinds={props.kinds}
draggable={!props.mobile}
onFileClick={(node) => props.onSelect(node.path)}
onFileDoubleClick={(node) => props.onSelectPermanent(node.path)}
/>
@@ -1,35 +0,0 @@
[data-slot="session-mobile-files"]
[data-slot="session-mobile-files-header"]
[data-component="tabs-v2"][data-variant="normal"][data-orientation="horizontal"]
[data-slot="tabs-v2-list"] {
position: static;
&::before {
inset-inline-start: 0;
width: 100%;
}
}
[data-slot="session-mobile-files"] [data-component="line-comment-v2"] {
max-width: none;
}
[data-slot="session-mobile-files"][data-browsing="true"] {
[data-component="session-review-v2-sidebar-root"] {
width: 100%;
}
[data-slot="session-review-v2-sidebar"] {
width: 100% !important;
border-inline-end: 0;
}
[data-slot="session-review-v2-preview"] {
display: none;
}
}
[data-slot="session-mobile-files"] [data-slot="tabs-v2-trigger-close-button"] [data-slot="tabs-close-button"] {
width: 32px;
height: 36px;
}
@@ -1,100 +0,0 @@
import { Button } from "@opencode-ai/ui/button"
import { Tabs } from "@opencode-ai/ui/tabs"
import { getFilename } from "@opencode-ai/util/path"
import { createMemo, For } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import { useSessionLayout } from "@/session/session-layout"
import { createSessionTabs, SESSION_OPEN_FILE_TAB } from "@/session/helpers"
import { useFile } from "@/workspaces/files/model"
import { SessionFileBrowserTab } from "./session-file-browser-tab"
import type { Kind } from "./file-tree-v2"
import "./session-mobile-files.css"
export function SessionMobileFiles() {
const file = useFile()
const language = useLanguage()
const layout = useSessionLayout()
const tabs = createSessionTabs({
tabs: layout.tabs,
pathFromTab: file.pathFromTab,
normalizeTab: file.tab,
})
const [store, setStore] = createStore({ browsing: !tabs.activeFileTab() })
const browsing = () => store.browsing || !tabs.activeFileTab()
const active = createMemo(() => file.pathFromTab(tabs.activeFileTab() ?? ""))
const kinds = new Map<string, Kind>()
const open = (path: string) => {
layout.tabs().open(file.tab(path))
void file.load(path)
setStore("browsing", false)
}
return (
<div data-slot="session-mobile-files" data-browsing={browsing()} class="flex h-full min-h-0 flex-col">
<div data-slot="session-mobile-files-header" class="relative flex h-10 shrink-0 items-center">
<Button
size="small"
variant="ghost"
class="shrink-0 mx-2"
onClick={() => setStore("browsing", true)}
aria-pressed={browsing()}
>
{language.t("session.files.all")}
</Button>
<Tabs
value={browsing() ? SESSION_OPEN_FILE_TAB : tabs.activeFileTab()}
onChange={(tab) => {
// Kobalte falls back to a file tab when the browse view has no trigger.
if (browsing()) return
const path = file.pathFromTab(tab)
if (path) open(path)
}}
variant="line"
class="min-w-0 flex-1 !h-auto"
>
<Tabs.List aria-label={language.t("session.files.openTabs")} class="!h-10 !px-0 overflow-x-auto">
<For each={tabs.openedTabs()}>
{(tab) => (
<Tabs.Trigger
value={tab}
onClick={() => open(file.pathFromTab(tab)!)}
class="shrink-0 max-w-48"
classes={{ button: "min-w-0" }}
closeButton={
<Tabs.CloseButton
aria-label={language.t("common.closeTab")}
onClick={() => layout.tabs().close(tab)}
/>
}
>
<span dir="ltr" class="truncate">
{getFilename(file.pathFromTab(tab) ?? tab)}
</span>
</Tabs.Trigger>
)}
</For>
</Tabs.List>
</Tabs>
</div>
<div class="min-h-0 flex-1">
<SessionFileBrowserTab
mobile
tab={tabs.activeFileTab() ?? SESSION_OPEN_FILE_TAB}
placeholder={browsing()}
active={active()}
kinds={kinds}
state={{
sidebarOpened: browsing,
sidebarWidth: () => 240,
sidebarTransition: () => false,
resizeSidebar: () => undefined,
toggleSidebar: () => setStore("browsing", !browsing()),
}}
onSelect={open}
onSelectPermanent={open}
/>
</div>
</div>
)
}
@@ -19,10 +19,7 @@ export function SessionHeader() {
const isDesktop = createMediaQuery("(min-width: 768px)")
const actions = createMemo<SessionHeaderActionsState>(() => ({
status:
isDesktop() && status()
? { label: language.t("status.popover.trigger"), content: () => <StatusPopover /> }
: undefined,
status: status() ? { label: language.t("status.popover.trigger"), content: () => <StatusPopover /> } : undefined,
reviewLabel: language.t("command.review.toggle"),
reviewKeybind: reviewTooltipKeybind(command),
reviewVisible: isDesktop(),
-22
View File
@@ -36,28 +36,6 @@ describe("createOpenReviewFile", () => {
expect(calls).toEqual(["show", "load:src/a.ts", "tab:src/a.ts", "open:file://src/a.ts", "active:file://src/a.ts"])
})
test("selects immediately and does not steal focus when loading finishes", async () => {
const loading = Promise.withResolvers<void>()
const state = { active: "file://previous.ts", opened: [] as string[] }
const openReviewFile = createOpenReviewFile({
showAllFiles: () => undefined,
tabForPath: (path) => `file://${path}`,
openTab: (tab) => state.opened.push(tab),
setActive: (tab) => {
state.active = tab
},
loadFile: () => loading.promise,
})
openReviewFile("requested.ts")
expect(state.opened).toEqual(["file://requested.ts"])
expect(state.active).toBe("file://requested.ts")
state.active = "file://previous.ts"
loading.resolve()
await loading.promise
expect(state.active).toBe("file://previous.ts")
})
})
describe("createOpenSessionFileTab", () => {
+8 -4
View File
@@ -124,10 +124,14 @@ export const createOpenReviewFile = (input: {
return (path: string) => {
batch(() => {
input.showAllFiles()
input.loadFile(path)
const tab = input.tabForPath(path)
input.openTab(tab)
input.setActive(tab)
const maybePromise = input.loadFile(path)
const open = () => {
const tab = input.tabForPath(path)
input.openTab(tab)
input.setActive(tab)
}
if (maybePromise instanceof Promise) void maybePromise.then(open)
else open()
})
}
}
+3 -5
View File
@@ -38,7 +38,7 @@ export function createSessionReview(input: {
const location = useWorkspaceLocation()
const server = useServerSDK()
const [state, setState] = createStore({
mobileTab: "session" as "session" | "changes" | "files" | "usage",
mobileTab: "session" as "session" | "changes",
detailsOpen: false,
scroll: undefined as HTMLDivElement | undefined,
pendingFile: undefined as string | undefined,
@@ -66,9 +66,7 @@ export function createSessionReview(input: {
}
return list
})
const mobileChanges = createMemo(
() => !input.session.isDesktop() && !input.screen.terminal.open() && state.mobileTab === "changes",
)
const mobileChanges = createMemo(() => !input.session.isDesktop() && state.mobileTab === "changes")
const vcsMode = createMemo<VcsMode | undefined>(() => {
const value = mode()
return value === "git" || value === "branch" ? value : undefined
@@ -409,7 +407,7 @@ export function createSessionReview(input: {
loadDiff,
mobile: {
changes: mobileChanges,
setTab: (tab: "session" | "changes" | "files" | "usage") => setState("mobileTab", tab),
setTab: (tab: "session" | "changes") => setState("mobileTab", tab),
tab: () => state.mobileTab,
},
mode,
@@ -23,9 +23,6 @@ export interface SessionReviewTabProps {
diffs: ReviewDiff[]
view: ReturnType<ReturnType<typeof useLayout>["view"]>
diffStyle: DiffStyle
changeSummary?: boolean
overflow?: "wrap" | "scroll"
disableLineNumbers?: boolean
onDiffStyleChange?: (style: DiffStyle) => void
onViewFile?: (file: string) => void
onLineComment?: (comment: { file: string; selection: SelectedLineRange; comment: string; preview?: string }) => void
@@ -125,7 +122,6 @@ export function SessionReviewTab(props: SessionReviewTabProps) {
createEffect(() => {
props.diffs.length
props.diffStyle
props.overflow
if (!layout.ready()) return
queueRestore()
})
@@ -160,9 +156,6 @@ export function SessionReviewTab(props: SessionReviewTabProps) {
}}
diffs={props.diffs}
diffStyle={props.diffStyle}
changeSummary={props.changeSummary}
overflow={props.overflow}
disableLineNumbers={props.disableLineNumbers}
onDiffStyleChange={props.onDiffStyleChange}
onViewFile={props.onViewFile}
focusedFile={props.focusedFile}
+40 -134
View File
@@ -2,137 +2,51 @@ import { SessionReviewEmptyChangesV2 } from "@opencode-ai/session-ui/v2/session-
import { SessionReviewV2SidebarToggle } from "@opencode-ai/session-ui/v2/session-review-v2"
import { Select } from "@opencode-ai/ui/select"
import { Tabs } from "@opencode-ai/ui/tabs"
import { Icon } from "@opencode-ai/ui/icon"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { Menu } from "@opencode-ai/ui/menu"
import { For, Match, Show, Suspense, Switch, lazy, createEffect, onCleanup, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { Match, Show, Suspense, Switch } from "solid-js"
import { useLanguage } from "@/runtime/i18n/language"
import { useSettings } from "@/settings/model"
import { SessionSidePanel } from "../files/session-side-panel"
import { ReviewPanel } from "./panel"
import { SessionReviewTab } from "./review-tab"
import type { ChangeMode, SessionReviewModel } from "./model"
const StatusDrawer = lazy(async () => {
const { StatusDrawer } = await import("@/shell/status/status-drawer")
return { default: StatusDrawer }
})
const MobilePanelDrawer = lazy(async () => {
const { MobilePanelDrawer } = await import("@/shell/mobile-panel-drawer")
return { default: MobilePanelDrawer }
})
export function SessionMobileViewTabs(props: {
current: "session" | "changes" | "files" | "usage" | "terminal"
onSelect: (view: "session" | "changes" | "files" | "usage" | "terminal") => void
details?: (close: () => void) => JSX.Element
onDetailsOpenChange?: (open: boolean) => void
}) {
export function SessionMobileTabs(props: { review: SessionReviewModel; compact?: boolean; bottom?: boolean }) {
const language = useLanguage()
const [store, setStore] = createStore({
menu: false,
status: false,
statusLoaded: false,
details: false,
detailsLoaded: false,
pending: undefined as "status" | "details" | undefined,
})
createEffect(() => props.onDetailsOpenChange?.(store.details))
onCleanup(() => props.onDetailsOpenChange?.(false))
let trigger: HTMLButtonElement | undefined
return (
<div
class="relative flex shrink-0 items-center before:pointer-events-none before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-v2-border-border-base before:content-['']"
data-slot="session-mobile-view-navigation"
>
<Tabs value={props.current} variant="line" class="!h-auto min-w-0 flex-1" data-slot="session-mobile-view-tabs">
<Tabs.List aria-label={language.t("session.view.select")} class="!h-9 !gap-0 !px-0 before:!hidden">
<For each={["session", "changes", "files", "terminal"] as const}>
{(view) => (
<Tabs.Trigger
value={view}
class="min-w-0 flex-1"
classes={{ button: "w-full justify-center" }}
onClick={() => props.onSelect(view)}
>
{view === "session"
? language.t("session.tab.session")
: view === "changes"
? language.plural("session.review.change", 0)
: view === "files"
? language.t("session.tab.files")
: language.t("terminal.title")}
</Tabs.Trigger>
)}
</For>
</Tabs.List>
</Tabs>
<Menu
appearance="standard"
modal={false}
placement="bottom-end"
gutter={4}
open={store.menu}
onOpenChange={(open) => setStore("menu", open)}
<Tabs value={props.review.mobile.tab()} class="h-auto">
<Tabs.List
classList={{
"!h-9": props.compact,
"[&::after]:!border-b-0 [&::after]:!border-t [&::after]:!border-border-weak-base": props.bottom,
}}
>
<Menu.Trigger
as={IconButton}
ref={(element: HTMLButtonElement) => {
trigger = element
<Tabs.Trigger
value="session"
classes={{ button: props.compact ? "w-full !py-2" : "w-full" }}
classList={{
"!w-1/2 !max-w-none": true,
"!border-b-0 !border-t !border-border-weak-base [&:has([data-selected])]:!border-t-transparent":
props.bottom,
}}
icon={<Icon name="menu" />}
variant="ghost-muted"
size="normal"
class="mx-1.5 shrink-0"
state={props.current === "usage" || store.menu ? "pressed" : undefined}
aria-label={language.t("common.moreOptions")}
/>
<Menu.Portal>
<Menu.Content
onCloseAutoFocus={(event) => {
if (!store.pending) return
event.preventDefault()
if (store.pending === "status") setStore({ status: true, statusLoaded: true })
if (store.pending === "details") setStore({ details: true, detailsLoaded: true })
setStore("pending", undefined)
}}
>
<Menu.Item onSelect={() => props.onSelect("usage")}>{language.t("session.tab.usage")}</Menu.Item>
<Show when={props.details}>
<Menu.Item onSelect={() => setStore({ pending: "details", menu: false })}>
{language.t("session.summary.title")}
</Menu.Item>
</Show>
<Menu.Item onSelect={() => setStore({ pending: "status", menu: false })}>
{language.t("status.popover.trigger")}
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu>
<Show when={store.statusLoaded}>
<Suspense>
<StatusDrawer
open={store.status}
onOpenChange={(open) => setStore("status", open)}
returnFocus={() => trigger}
/>
</Suspense>
</Show>
<Show when={store.detailsLoaded}>
<Suspense>
<MobilePanelDrawer
title={language.t("session.summary.title")}
open={store.details}
onOpenChange={(open) => setStore("details", open)}
returnFocus={() => trigger}
>
{props.details?.(() => setStore("details", false))}
</MobilePanelDrawer>
</Suspense>
</Show>
</div>
onClick={() => props.review.mobile.setTab("session")}
>
{language.t("session.tab.session")}
</Tabs.Trigger>
<Tabs.Trigger
value="changes"
classes={{ button: props.compact ? "w-full !py-2" : "w-full" }}
classList={{
"!w-1/2 !max-w-none !border-r-0": true,
"!border-b-0 !border-t !border-border-weak-base [&:has([data-selected])]:!border-t-transparent":
props.bottom,
}}
onClick={() => props.review.mobile.setTab("changes")}
>
{props.review.hasChanges()
? language.t("session.review.filesChanged", { count: props.review.count() })
: language.plural("session.review.change", 0)}
</Tabs.Trigger>
</Tabs.List>
</Tabs>
)
}
@@ -174,22 +88,14 @@ export function SessionDesktopReview(props: { review: SessionReviewModel; presen
}
function ReviewContent(props: { review: SessionReviewModel }) {
const settings = useSettings()
return (
<Show when={!props.review.deferRender()}>
<SessionReviewTab
title={<ReviewTitle review={props.review} />}
empty={<ReviewEmpty review={props.review} loadingClass="px-2 py-2 text-text-weak" />}
empty={<ReviewEmpty review={props.review} loadingClass="px-4 py-4 text-text-weak" />}
diffs={props.review.diffs()}
view={props.review.view()}
diffStyle="unified"
changeSummary
disableLineNumbers={false}
overflow={settings.general.mobileDiffWrap() ? "wrap" : "scroll"}
onViewFile={(file) => {
props.review.openFile(file)
props.review.mobile.setTab("files")
}}
onScrollRef={props.review.setScroll}
focusedFile={props.review.activeFile()}
onLineComment={props.review.comments.add}
@@ -200,11 +106,11 @@ function ReviewContent(props: { review: SessionReviewModel }) {
comments={props.review.comments.all()}
focusedComment={props.review.comments.focus()}
onFocusedCommentChange={props.review.comments.setFocus}
onViewFile={props.review.openFile}
classes={{
root: "[&_[data-slot=session-review-list]]:pb-0 [&_[data-slot=accordion-trigger]]:!rounded-none [&_[data-slot=accordion-trigger]]:!border-x-0 [&_[data-slot=accordion-item]:first-child_[data-slot=accordion-trigger]]:!border-t-0 [&_[data-slot=accordion-item]:last-child:not([data-expanded])_[data-slot=accordion-trigger]]:!border-b-0 [&_[data-slot=accordion-item]:last-child_[data-slot=accordion-content]]:!border-b-0 [&_[data-slot=accordion-item]:last-child_[data-slot=session-review-diff-placeholder]]:!border-b-0 [&_[data-slot=accordion-content]]:!rounded-none [&_[data-slot=accordion-content]]:!border-x-0 [&_[data-slot=session-review-diff-placeholder]]:!rounded-none [&_[data-slot=session-review-diff-placeholder]]:!border-x-0",
header:
"!px-2 !h-10 !pb-0 relative before:pointer-events-none before:absolute before:inset-x-0 before:bottom-0 before:h-px before:bg-v2-border-border-base before:content-['']",
container: "!px-0",
root: "pb-8 [&_[data-slot=session-review-list]]:pb-0",
header: "px-4 !h-16 !pb-4",
container: "px-4",
}}
/>
</Show>
+18 -111
View File
@@ -1,23 +1,11 @@
import {
ErrorBoundary,
Show,
Match,
Switch,
Suspense,
lazy,
createMemo,
createEffect,
createComputed,
on,
} from "solid-js"
import { ErrorBoundary, Show, Match, Switch, createMemo, createEffect, createComputed, on } from "solid-js"
import { createStore } from "solid-js/store"
import createPresence from "solid-presence"
import { ResizeHandle } from "@opencode-ai/ui/resize-handle"
import { SessionHeader } from "@/session/header/session-header"
import { useLayout } from "@/shell/state/layout"
import { MessageTimeline, SessionSummaryPanel } from "@/session/timeline/message-timeline"
import { useServer } from "@/runtime/server/current"
import { projectForSession } from "@/shell/layout/helpers"
import { useSettings } from "@/settings/model"
import { MessageTimeline } from "@/session/timeline/message-timeline"
import type { SessionModel } from "@/session/model"
import { SESSION_PANEL_WIDTH_MIN } from "@/session/session-panel-width"
import { SessionPanelFrame } from "@/session/session-frame"
@@ -26,25 +14,15 @@ import { useUsageExceededDialogs } from "./usage-exceeded-dialogs"
import { SessionErrorFallback } from "./route-error"
import { createSessionScreenLayout } from "./screen-layout"
import { createSessionReview } from "./review/model"
import { SessionDesktopReview, SessionMobileReview, SessionMobileViewTabs } from "./review/view"
import { SessionContextTab } from "./files/session-context-tab"
import { SessionDesktopReview, SessionMobileReview, SessionMobileTabs } from "./review/view"
import { createSessionTimelineInteraction } from "./timeline/interaction"
import { ActiveSessionComposerRegion, createActiveSessionRegion } from "./composer/region"
import { SessionIdentityHeader } from "./session-identity-header"
const SessionMobileFiles = lazy(async () => {
const { SessionMobileFiles } = await import("./files/session-mobile-files")
return { default: SessionMobileFiles }
})
export function SessionScreen(props: { session: SessionModel }) {
const session = props.session
const layout = useLayout()
const server = useServer()
const detailsProject = createMemo(() => {
const info = session.data.info()
return info ? projectForSession(info, server.ctx.sync.data.project) : undefined
})
const settings = useSettings()
const isDesktop = session.isDesktop
const screen = createSessionScreenLayout(session)
const timeline = createSessionTimelineInteraction(session)
@@ -56,8 +34,6 @@ export function SessionScreen(props: { session: SessionModel }) {
sideRegionPresent: false,
sideReviewPresent: false,
sideTerminalPresent: false,
mobileTerminalCached: false,
mobileMoveDismissed: false,
})
const [elements, setElements] = createStore<{
side?: HTMLDivElement
@@ -65,7 +41,7 @@ export function SessionScreen(props: { session: SessionModel }) {
}>({})
const sideVisible = createMemo(() => isDesktop() && screen.side.layout().visible)
const sideTerminalVisible = createMemo(() => isDesktop() && screen.terminal.side() && screen.terminal.open())
const bottomTerminalVisible = createMemo(() => isDesktop() && screen.terminal.open() && screen.terminal.bottom())
const bottomTerminalVisible = createMemo(() => screen.terminal.open() && (!isDesktop() || screen.terminal.bottom()))
const sidePresence = createPresence({
show: sideVisible,
element: () => elements.side ?? null,
@@ -91,7 +67,6 @@ export function SessionScreen(props: { session: SessionModel }) {
createComputed((prev) => {
const key = session.identity.sessionKey()
if (key !== prev) {
setStore("mobileMoveDismissed", false)
setStore("deferRender", true)
const owner = session.ownership.capture()
requestAnimationFrame(() => {
@@ -101,11 +76,6 @@ export function SessionScreen(props: { session: SessionModel }) {
return key
})
const review = createSessionReview({ session, screen, deferRender: () => store.deferRender })
const mobileView = createMemo(() => (screen.terminal.open() ? "terminal" : review.mobile.tab()))
const conversationVisible = createMemo(() => isDesktop() || mobileView() === "session")
createEffect(() => {
if (!isDesktop() && screen.terminal.open()) setStore("mobileTerminalCached", true)
})
const composer = createActiveSessionRegion({
session,
screen,
@@ -114,102 +84,36 @@ export function SessionScreen(props: { session: SessionModel }) {
useUsageExceededDialogs()
const mobileTabsBottom = createMemo(() => !isDesktop() && settings.general.mobileTitlebarPosition() === "bottom")
const sessionErrorFallback = (error: unknown, reset: () => void) => {
createEffect(on(session.identity.sessionKey, reset, { defer: true }))
return <SessionErrorFallback error={error} sessionID={session.identity.params.id} />
}
const mobileTabs = () => (
<Show when={session.identity.sessionKey()} keyed>
{(_key) => (
<SessionMobileViewTabs
current={mobileView()}
onDetailsOpenChange={review.details.setOpen}
details={
!session.data.isChild() && detailsProject()
? (close) => (
<Show when={detailsProject()}>
{(project) => (
<SessionSummaryPanel
mobile
project={project()}
directory={session.workspace.directory()}
local={!session.workspace.current()}
branch={
session.shared.data.location.vcs.info({ directory: session.workspace.directory() })?.branch
.current
}
baseBranch={
session.shared.data.location.vcs.info({ directory: project().worktree })?.branch.current
}
diffs={project().vcs === "git" ? review.details.diffs() : []}
sessionID={session.identity.params.id ?? ""}
moveEligible={composer.workspaceMoveEligible()}
moveDismissed={store.mobileMoveDismissed}
onMoveDismiss={() => setStore("mobileMoveDismissed", true)}
onReview={() => {
close()
review.mobile.setTab("changes")
session.layout.view().terminal.close()
}}
backgroundTasks={composer.region.state.background.tasks()}
/>
)}
</Show>
)
: undefined
}
onSelect={(view) => {
if (view === "terminal") {
session.layout.view().terminal.open()
return
}
review.mobile.setTab(view)
session.layout.view().terminal.close()
}}
/>
)}
</Show>
)
const sessionPanelContent = () => (
<>
<Show when={!isDesktop() && !!session.identity.params.id}>{mobileTabs()}</Show>
<Show when={!isDesktop() && !!session.identity.params.id && !mobileTabsBottom()}>
<SessionMobileTabs review={review} compact />
</Show>
{/* Surface query errors without suspending session metadata while messages load. */}
<Show when={timeline.resource.error}>
{(error) => {
throw error()
}}
</Show>
<div class="relative flex-1 min-h-0 overflow-hidden">
<Show when={!isDesktop() && store.mobileTerminalCached}>
<div class="absolute inset-0" classList={{ invisible: mobileView() !== "terminal" }}>
<TerminalPanel fill embedded present contentHeight="100%" />
</div>
</Show>
<div class="flex-1 min-h-0 overflow-hidden">
<Switch>
<Match when={!isDesktop() && mobileView() === "terminal"}>
<></>
</Match>
<Match when={!isDesktop() && mobileView() === "usage"}>
<SessionContextTab />
</Match>
<Match when={!isDesktop() && mobileView() === "files"}>
<Suspense>
<SessionMobileFiles />
</Suspense>
</Match>
<Match when={session.identity.params.id && review.mobile.changes()}>
<SessionMobileReview review={review} />
</Match>
<Match when={session.identity.params.id}>
<Show when={isDesktop() && !messagesReady()}>
<Show when={!messagesReady()}>
<SessionIdentityHeader sessionID={session.identity.params.id ?? ""} session={session.data.info()} />
</Show>
<Show when={messagesReady() ? session.identity.params.id : undefined} keyed>
{(_id) => (
<MessageTimeline
hideHeader={!isDesktop()}
session={session}
background={composer.region.state.background}
actions={composer.actions.timeline}
@@ -239,11 +143,14 @@ export function SessionScreen(props: { session: SessionModel }) {
</Switch>
</div>
<Show when={conversationVisible() ? session.identity.params.id : undefined} keyed>
<Show when={!review.mobile.changes() ? session.identity.params.id : undefined} keyed>
{(_id) => (
<ActiveSessionComposerRegion model={composer} session={session} onResponseSubmit={timeline.actions.resume} />
)}
</Show>
<Show when={!!session.identity.params.id && mobileTabsBottom()}>
<SessionMobileTabs review={review} compact bottom />
</Show>
</>
)
@@ -393,7 +300,7 @@ export function SessionScreen(props: { session: SessionModel }) {
</Show>
</div>
<Show when={isDesktop() && (bottomTerminalPresence.present() || store.bottomTerminalCached)}>
<Show when={bottomTerminalPresence.present() || store.bottomTerminalCached}>
<div
ref={(element) => setElements("bottomTerminal", element)}
data-slot="terminal-panel-presence"
+1 -9
View File
@@ -38,14 +38,7 @@ type CachedTerminalSurface = {
}
export function TerminalPanel(
props: {
stacked?: boolean
fill?: boolean
framed?: boolean
present?: boolean
contentHeight?: string
embedded?: boolean
} = {},
props: { stacked?: boolean; fill?: boolean; framed?: boolean; present?: boolean; contentHeight?: string } = {},
) {
const layout = useLayout()
const terminal = useTerminal()
@@ -230,7 +223,6 @@ export function TerminalPanel(
opened={opened()}
present={present()}
framed={props.framed}
embedded={props.embedded}
desktop={isDesktop()}
stacked={stacked()}
height={panelHeight()}
@@ -7,7 +7,6 @@ export function TerminalSurface(
opened: boolean
present?: boolean
framed?: boolean
embedded?: boolean
desktop: boolean
stacked: boolean
height: string
@@ -27,7 +26,7 @@ export function TerminalSurface(
id="terminal-panel"
data-component="terminal-panel"
data-opened={props.opened}
data-size-animated={!props.embedded && !props.resizing && (!props.desktop || props.stacked)}
data-size-animated={!props.resizing && (!props.desktop || props.stacked)}
role="region"
aria-label={props.label}
aria-hidden={!props.opened}
@@ -38,14 +37,11 @@ export function TerminalSurface(
"min-w-0 h-full flex-1": props.desktop && (props.present ?? props.opened) && !props.stacked,
"w-0 h-full pointer-events-none": props.desktop && !(props.present ?? props.opened),
"rounded-[10px] shadow-[var(--v2-elevation-raised)]": props.desktop && (props.framed ?? true),
"will-change-[height]": !props.embedded && !props.resizing && (!props.desktop || props.stacked),
"will-change-[height]": !props.resizing && (!props.desktop || props.stacked),
}}
style={{ height: props.height, "--terminal-panel-height": props.contentHeight }}
>
<div
classList={{ "md:hidden": !props.stacked, hidden: props.stacked || props.embedded }}
onPointerDown={props.onResizeStart}
>
<div classList={{ "md:hidden": !props.stacked, hidden: props.stacked }} onPointerDown={props.onResizeStart}>
<ResizeHandle
class="-top-1"
direction="vertical"
@@ -61,7 +57,7 @@ export function TerminalSurface(
data-slot="terminal-panel-content"
class="absolute inset-x-0 top-0 flex flex-col overflow-hidden"
classList={{
"border-t border-border-weak-base": props.opened && !props.desktop && !props.embedded,
"border-t border-border-weak-base": props.opened && !props.desktop,
"pointer-events-none": !props.opened,
}}
style={{ height: props.contentHeight }}
@@ -69,7 +69,7 @@ export function BackgroundMoveHint(props: { keybind?: string[] }) {
)
}
export function BackgroundWorkSummary(props: { tasks: BackgroundTask[]; mobile?: boolean }) {
export function BackgroundWorkSummary(props: { tasks: BackgroundTask[] }) {
const language = useLanguage()
const [open, setOpen] = createSignal(false)
const taskType = (task: BackgroundTask) => {
@@ -81,7 +81,7 @@ export function BackgroundWorkSummary(props: { tasks: BackgroundTask[]; mobile?:
return (
<Popover
open={open()}
placement={props.mobile ? "top-end" : language.direction() === "rtl" ? "right-end" : "left-end"}
placement={language.direction() === "rtl" ? "right-end" : "left-end"}
gutter={4}
onOpenChange={setOpen}
>
@@ -126,7 +126,6 @@ export function BackgroundWorkSummary(props: { tasks: BackgroundTask[]; mobile?:
function WorkspaceMoveAction(props: {
variant: "inline" | "panel"
mobile?: boolean
eligible: boolean
sessionID: string
project: Project
@@ -151,17 +150,9 @@ function WorkspaceMoveAction(props: {
sessionID={props.sessionID}
project={props.project}
directory={props.directory}
placement={
props.mobile
? "top-end"
: inline()
? "bottom-end"
: language.direction() === "rtl"
? "right-start"
: "left-start"
}
gutter={props.mobile || inline() ? 4 : -22}
contentClass={props.mobile || inline() ? undefined : "relative top-3.5"}
placement={inline() ? "bottom-end" : language.direction() === "rtl" ? "right-start" : "left-start"}
gutter={inline() ? 4 : -22}
contentClass={inline() ? undefined : "relative top-3.5"}
class={
inline()
? "flex h-5 w-full items-center gap-1.5 rounded-[4px] pe-6 text-[13px] font-[440] leading-5 tracking-[-0.04px] text-v2-text-text-faint hover:bg-v2-overlay-simple-overlay-hover focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none data-[expanded]:bg-v2-overlay-simple-overlay-pressed"
@@ -190,8 +181,7 @@ function WorkspaceMoveAction(props: {
)
}
export function SessionSummaryPanel(props: {
mobile?: boolean
function SessionSummaryPanel(props: {
project: Project
avatar?: JSX.Element
directory: string
@@ -217,7 +207,7 @@ export function SessionSummaryPanel(props: {
"flex h-7 w-full items-center gap-2 rounded-[4px] px-3 text-[13px] font-[440] leading-5 tracking-[-0.04px] text-v2-text-text-base"
return (
<div data-component="session-summary-panel" class={props.mobile ? "w-full" : "w-[280px]"}>
<div data-component="session-summary-panel" class="w-[280px]">
<div class="relative z-10 flex flex-col gap-1 overflow-hidden rounded-[6px] bg-v2-background-bg-base px-0.5 py-1.5 shadow-[var(--v2-elevation-raised)]">
<div class={row}>
{props.avatar ?? (
@@ -227,23 +217,19 @@ export function SessionSummaryPanel(props: {
variant={getProjectAvatarVariant(props.project.icon?.color)}
/>
)}
<span dir="auto" class="min-w-0 flex-1 truncate text-v2-text-text-muted">
{displayName(props.project)}
</span>
<span class="min-w-0 flex-1 truncate text-v2-text-text-muted">{displayName(props.project)}</span>
</div>
<SessionWorkspaceMenu
eligible={props.moveEligible}
sessionID={props.sessionID}
project={props.project}
directory={props.directory}
placement={props.mobile ? "top-end" : language.direction() === "rtl" ? "right-start" : "left-start"}
gutter={props.mobile ? 4 : -22}
placement={language.direction() === "rtl" ? "right-start" : "left-start"}
gutter={-22}
class={`${row} hover:bg-v2-overlay-simple-overlay-hover focus-visible:bg-v2-overlay-simple-overlay-hover focus-visible:outline-none data-[expanded]:bg-v2-overlay-simple-overlay-pressed`}
>
<Icon name={props.local ? "monitor" : "workspace-isolated"} class="shrink-0 text-v2-icon-icon-muted" />
<span dir="auto" class="min-w-0 flex-1 truncate text-start">
{location()}
</span>
<span class="min-w-0 flex-1 truncate text-start">{location()}</span>
<Icon name="chevron-down" size="small" class="shrink-0 text-v2-icon-icon-muted" />
</SessionWorkspaceMenu>
<div class={row}>
@@ -266,9 +252,7 @@ export function SessionSummaryPanel(props: {
</span>
}
>
<span dir="auto" class="min-w-0 truncate">
{branch()}
</span>
<span class="min-w-0 truncate">{branch()}</span>
</Show>
</div>
<button
@@ -288,13 +272,12 @@ export function SessionSummaryPanel(props: {
</Show>
</button>
<Show when={props.backgroundTasks.length > 0}>
<BackgroundWorkSummary tasks={props.backgroundTasks} mobile={props.mobile} />
<BackgroundWorkSummary tasks={props.backgroundTasks} />
</Show>
</div>
<Show when={props.local && props.diffs && props.diffs.length > 0 && props.moveEligible}>
<WorkspaceMoveAction
variant="panel"
mobile={props.mobile}
eligible={props.moveEligible}
sessionID={props.sessionID}
project={props.project}
@@ -308,7 +291,6 @@ export function SessionSummaryPanel(props: {
}
type MessageTimelineProps = {
hideHeader?: boolean
session: TimelineSessionSource
background: SessionBackground
actions?: SessionUserActions
@@ -411,7 +393,7 @@ function MessageTimelineView(
}),
)
const turnPadding = () => "px-4 md:px-5"
const showHeader = createMemo(() => !props.hideHeader && (props.data.showHeader() || workspaceSession()))
const showHeader = createMemo(() => props.data.showHeader() || workspaceSession())
const pinned = createMemo(() => props.pinned)
const messageByID = projection.messageByID
const virtualized = createTimelineVirtualizer({
@@ -574,200 +556,198 @@ function MessageTimelineView(
}}
renderRow={(row, onSizeChange) => <rowRenderer.Row row={row} onSizeChange={onSizeChange} />}
header={
<Show when={!props.hideHeader}>
<SessionTitleHeader>
<div class="h-12 w-full flex items-center justify-between gap-2">
<div class="flex items-center gap-1 min-w-0 flex-1">
<div class="flex items-center min-w-0 flex-1 w-full">
<SessionTitleHeader>
<div class="h-12 w-full flex items-center justify-between gap-2">
<div class="flex items-center gap-1 min-w-0 flex-1">
<div class="flex items-center min-w-0 flex-1 w-full">
<Show
when={workspaceSession()}
fallback={
<span class="flex size-6 shrink-0 items-center justify-center text-v2-icon-icon-muted">
<Show when={showProjectIcon()} fallback={<Icon name="monitor" />}>
{projectAvatar()}
</Show>
</span>
}
>
<Tooltip
placement="bottom-start"
value={sessionDirectory()}
contentClass="max-w-[calc(100vw-32px)] break-all"
>
<span
tabIndex={0}
aria-label={sessionDirectory()}
classList={{
"flex size-6 shrink-0 items-center justify-center": true,
"text-v2-icon-icon-accent": !showProjectIcon(),
}}
>
<Show when={showProjectIcon()} fallback={<Icon name="workspace-isolated" />}>
{projectAvatar()}
</Show>
</span>
</Tooltip>
</Show>
<Show when={parentID()}>
<button
type="button"
data-slot="session-title-parent"
class="min-w-0 max-w-[40%] truncate pl-2 text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:text-v2-text-text-muted"
onClick={props.action.navigateParent}
>
{parentTitle()}
</button>
<span
data-slot="session-title-separator"
class="-translate-y-[0.5px] pl-2 pr-1 text-[11px] font-medium text-v2-text-text-faint"
aria-hidden="true"
>
/
</span>
</Show>
<Show when={childTitle() || title.editing}>
<Show
when={workspaceSession()}
when={title.editing}
fallback={
<span class="flex size-6 shrink-0 items-center justify-center text-v2-icon-icon-muted">
<Show when={showProjectIcon()} fallback={<Icon name="monitor" />}>
{projectAvatar()}
</Show>
</span>
<h1
data-slot="session-title-child"
class="truncate text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-base w-fit rounded-[6px] px-2 py-1 hover:bg-v2-overlay-simple-overlay-hover"
onClick={openTitleEditor}
>
{childTitle()}
</h1>
}
>
<Tooltip
placement="bottom-start"
value={sessionDirectory()}
contentClass="max-w-[calc(100vw-32px)] break-all"
>
<span
tabIndex={0}
aria-label={sessionDirectory()}
classList={{
"flex size-6 shrink-0 items-center justify-center": true,
"text-v2-icon-icon-accent": !showProjectIcon(),
}}
>
<Show when={showProjectIcon()} fallback={<Icon name="workspace-isolated" />}>
{projectAvatar()}
</Show>
</span>
</Tooltip>
<InlineInput
ref={(el) => {
titleRef = el
}}
data-slot="session-title-child"
dir="auto"
value={title.draft}
disabled={props.pending.rename()}
class="block text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-base field-sizing-content self-start rounded-[6px] px-2 py-1"
style={{
"--inline-input-shadow": "none",
"text-align": "start",
}}
onInput={(event) => setTitle("draft", event.currentTarget.value)}
onKeyDown={(event) => {
event.stopPropagation()
if (event.isComposing || event.keyCode === 229) return
if (event.key === "Enter") {
event.preventDefault()
void saveTitleEditor()
return
}
if (event.key === "Escape") {
event.preventDefault()
closeTitleEditor()
}
}}
onBlur={() => void saveTitleEditor()}
/>
</Show>
<Show when={parentID()}>
<button
type="button"
data-slot="session-title-parent"
class="min-w-0 max-w-[40%] truncate pl-2 text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-faint transition-colors hover:text-v2-text-text-muted"
onClick={props.action.navigateParent}
>
{parentTitle()}
</button>
<span
data-slot="session-title-separator"
class="-translate-y-[0.5px] pl-2 pr-1 text-[11px] font-medium text-v2-text-text-faint"
aria-hidden="true"
>
/
</span>
</Show>
<Show when={childTitle() || title.editing}>
<Show
when={title.editing}
fallback={
<h1
data-slot="session-title-child"
class="truncate text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-base w-fit rounded-[6px] px-2 py-1 hover:bg-v2-overlay-simple-overlay-hover"
onClick={openTitleEditor}
>
{childTitle()}
</h1>
}
>
<InlineInput
ref={(el) => {
titleRef = el
}}
data-slot="session-title-child"
dir="auto"
value={title.draft}
disabled={props.pending.rename()}
class="block text-[13px] font-[530] leading-4 tracking-[-0.04px] text-v2-text-text-base field-sizing-content self-start rounded-[6px] px-2 py-1"
style={{
"--inline-input-shadow": "none",
"text-align": "start",
}}
onInput={(event) => setTitle("draft", event.currentTarget.value)}
onKeyDown={(event) => {
event.stopPropagation()
if (event.isComposing || event.keyCode === 229) return
if (event.key === "Enter") {
event.preventDefault()
void saveTitleEditor()
return
}
if (event.key === "Escape") {
event.preventDefault()
closeTitleEditor()
}
}}
onBlur={() => void saveTitleEditor()}
/>
</Show>
</Show>
</div>
</Show>
</div>
<Show when={sessionID()} keyed>
{(id) => (
<div class="shrink-0 flex items-center gap-2">
<SessionContextUsage placement="bottom" />
<Show when={!parentID() && project()}>
{(project) => (
<Popover open={summaryOpen()} placement="bottom-end" gutter={6} onOpenChange={setSummary}>
<Popover.Trigger
as={IconButton}
icon={<Icon name="window-analytics" />}
variant="ghost-muted"
size="large"
state={summaryOpen() ? "pressed" : undefined}
aria-label={language.t("session.summary.title")}
aria-expanded={summaryOpen()}
/>
<Popover.Portal>
<Popover.Content class="z-50 border-0 bg-transparent p-0 outline-none">
<SessionSummaryPanel
project={project()}
avatar={showProjectIcon() ? projectAvatar() : undefined}
directory={sessionDirectory()}
local={!workspaceSession()}
branch={data.location.vcs.info({ directory: sdk().directory })?.branch.current}
baseBranch={data.location.vcs.info({ directory: project().worktree })?.branch.current}
diffs={sessionDiffs()}
sessionID={id}
moveEligible={props.workspaceMoveEligible}
moveDismissed={workspaceSuggestionDismissed()}
onMoveDismiss={() => setWorkspaceSuggestionDismissed(true)}
onReview={() => {
setSummary(false)
props.onReview()
}}
backgroundTasks={props.background.tasks()}
/>
</Popover.Content>
</Popover.Portal>
</Popover>
)}
</Show>
<Show when={!parentID()}>
<Menu
gutter={6}
placement="bottom-end"
open={title.menuOpen}
onOpenChange={(open) => {
setTitle("menuOpen", open)
if (open) return
}}
>
<Menu.Trigger
</div>
<Show when={sessionID()} keyed>
{(id) => (
<div class="shrink-0 flex items-center gap-2">
<SessionContextUsage placement="bottom" />
<Show when={!parentID() && project()}>
{(project) => (
<Popover open={summaryOpen()} placement="bottom-end" gutter={6} onOpenChange={setSummary}>
<Popover.Trigger
as={IconButton}
icon={<Icon name="outline-dots" />}
icon={<Icon name="window-analytics" />}
variant="ghost-muted"
size="large"
aria-label={language.t("common.moreOptions")}
aria-expanded={title.menuOpen}
state={summaryOpen() ? "pressed" : undefined}
aria-label={language.t("session.summary.title")}
aria-expanded={summaryOpen()}
/>
<Menu.Portal>
<Menu.Content
style={{ width: "120px", "min-width": "120px" }}
onCloseAutoFocus={(event) => {
if (title.pendingRename) {
event.preventDefault()
setTitle("pendingRename", false)
openTitleEditor()
return
}
<Popover.Portal>
<Popover.Content class="z-50 border-0 bg-transparent p-0 outline-none">
<SessionSummaryPanel
project={project()}
avatar={showProjectIcon() ? projectAvatar() : undefined}
directory={sessionDirectory()}
local={!workspaceSession()}
branch={data.location.vcs.info({ directory: sdk().directory })?.branch.current}
baseBranch={data.location.vcs.info({ directory: project().worktree })?.branch.current}
diffs={sessionDiffs()}
sessionID={id}
moveEligible={props.workspaceMoveEligible}
moveDismissed={workspaceSuggestionDismissed()}
onMoveDismiss={() => setWorkspaceSuggestionDismissed(true)}
onReview={() => {
setSummary(false)
props.onReview()
}}
backgroundTasks={props.background.tasks()}
/>
</Popover.Content>
</Popover.Portal>
</Popover>
)}
</Show>
<Show when={!parentID()}>
<Menu
gutter={6}
placement="bottom-end"
open={title.menuOpen}
onOpenChange={(open) => {
setTitle("menuOpen", open)
if (open) return
}}
>
<Menu.Trigger
as={IconButton}
icon={<Icon name="outline-dots" />}
variant="ghost-muted"
size="large"
aria-label={language.t("common.moreOptions")}
aria-expanded={title.menuOpen}
/>
<Menu.Portal>
<Menu.Content
style={{ width: "120px", "min-width": "120px" }}
onCloseAutoFocus={(event) => {
if (title.pendingRename) {
event.preventDefault()
setTitle("pendingRename", false)
openTitleEditor()
return
}
}}
>
<Menu.Item
onSelect={() => {
setTitle("pendingRename", true)
setTitle("menuOpen", false)
}}
>
<Menu.Item
onSelect={() => {
setTitle("pendingRename", true)
setTitle("menuOpen", false)
}}
>
{language.t("common.rename")}
</Menu.Item>
<Menu.Item onSelect={() => void props.action.export(id)}>
{language.t("common.export")}...
</Menu.Item>
{/* TODO: Need a session archive API. */}
<Menu.Separator />
<Menu.Item onSelect={() => props.action.showDelete(id)}>
{language.t("common.delete")}...
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu>
</Show>
</div>
)}
</Show>
</div>
</SessionTitleHeader>
</Show>
{language.t("common.rename")}
</Menu.Item>
<Menu.Item onSelect={() => void props.action.export(id)}>
{language.t("common.export")}...
</Menu.Item>
{/* TODO: Need a session archive API. */}
<Menu.Separator />
<Menu.Item onSelect={() => props.action.showDelete(id)}>
{language.t("common.delete")}...
</Menu.Item>
</Menu.Content>
</Menu.Portal>
</Menu>
</Show>
</div>
)}
</Show>
</div>
</SessionTitleHeader>
}
/>
)
@@ -22,7 +22,6 @@ import {
type JSX,
} from "solid-js"
import { createStore } from "solid-js/store"
import { createMediaQuery } from "@solid-primitives/media"
import type { createTimelineProjection } from "./projection"
import { observeElementOffsetReconnectAware } from "./observe-element-offset"
import { filterVirtualIndexes } from "./virtual-items"
@@ -74,8 +73,6 @@ type ViewProps = {
export function createTimelineVirtualizer(input: Input) {
const language = useLanguage()
const isDesktop = createMediaQuery("(min-width: 768px)")
const topOffset = () => (input.showHeader() ? 64 : isDesktop() ? 0 : 16)
const ownerSessionKey = input.sessionKey()
const cached = cache.get(ownerSessionKey)
const initialMeasurements = cached?.measurements
@@ -189,7 +186,7 @@ export function createTimelineVirtualizer(input: Input) {
},
scrollEndThreshold: 80,
get scrollMargin() {
return topOffset()
return input.showHeader() ? 64 : 0
},
paddingEnd: 64,
get rangeExtractor() {
@@ -449,7 +446,7 @@ export function createTimelineVirtualizer(input: Input) {
data-timeline-key={rowProps.rowKey}
style={{
position: "absolute",
top: `${item().start - topOffset()}px`,
top: `${item().start - (input.showHeader() ? 64 : 0)}px`,
left: "0",
width: "100%",
height: `${item().size}px`,
@@ -519,9 +516,7 @@ export function createTimelineVirtualizer(input: Input) {
class="relative min-w-0 w-full h-full"
style={{ "--sticky-accordion-top": input.showHeader() ? "48px" : "0px" }}
>
<Show when={input.showHeader()} fallback={<div aria-hidden="true" class="h-4 md:hidden" />}>
{props.header}
</Show>
<Show when={input.showHeader()}>{props.header}</Show>
<div
data-timeline-virtual-content
ref={(element) => {
@@ -362,22 +362,6 @@ export const SettingsGeneral: Component<{
<ReasoningModeSetting />
<SettingsRow
title={language.t("session.review.wrapLines")}
description={language.t("settings.general.row.mobileDiffWrap.description")}
>
<div data-action="settings-mobile-diff-wrap">
<Switch
aria-label={language.t("session.review.wrapLines")}
checked={settings.general.mobileDiffWrap()}
onChange={settings.general.setMobileDiffWrap}
hideLabel
>
{language.t("session.review.wrapLines")}
</Switch>
</div>
</SettingsRow>
<SettingsRow
title={language.t("settings.general.row.shellToolPartsExpanded.title")}
description={language.t("settings.general.row.shellToolPartsExpanded.description")}
-6
View File
@@ -41,7 +41,6 @@ export interface Settings {
editToolPartsExpanded: boolean
showCustomAgents: boolean
mobileTitlebarPosition: "top" | "bottom"
mobileDiffWrap: boolean
terminalPlacement: TerminalPlacement
followUpBehavior: FollowUpBehavior
}
@@ -131,7 +130,6 @@ const defaultSettings: Settings = {
editToolPartsExpanded: false,
showCustomAgents: false,
mobileTitlebarPosition: "top",
mobileDiffWrap: true,
terminalPlacement: "side",
followUpBehavior: "steer",
},
@@ -270,10 +268,6 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
setMobileTitlebarPosition(value: "top" | "bottom") {
setStore("general", "mobileTitlebarPosition", value)
},
mobileDiffWrap: withFallback(() => store.general?.mobileDiffWrap, defaultSettings.general.mobileDiffWrap),
setMobileDiffWrap(value: boolean) {
setStore("general", "mobileDiffWrap", value)
},
terminalPlacement: withFallback(
() => store.general?.terminalPlacement,
defaultSettings.general.terminalPlacement,
@@ -1,44 +0,0 @@
import Drawer from "@corvu/drawer"
import type { ParentProps } from "solid-js"
import { useLanguage } from "@/runtime/i18n/language"
import "./status/status-drawer.css"
export function MobilePanelDrawer(
props: ParentProps<{
title: string
open: boolean
onOpenChange: (open: boolean) => void
returnFocus?: () => HTMLElement | undefined
}>,
) {
const language = useLanguage()
return (
<Drawer
open={props.open}
onOpenChange={props.onOpenChange}
side="bottom"
finalFocusEl={props.returnFocus?.()}
// Menu focus handoff must not dismiss the drawer during its opening transition.
closeOnOutsideFocus={false}
>
{/* Preserve Corvu's content and dismissal lifecycle across reopenings. */}
<Drawer.Portal forceMount>
<Drawer.Overlay data-slot="mobile-status-overlay" />
<Drawer.Content forceMount data-slot="mobile-status-drawer" dir={language.direction()}>
<div data-slot="mobile-status-drag-handle" aria-hidden="true">
<span />
</div>
<div data-slot="mobile-status-header" data-corvu-no-drag>
<Drawer.Label>{props.title}</Drawer.Label>
<Drawer.Close data-slot="mobile-status-close" aria-label={language.t("common.close")}>
{language.t("common.close")}
</Drawer.Close>
</div>
<div data-slot="mobile-status-content" data-corvu-no-drag>
{props.children}
</div>
</Drawer.Content>
</Drawer.Portal>
</Drawer>
)
}
+2 -8
View File
@@ -20,7 +20,7 @@ const pluginEmptyMessage = (value: string, file: string): JSXElement => {
)
}
export function StatusPopoverBody(props: { shown: boolean; embedded?: boolean }) {
export function StatusPopoverBody(props: { shown: boolean }) {
const data = useData()
const sdk = useWorkspaceLocation()
const serverSDK = useServerSDK()
@@ -42,13 +42,7 @@ export function StatusPopoverBody(props: { shown: boolean; embedded?: boolean })
const pluginEmpty = createMemo(() => pluginEmptyMessage(language.t("dialog.plugins.empty"), "opencode.json"))
return (
<div
class="flex items-center gap-1 rounded-xl"
classList={{
"w-[360px] shadow-[var(--shadow-lg-border-base)]": !props.embedded,
"w-full min-w-0": props.embedded,
}}
>
<div class="flex items-center gap-1 w-[360px] rounded-xl shadow-[var(--shadow-lg-border-base)]">
<Tabs
aria-label={language.t("status.popover.ariaLabel")}
class="tabs bg-background-strong rounded-xl overflow-hidden"
@@ -1,145 +0,0 @@
[data-slot="mobile-status-overlay"] {
position: fixed;
inset: 0;
z-index: 50;
background: var(--v2-overlay-simple-overlay-scrim);
animation: mobile-status-backdrop-in 240ms ease-out;
}
[data-slot="mobile-status-overlay"]:is([data-closing], [data-closed]) {
animation: mobile-status-backdrop-out 200ms ease-in forwards;
}
[data-slot="mobile-status-drawer"] {
box-sizing: border-box;
position: fixed;
inset-inline: 0;
bottom: 0;
z-index: 51;
display: flex;
flex-direction: column;
max-height: min(75dvh, calc(100dvh - env(safe-area-inset-top, 0px) - 16px));
padding: 0 12px max(12px, env(safe-area-inset-bottom, 0px));
padding-left: max(12px, env(safe-area-inset-left, 0px));
padding-right: max(12px, env(safe-area-inset-right, 0px));
border-radius: 16px 16px 0 0;
background: var(--v2-background-bg-deep);
color: var(--v2-text-text-base);
box-shadow: var(--v2-elevation-overlay);
outline: none;
app-region: no-drag;
}
[data-slot="mobile-status-drawer"][data-transitioning] {
transition: transform 240ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
[data-slot="mobile-status-drawer"][data-closing] {
transition-duration: 200ms;
}
[data-slot="mobile-status-drawer"][data-closed] {
visibility: hidden;
pointer-events: none;
}
[data-slot="mobile-status-drag-handle"] {
display: flex;
height: 28px;
flex-shrink: 0;
align-items: center;
justify-content: center;
touch-action: none;
}
[data-slot="mobile-status-drag-handle"] span {
width: 32px;
height: 4px;
border-radius: 999px;
background: var(--v2-border-border-strong);
}
[data-slot="mobile-status-header"] {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
padding-inline-start: 8px;
padding-block-end: 8px;
}
[data-slot="mobile-status-header"] h2 {
margin: 0;
font-size: 14px;
font-weight: 530;
line-height: var(--line-height-base);
}
[data-slot="mobile-status-close"] {
min-height: 44px;
flex-shrink: 0;
padding-inline: 12px;
border-radius: 6px;
color: var(--v2-text-text-base);
font-size: 13px;
line-height: var(--line-height-compact);
}
@media (hover: hover) {
[data-slot="mobile-status-close"]:hover {
background: var(--v2-overlay-simple-overlay-hover);
}
}
[data-slot="mobile-status-close"]:focus-visible {
outline: 2px solid var(--v2-border-border-focus);
outline-offset: -2px;
}
[data-slot="mobile-status-content"] {
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
touch-action: pan-y;
}
[data-slot="mobile-status-loading"] {
display: flex;
min-height: 56px;
align-items: center;
justify-content: center;
color: var(--v2-text-text-muted);
font-size: 13px;
line-height: var(--line-height-base);
}
@keyframes mobile-status-backdrop-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes mobile-status-backdrop-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@media (prefers-reduced-motion: reduce) {
[data-slot="mobile-status-drawer"][data-transitioning],
[data-slot="mobile-status-drawer"][data-closing] {
transition: none;
}
[data-slot="mobile-status-overlay"],
[data-slot="mobile-status-overlay"]:is([data-closing], [data-closed]) {
animation: none;
}
}
@@ -1,35 +0,0 @@
import { lazy, Suspense } from "solid-js"
import { useLanguage } from "@/runtime/i18n/language"
import { MobilePanelDrawer } from "../mobile-panel-drawer"
const Body = lazy(async () => {
const { StatusPopoverBody } = await import("./body")
return { default: StatusPopoverBody }
})
export function StatusDrawer(props: {
open: boolean
onOpenChange: (open: boolean) => void
returnFocus?: () => HTMLElement | undefined
}) {
const language = useLanguage()
return (
<MobilePanelDrawer
title={language.t("status.popover.trigger")}
open={props.open}
onOpenChange={props.onOpenChange}
returnFocus={props.returnFocus}
>
<Suspense
fallback={
<div data-slot="mobile-status-loading" role="status">
{language.t("common.loading")}
</div>
}
>
<Body shown={props.open} embedded />
</Suspense>
</MobilePanelDrawer>
)
}
@@ -1,79 +0,0 @@
import { afterEach, beforeEach, expect, test } from "bun:test"
import { MemoryRouter, createMemoryHistory } from "@solidjs/router"
import { createComponent, render } from "solid-js/web"
import { isStandalone, PwaRoutePersistence, restorePwaRoute } from "../src/runtime/platform/pwa"
const key = "opencode.pwa.last-route"
const originalUrl = window.location.href
beforeEach(() => {
window.location.href = "http://localhost/"
})
afterEach(() => {
localStorage.removeItem(key)
window.location.href = originalUrl
})
test("normal browser windows are not standalone", () => {
expect(isStandalone()).toBe(false)
})
test("restores the last PWA route including query and hash without adding history", () => {
window.history.replaceState({ retained: true }, "", "http://localhost/")
const length = window.history.length
localStorage.setItem(key, "/server/local/session/session-1?view=files#file")
restorePwaRoute()
expect(window.location.pathname + window.location.search + window.location.hash).toBe(
"/server/local/session/session-1?view=files#file",
)
expect(window.history.length).toBe(length)
expect(window.history.state).toEqual({ retained: true })
})
test("preserves explicit launch routes, queries, and hashes", () => {
localStorage.setItem(key, "/server/local/session/saved")
for (const route of ["/server/local/session/linked", "/new-session?draftId=123", "/?launch=1", "/#launch"]) {
window.history.replaceState(null, "", `http://localhost${route}`)
restorePwaRoute()
expect(window.location.pathname + window.location.search + window.location.hash).toBe(route)
}
})
test("ignores missing, invalid, external, and auth-bearing saved routes", () => {
window.history.replaceState(null, "", "http://localhost/")
restorePwaRoute()
expect(window.location.pathname).toBe("/")
for (const value of [
"/removed-route",
"https://example.com/new-session",
"//example.com/new-session",
"http://[",
"/new-session?auth_token=secret",
]) {
localStorage.setItem(key, value)
restorePwaRoute()
expect(window.location.href).toBe("http://localhost/")
}
})
test("persists router navigation including returning home", async () => {
const host = document.createElement("div")
const history = createMemoryHistory()
history.set({ value: "/new-session?draftId=123", replace: true, scroll: false })
const dispose = render(() => createComponent(MemoryRouter, { history, root: PwaRoutePersistence }), host)
try {
expect(localStorage.getItem(key)).toBe("/new-session?draftId=123")
history.set({ value: "/server/local/session/next#file", scroll: false })
await new Promise((resolve) => setTimeout(resolve, 0))
expect(localStorage.getItem(key)).toBe("/server/local/session/next#file")
history.set({ value: "/", scroll: false })
await new Promise((resolve) => setTimeout(resolve, 0))
expect(localStorage.getItem(key)).toBe("/")
} finally {
dispose()
}
})
-34
View File
@@ -6,7 +6,6 @@ Private generation target for clients derived directly from OpenCode's authorita
- `@opencode-ai/client`: zero-Effect Promise client using `fetch`.
- `@opencode-ai/client/effect`: rich Effect network client using an environment-provided `HttpClient`.
- `@opencode-ai/client/effect/websocket`: native Effect RPC over a single scoped WebSocket.
The generated surface includes every standard HTTP group from Server's concrete API. The build compiler reads `@opencode-ai/server/api`; the generated Effect runtime imports a client-local projection built from Protocol, with a generation-equivalence test preventing transport drift. Custom transports such as the PTY WebSocket connection remain outside the generic HTTP client. Run `bun run generate` after changing the contract and `bun run check:generated` to detect committed-output drift.
@@ -26,36 +25,3 @@ yield *
})
yield * client.sessions.prompt({ sessionID, prompt: Prompt.make({ text: "Hello" }) })
```
## WebSocket RPC
The additive `/api/rpc` transport derives its operation contracts from Protocol's HTTP schemas; existing HTTP clients are unchanged. Use operation identifiers directly, with decoded `params`, `query`, and `payload` fields where declared. Numeric queries are numbers, not HTTP strings. Optional `location: { directory, workspace? }` selects per-call location context; session-specific operations retain their existing session location rules.
```ts
import { OpenCodeRpc } from "@opencode-ai/client/effect/websocket"
import { Effect, Redacted, Stream } from "effect"
declare const token: string // Base64 of "opencode:<server password>", not the raw password.
const program = Effect.gen(function* () {
const client = yield* OpenCodeRpc.make({
url: "wss://opencode.example/api/rpc",
authToken: Redacted.make(token),
})
const events = yield* client["event.subscribe"]({}).pipe(
Stream.runForEach((event) => Effect.log(event.type)),
Effect.forkScoped,
)
const sessions = yield* client["session.list"]({ query: {} })
// Both requests share the connection; interrupting events cancels only that subscription.
return sessions
})
Effect.runPromise(Effect.scoped(program))
```
Keep the scope open while consuming streams. Scope closure closes the socket and cancels outstanding work. Connection failures are surfaced rather than replaying potentially mutating requests; create a new scoped client to reconnect. Browsers use their native WebSocket constructor, with an optional `webSocketConstructor` override for other runtimes. Authentication uses the server's existing `auth_token` upgrade mechanism; treat the resulting URL as sensitive and do not log it.
Streaming operations return native Effect Streams of the original typed items, not SSE text. No-content operations return `void`. `fs.read` takes `params: { path: "relative/file" }` plus `query: {}` and returns `{ content: Uint8Array, mime: string }`, with bytes encoded as base64 on the wire. Raw `pty.connect` and `persistentPty.connect` remain on their existing WebSocket routes.
From `packages/server`, run `bun run script/benchmark-rpc.ts` for an isolated loopback comparison of HTTP and RPC session-list calls. It uses an in-memory database, temporary configuration, and schema-decoding clients at concurrency 1 and 16. This measures transport overhead, not end-to-end desktop/web speed; the apps still use HTTP until explicitly switched.
-1
View File
@@ -23,7 +23,6 @@
"./solid": "./src/solid/index.ts",
"./effect": "./src/effect/index.ts",
"./effect/api": "./src/effect/api.ts",
"./effect/websocket": "./src/effect/websocket.ts",
"./effect/service": "./src/effect/service.ts"
},
"scripts": {
-35
View File
@@ -1,35 +0,0 @@
export * as OpenCodeRpc from "./websocket.js"
import { Group, type Rpcs } from "@opencode-ai/protocol/rpc"
import { Effect, Redacted, Schedule, Scope } from "effect"
import { RpcClient, RpcClientError, RpcSerialization } from "effect/unstable/rpc"
import { Socket } from "effect/unstable/socket"
export interface Options {
/** Full WebSocket endpoint, for example wss://opencode.example/api/rpc. */
readonly url: string | URL
/** Existing server auth_token, sent only during the WebSocket upgrade. */
readonly authToken?: Redacted.Redacted<string>
readonly webSocketConstructor?: Socket.WebSocketConstructor["Service"]
}
export type Client = RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError>
/** One scoped connection multiplexes all unary calls and streaming subscriptions. */
export const make: (options: Options) => Effect.Effect<Client, never, Scope.Scope> = Effect.fnUntraced(
function* (options) {
const url = new URL(options.url)
if (options.authToken) url.searchParams.set("auth_token", Redacted.value(options.authToken))
const socket = yield* Socket.makeWebSocket(url.toString()).pipe(
Effect.provideService(
Socket.WebSocketConstructor,
options.webSocketConstructor ?? ((url, protocols) => new WebSocket(url, protocols)),
),
)
const protocol = yield* RpcClient.makeProtocolSocket({ retryPolicy: Schedule.recurs(0) }).pipe(
Effect.provideService(Socket.Socket, socket),
Effect.provideService(RpcSerialization.RpcSerialization, RpcSerialization.json),
)
return yield* RpcClient.make(Group).pipe(Effect.provideService(RpcClient.Protocol, protocol))
},
)
+19 -18
View File
@@ -3,7 +3,7 @@ export * as SharedEvents from "./shared-events.js"
export function make<A extends { readonly type: string }>(connect: (signal: AbortSignal) => AsyncIterable<A>) {
type Completion = { readonly error: unknown } | Record<string, never>
type Subscriber = {
push: (value: A) => void
push: (value: A) => Promise<void>
finish: (completion: Completion) => void
}
type Connection = {
@@ -13,7 +13,7 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
}
let current: Connection | undefined
const capacity = 4_096
const delivered = Promise.resolve()
function stop(connection: Connection) {
connection.connected = undefined
@@ -31,7 +31,7 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
const item = await iterator.next()
if (item.done || connection.controller.signal.aborted) break
if (item.value.type === "server.connected") connection.connected = item.value
connection.subscribers.forEach((subscriber) => subscriber.push(item.value))
await Promise.all(Array.from(connection.subscribers, (subscriber) => subscriber.push(item.value)))
}
} catch (error) {
completion = { error }
@@ -51,14 +51,15 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
return {
[Symbol.asyncIterator]() {
const pending: ReturnType<typeof Promise.withResolvers<IteratorResult<A>>>[] = []
const queued: A[] = []
let started = false
let completion: Completion | undefined
let connection: Connection | undefined
let offered: { readonly value: A; readonly accepted: ReturnType<typeof Promise.withResolvers<void>> } | undefined
function finish(result: Completion, discard = true) {
function finish(result: Completion) {
completion = result
if (discard) queued.length = 0
offered?.accepted.resolve()
offered = undefined
options?.signal?.removeEventListener("abort", abort)
if (connection?.subscribers.delete(subscriber) && !connection.subscribers.size) stop(connection)
pending.splice(0).forEach((request) => {
@@ -72,21 +73,17 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
}
const subscriber: Subscriber = {
finish(result) {
finish(result, false)
},
finish,
push(value) {
if (completion) return
if (completion) return delivered
const request = pending.shift()
if (request) {
request.resolve({ done: false, value })
return
return delivered
}
if (queued.length === capacity) {
finish({ error: new Error(`Event subscriber exceeded its ${capacity}-event capacity`) })
return
}
queued.push(value)
const accepted = Promise.withResolvers<void>()
offered = { value, accepted }
return accepted.promise
},
}
@@ -105,8 +102,12 @@ export function make<A extends { readonly type: string }>(connect: (signal: Abor
return {
next(): Promise<IteratorResult<A>> {
const value = queued.shift()
if (value) return Promise.resolve({ done: false, value })
if (offered) {
const current = offered
offered = undefined
current.accepted.resolve()
return Promise.resolve({ done: false, value: current.value })
}
if (completion) {
if ("error" in completion) return Promise.reject(completion.error)
return Promise.resolve({ done: true, value: undefined })
+2 -6
View File
@@ -618,17 +618,13 @@ export function createData(config: CreateDataInput) {
})
.catch((error) => console.error("Failed to load projected model switch message", error))
return
case "session.renamed": {
case "session.renamed":
// Preserve the live title when it races the session's initial read.
const family = sync.pending(`session.family:${event.data.sessionID}`)
? result.session.sync(event.data.sessionID, { children: true })
: Promise.resolve()
void Promise.all([result.session.sync(event.data.sessionID), family]).then(() => {
void result.session.sync(event.data.sessionID).then(() => {
if (store.session.info[event.data.sessionID])
setStore("session", "info", event.data.sessionID, "title", event.data.title)
})
return
}
case "session.moved": {
const current = store.session.info[event.data.sessionID]
if (current) {
@@ -28,12 +28,6 @@ describe("public import boundaries", () => {
expect(within(network.all, core)).toEqual([])
expect(within(network.all, server)).toEqual([])
const rpc = await bundleInputs("@opencode-ai/client/effect/websocket", "browser")
expect(within(rpc.eager, effect).length).toBeGreaterThan(0)
expect(within(rpc.eager, protocol).length).toBeGreaterThan(0)
expect(within(rpc.all, core)).toEqual([])
expect(within(rpc.all, server)).toEqual([])
const promiseService = await bundleInputs("@opencode-ai/client/service", "bun")
expect(within(promiseService.all, effect)).toEqual([])
+1 -59
View File
@@ -97,11 +97,7 @@ test("multiple consumers share one source and receive live native and RPC events
const first = shared.subscribe()[Symbol.asyncIterator]()
const second = shared.subscribe()[Symbol.asyncIterator]()
for (const event of [
{ type: "server.connected" },
{ type: "session.updated" },
{ type: "rpc.example.updated", value: 1 },
]) {
for (const event of [{ type: "server.connected" }, { type: "session.updated" }, { type: "rpc.example.updated", value: 1 }]) {
const reads = [first.next(), second.next()]
events.connections[0].push(event)
expect(await Promise.all(reads)).toEqual([
@@ -119,60 +115,6 @@ test("multiple consumers share one source and receive live native and RPC events
await events.connections[0].closed
})
test("an idle consumer does not stall events for an active consumer", async () => {
const events = source()
const shared = SharedEvents.make(events.connect)
const idle = shared.subscribe()[Symbol.asyncIterator]()
const active = shared.subscribe()[Symbol.asyncIterator]()
const connected = [idle.next(), active.next()]
events.connections[0].push({ type: "server.connected" })
await Promise.all(connected)
for (const event of [
{ type: "session.updated", value: 1 },
{ type: "session.updated", value: 2 },
]) {
const next = active.next()
events.connections[0].push(event)
expect(
await Promise.race([next, Bun.sleep(1_000).then(() => ({ done: true as const, value: { type: "timeout" } }))]),
).toEqual({ done: false, value: event })
}
await idle.return!()
await active.return!()
await events.connections[0].closed
})
test("an idle consumer fails instead of buffering events without bound", async () => {
const events = source()
const idle = SharedEvents.make(events.connect).subscribe()[Symbol.asyncIterator]()
const connected = idle.next()
events.connections[0].push({ type: "server.connected" })
await connected
Array.from({ length: 4_097 }, (_, value) => events.connections[0].push({ type: "session.updated", value }))
await events.connections[0].closed
await expect(idle.next()).rejects.toThrow("Event subscriber exceeded its 4096-event capacity")
})
test("source completion preserves events already buffered for an idle consumer", async () => {
const events = source()
const idle = SharedEvents.make(events.connect).subscribe()[Symbol.asyncIterator]()
const connected = idle.next()
events.connections[0].push({ type: "server.connected" })
await connected
events.connections[0].push({ type: "session.updated", value: 1 })
events.connections[0].push({ type: "session.updated", value: 2 })
events.connections[0].close()
await events.connections[0].closed
await Bun.sleep(0)
expect(await idle.next()).toEqual({ done: false, value: { type: "session.updated", value: 1 } })
expect(await idle.next()).toEqual({ done: false, value: { type: "session.updated", value: 2 } })
expect(await idle.next()).toEqual({ done: true, value: undefined })
})
test("late consumers receive the latest connection marker but no business event replay", async () => {
const events = source()
const shared = SharedEvents.make(events.connect)
-57
View File
@@ -73,63 +73,6 @@ test("revalidates after an event overtakes an active session read", async () =>
}
})
test("preserves a live session rename across concurrent session and family reads", async () => {
const family = Promise.withResolvers<void>()
const renamed = Promise.withResolvers<void>()
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
let requests = 0
const stale = { ...session(0), title: undefined }
const api = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
if (!request.url.endsWith(`/api/session/${stale.id}`)) return Response.json({ data: [], cursor: {} })
requests++
await (requests === 1 ? family.promise : renamed.promise)
return Response.json({ data: stale })
},
})
const setup = createRoot((dispose) => ({
data: createData({
api: () => api,
directory: "/project",
event: {
on: () => () => {},
listen(handler) {
listeners.add(handler)
return () => listeners.delete(handler)
},
},
}),
dispose,
}))
try {
const initial = setup.data.session.sync(stale.id, { children: true })
await wait(() => requests === 1)
const event: OpenCodeEvent = {
id: "evt_renamed",
created: 1,
type: "session.renamed",
durable: { aggregateID: stale.id, seq: 1, version: 1 },
data: { sessionID: stale.id, title: "Generated title" },
}
listeners.forEach((listener) => listener({ name: event.type, details: event }))
await wait(() => requests === 2)
renamed.resolve()
await wait(() => setup.data.session.get(stale.id) !== undefined)
family.resolve()
await initial
await Bun.sleep(0)
expect(setup.data.session.get(stale.id)?.title).toBe("Generated title")
} finally {
family.resolve()
renamed.resolve()
setup.dispose()
}
})
test("updates authoritative cached project metadata from live events", async () => {
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
const original: Project = {
-105
View File
@@ -1,105 +0,0 @@
import { expect, test } from "bun:test"
import { createServer } from "node:http"
import { NodeHttpServer } from "@effect/platform-node"
import { ClientApi } from "@opencode-ai/protocol/client"
import { SessionNotFoundError } from "@opencode-ai/protocol/errors"
import { Group, fromEndpoint } from "@opencode-ai/protocol/rpc"
import { Event } from "@opencode-ai/schema/event"
import { Session } from "@opencode-ai/schema/session"
import { Deferred, Effect, Fiber, Redacted, Stream } from "effect"
import { RpcGroup, RpcSerialization, RpcServer } from "effect/unstable/rpc"
import { OpenCodeRpc } from "../src/effect/websocket.js"
test("one scoped socket multiplexes unary calls and cancellable typed streams", async () => {
const sockets: WebSocket[] = []
await Effect.gen(function* () {
const started = yield* Deferred.make<void>()
const stopped = yield* Deferred.make<void>()
const group = RpcGroup.make(
fromEndpoint(ClientApi.groups["server.health"].endpoints["health.get"]),
fromEndpoint(ClientApi.groups["server.session"].endpoints["session.list"]),
fromEndpoint(ClientApi.groups["server.session"].endpoints["session.get"]),
fromEndpoint(ClientApi.groups["server.session"].endpoints["session.remove"]),
fromEndpoint(ClientApi.groups["server.event"].endpoints["event.subscribe"]),
fromEndpoint(ClientApi.groups["server.fs"].endpoints["fs.read"]),
)
const app = yield* RpcServer.toHttpEffectWebsocket(group).pipe(
Effect.provide(
group.toLayer({
"health.get": () => Effect.succeed({ healthy: true, version: "test", pid: 0 }),
"session.list": () => Effect.succeed({ data: [], cursor: {} }),
"session.get": ({ params }) =>
Effect.fail(new SessionNotFoundError({ sessionID: params.sessionID, message: "missing" })),
"session.remove": () => Effect.void,
"fs.read": () => Effect.succeed({ content: new Uint8Array([0, 255, 128]), mime: "application/octet-stream" }),
"event.subscribe": () =>
Stream.fromEffect(Deferred.succeed(started, undefined)).pipe(
Stream.map(() => ({ id: Event.ID.make("evt_connected"), type: "server.connected" as const, data: {} })),
Stream.concat(Stream.never),
Stream.ensuring(Deferred.succeed(stopped, undefined)),
),
}),
),
Effect.provideService(RpcSerialization.RpcSerialization, RpcSerialization.json),
)
const server = yield* NodeHttpServer.make(createServer, { host: "127.0.0.1", port: 0 })
yield* server.serve(app)
if (server.address._tag !== "TcpAddress") return yield* Effect.die("Expected TCP listener")
yield* Effect.scoped(
Effect.gen(function* () {
const client = yield* OpenCodeRpc.make({
url: `ws://127.0.0.1:${server.address._tag === "TcpAddress" ? server.address.port : 0}/api/rpc`,
authToken: Redacted.make("test-token"),
webSocketConstructor: (url, protocols) => {
expect(new URL(url).searchParams.get("auth_token")).toBe("test-token")
const socket = new WebSocket(url, protocols)
sockets.push(socket)
return socket
},
})
const received = yield* Deferred.make<void>()
const events = yield* client["event.subscribe"]({}).pipe(
Stream.runForEach((event) => {
expect(event.type).toBe("server.connected")
return Deferred.succeed(received, undefined)
}),
Effect.forkScoped,
)
yield* Deferred.await(started)
yield* Deferred.await(received)
const [health, sessions, file] = yield* Effect.all(
[
client["health.get"]({}),
client["session.list"]({ query: {} }),
client["fs.read"]({ params: { path: "a.bin" }, query: {} }),
],
{ concurrency: "unbounded" },
)
expect(health).toEqual({ healthy: true, version: "test", pid: 0 })
expect(sessions).toEqual({ data: [], cursor: {} })
expect(file.content).toEqual(new Uint8Array([0, 255, 128]))
const error = yield* client["session.get"]({ params: { sessionID: Session.ID.make("ses_missing") } }).pipe(
Effect.flip,
)
expect(error).toBeInstanceOf(SessionNotFoundError)
expect(yield* client["session.remove"]({ params: { sessionID: Session.ID.make("ses_test") } })).toBeUndefined()
yield* Fiber.interrupt(events)
yield* Deferred.await(stopped)
expect((yield* client["health.get"]({})).healthy).toBe(true)
expect(sockets).toHaveLength(1)
}),
)
}).pipe(Effect.scoped, Effect.timeout("10 seconds"), Effect.runPromise)
expect(sockets[0]!.readyState).toBe(WebSocket.CLOSED)
})
// The derived client keeps operation-specific request and response types.
type Client = Effect.Success<ReturnType<typeof OpenCodeRpc.make>>
type HasRawPty = "pty.connect" extends keyof Client ? true : false
const noRawPty: HasRawPty = false
type Tags = RpcGroup.Rpcs<typeof Group>["_tag"]
const fileTag: Tags = "fs.read"
test("raw PTY is not part of the typed client", () => {
expect(noRawPty).toBe(false)
expect(fileTag).toBe("fs.read")
})
+1 -1
View File
@@ -180,7 +180,7 @@ export const toTypeScript = (schema: Schema.Top, decoded = false, pretty = false
export const jsonSchemaToTypeScript = (schema: JsonSchema, pretty = false): string => {
try {
return renderSchema(schema, { definitions: {}, pretty })
return renderSchema(schema, { definitions: { ...(schema.definitions ?? {}), ...(schema.$defs ?? {}) }, pretty })
} catch {
return "unknown"
}
-29
View File
@@ -216,35 +216,6 @@ describe("pretty signature rendering", () => {
})
})
describe("JSON Schema definition scope", () => {
test.each(["definitions", "$defs"])("resolves root %s and lets $defs take precedence", (key) => {
const schema = { $ref: `#/${key}/Value`, [key]: { Value: { type: "string" } } }
expect(jsonSchemaToTypeScript(schema)).toBe("string")
expect(jsonSchemaToTypeScript(schema, true)).toBe("string")
const overridden = { ...schema, $defs: { Value: { type: "number" } } }
expect(jsonSchemaToTypeScript(overridden)).toBe("number")
expect(jsonSchemaToTypeScript(overridden, true)).toBe("number")
})
test.each(["definitions", "$defs"])("nested %s shadow inherited definitions without affecting siblings", (key) => {
const schema = {
type: "object",
definitions: { Inherited: { type: "string" } },
$defs: { Value: { type: "number" } },
properties: {
nested: { $ref: `#/${key}/Value`, [key]: { Value: { type: "boolean" } } },
inherited: { $ref: "#/definitions/Inherited" },
sibling: { $ref: "#/$defs/Value" },
},
}
expect(jsonSchemaToTypeScript(schema)).toBe("{ nested?: boolean; inherited?: string; sibling?: number }")
expect(jsonSchemaToTypeScript(schema, true)).toBe(
["{", " nested?: boolean,", " inherited?: string,", " sibling?: number,", "}"].join("\n"),
)
})
})
describe("non-identifier property names render as quoted keys", () => {
// MCP-style schemas routinely carry property names that are not bare TS identifiers
// (`foo-bar`, `@type`, dotted names); the rendered signature must quote them so the
+8 -1
View File
@@ -327,7 +327,12 @@ function modelFromLanguage(info: Info, language: LanguageModelV3) {
},
body: {
schema: Schema.Unknown,
from: (request) => Effect.succeed(callOptions(request, packageName, info.modelID ?? info.id, optionKey)),
from: (request) =>
Effect.try({
try: () => callOptions(request, packageName, info.modelID ?? info.id, optionKey),
catch: (cause) =>
cause instanceof AIError ? cause : ProviderShared.invalidRequest("Invalid AI SDK request", cause),
}),
},
with: () => route,
model: (input) =>
@@ -512,6 +517,8 @@ function userPart(part: ContentPart): UserContent {
function assistantPart(part: ContentPart): AssistantContent {
switch (part.type) {
case "compaction":
throw ProviderShared.invalidRequest("AI SDK routes cannot replay native provider compaction state")
case "text":
return [{ type: "text", text: part.text, providerOptions: metadataProviderOptions(part.providerMetadata) }]
case "media":
+3 -2
View File
@@ -54,8 +54,9 @@ const layer = Layer.effect(
})
const file = Effect.fn("Formatter.file")(function* (filepath: string) {
const extension = path.extname(filepath)
const matching = state.get().formatters.filter((formatter) => formatter.extensions.includes(extension))
const matching = state
.get()
.formatters.filter((formatter) => formatter.extensions.includes(path.extname(filepath)))
for (const formatter of matching) {
const enabled = yield* command(formatter)
+1 -1
View File
@@ -95,7 +95,7 @@ export function convertHTMLToMarkdown(html: string) {
const remaining = limit - outputBytes
const next = bytes.byteLength <= remaining ? value : sliceBytes(value, remaining)
output.push(next)
outputBytes += bytes.byteLength <= remaining ? bytes.byteLength : encoder.encode(next).byteLength
outputBytes += encoder.encode(next).byteLength
last = next.at(-1) ?? last
}
const appendRaw = (value: string) => {
+27
View File
@@ -10,6 +10,8 @@ import { Provider } from "@opencode-ai/core/provider"
import {
LLM,
AIError,
CompactionPart,
ProviderID,
HttpContext,
LLMEvent,
Message,
@@ -68,6 +70,31 @@ const client = LLMClient.layer.pipe(
),
)
it.effect("rejects native provider compaction rather than silently dropping replay state", () =>
Effect.gen(function* () {
const aisdk = yield* AISDK.Service
yield* aisdk.hook.sdk((event) => {
event.sdk = { languageModel: () => streamModel([]) }
})
const resolved = yield* aisdk.model(model("@ai-sdk/openai"))
const error = yield* compileRequest(
LLM.request({
model: resolved,
messages: [
Message.assistant(
CompactionPart.make({
provider: ProviderID.make("test-provider"),
encrypted: "opaque",
}),
),
],
}),
).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidRequest")
expect(error.message).toContain("cannot replay")
}),
)
it.effect("keys language models by package and flattened overlays", () =>
Effect.gen(function* () {
const aisdk = yield* AISDK.Service
-28
View File
@@ -58,34 +58,6 @@ function withFormatter<A, E, R>(
}
describe("Formatter", () => {
;[
{ file: "test.match", extension: ".match", matches: true },
{ file: "test.other", extension: ".match", matches: false },
{ file: "test.MATCH", extension: ".match", matches: false },
{ file: "test.MATCH", extension: ".MATCH", matches: true },
{ file: ".match", extension: ".match", matches: false },
{ file: ".match", extension: "", matches: true },
{ file: "README", extension: ".match", matches: false },
{ file: "README", extension: "", matches: true },
{ file: "test.part.match", extension: ".match", matches: true },
{ file: "test.part.match", extension: ".part.match", matches: false },
].forEach((entry) =>
it.live(`matches ${entry.file} against ${JSON.stringify(entry.extension)}: ${entry.matches}`, () =>
withFormatter(
{
matching: {
command: [process.execPath, "-e", "process.exit(0)", "$FILE"],
extensions: [entry.extension],
},
},
(formatter, directory) =>
Effect.gen(function* () {
expect(yield* formatter.file(path.join(directory, entry.file))).toBe(entry.matches)
}),
),
),
)
it.live("does not run formatters marked as disabled in config", () =>
withFormatter(
{
-9
View File
@@ -128,15 +128,6 @@ describe("WebFetchTool helpers", () => {
expect(output).toHaveLength(WebFetchTool.MAX_RESPONSE_BYTES - 64 * 1024)
})
test.each(["x", "\u00e9", "\u{1f600}"])("preserves UTF-8 boundaries at the content limit for %s", (character) => {
const budget = WebFetchTool.MAX_RESPONSE_BYTES - 64 * 1024
const fitting = "aa" + character.repeat(Math.floor((budget - 2) / Buffer.byteLength(character)))
expect(WebFetchTool.convertHTMLToMarkdown(fitting)).toBe(fitting)
const truncated = WebFetchTool.convertHTMLToMarkdown(fitting + character)
expect(truncated).toBe(fitting)
expect(Buffer.byteLength(truncated)).toBe(Buffer.byteLength(fitting))
})
test("bounds deeply nested list output and fragmented code fences", () => {
const lists = `${"<ul><li>item".repeat(2_000)}${"</li></ul>".repeat(2_000)}`
const quotes = `${"<blockquote><p>item".repeat(2_000)}${"</p></blockquote>".repeat(2_000)}`
-117
View File
@@ -1,117 +0,0 @@
export * as OpenCodeRpc from "./rpc.js"
import { Predicate, Schema, SchemaAST, Stream } from "effect"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema } from "effect/unstable/httpapi"
import { Rpc, RpcGroup, RpcSchema } from "effect/unstable/rpc"
import { ClientApi } from "./client.js"
import { LocationQuery } from "./groups/location.js"
export const omitEndpoints: ReadonlySet<string> = new Set(["pty.connect", "persistentPty.connect"])
export const FileRead = Schema.Struct({ content: Schema.Uint8ArrayFromBase64, mime: Schema.String })
export const FileReadParams = Schema.Struct({ path: Schema.String })
type Part<K extends string, S extends Schema.Constraint> = [S] extends [never] ? {} : { readonly [P in K]: S["Type"] }
export type Request<E extends HttpApiEndpoint.ConstraintRequest> = (E["identifier"] extends "fs.read"
? { readonly params: typeof FileReadParams.Type }
: Part<"params", E["~Params"]>) &
Part<"query", E["~Query"]> &
Part<"payload", E["~Payload"]> &
Part<"headers", E["~Headers"]> & {
readonly location?: typeof LocationQuery.Type.location
}
type Success<S extends Schema.Constraint> =
S["Type"] extends Stream.Stream<infer A, infer E>
? RpcSchema.Stream<Schema.Codec<A, unknown>, Schema.Codec<E, unknown>>
: Schema.Codec<S["Type"], unknown>
export type Endpoint<E extends HttpApiEndpoint.ConstraintRequest> = E extends HttpApiEndpoint.ConstraintRequest
? E["identifier"] extends "pty.connect" | "persistentPty.connect"
? never
: Rpc.Rpc<
E["identifier"],
Schema.Codec<Request<E>, unknown>,
E["identifier"] extends "fs.read" ? typeof FileRead : Success<E["~Success"]>,
Schema.Codec<E["~Error"]["Type"] | HttpApiMiddleware.Error<E["~Middleware"]>, unknown>
>
: never
type Endpoints<G extends HttpApiGroup.Constraint> =
HttpApiGroup.Endpoints<G> extends infer E
? E extends HttpApiEndpoint.ConstraintRequest
? Endpoint<E>
: never
: never
/** Convert HTTP stream declarations to RPC streams without serializing an SSE envelope. */
export function successSchema(schema: Schema.Top): Schema.Top {
if (RpcSchema.isStreamSchema(schema)) return schema
if (!isHttpStream(schema)) return Schema.toCodecJson(schema)
if (schema._tag === "StreamUint8Array") {
return RpcSchema.Stream(Schema.Uint8ArrayFromBase64, Schema.Unknown)
}
if (schema.sseMode === "events") {
return RpcSchema.Stream(Schema.toCodecJson(schema.events), Schema.toCodecJson(schema.error))
}
// StreamSse({ data }) stores its original data codec in the event struct's data field.
const ast = SchemaAST.toType(schema.events.ast)
const data = SchemaAST.isObjects(ast) ? ast.propertySignatures.find((field) => field.name === "data") : undefined
if (!data) throw new Error("SSE data schema is missing its data field")
return RpcSchema.Stream(Schema.toCodecJson(Schema.make(data.type)), Schema.toCodecJson(schema.error))
}
function isHttpStream(schema: Schema.Top): schema is HttpApiSchema.StreamSchema {
return Predicate.hasProperty(schema, "~effect/httpapi/HttpApiSchema/Stream")
}
export function fromEndpoint<E extends HttpApiEndpoint.ConstraintRequest>(input: E): Endpoint<E> {
const endpoint = input as unknown as HttpApiEndpoint.Top
if (omitEndpoints.has(endpoint.identifier)) throw new Error(`Raw WebSocket endpoint: ${endpoint.identifier}`)
const payload = Array.from(endpoint.payload.values()).flatMap((entry) => entry.schemas)
const success = endpoint.success.size ? Array.from(endpoint.success) : [HttpApiSchema.NoContent]
const middleware = Array.from(endpoint.middlewares) as unknown as HttpApiMiddleware.AnyService[]
const errors = [...endpoint.error, ...middleware.flatMap((service) => Array.from(service.error))]
if (success.length > 1 && success.some(isHttpStream)) {
throw new Error(`Mixed streaming responses are not supported: ${endpoint.identifier}`)
}
const request = Schema.Struct({
...(endpoint.identifier === "fs.read"
? { params: FileReadParams }
: endpoint.params
? { params: Schema.toCodecJson(Schema.toType(endpoint.params)) }
: {}),
...(endpoint.query ? { query: Schema.toCodecJson(Schema.toType(endpoint.query)) } : {}),
...(endpoint.headers ? { headers: Schema.toCodecJson(Schema.toType(endpoint.headers)) } : {}),
...(payload.length ? { payload: Schema.toCodecJson(Schema.toType(Schema.Union(payload))) } : {}),
location: LocationQuery.fields.location,
})
return Rpc.make(endpoint.identifier, {
payload: request,
success:
endpoint.identifier === "fs.read"
? FileRead
: success.length === 1
? successSchema(success[0]!)
: Schema.Union(success.map(successSchema)),
error: Schema.toCodecJson(Schema.Union([...new Set(errors)])),
}) as unknown as Endpoint<E>
}
/** Server passes its concrete HttpApi so its middleware error schemas are retained. */
export function makeGroup<Id extends string, G extends HttpApiGroup.Constraint>(
api: HttpApi.HttpApi<Id, G>,
): RpcGroup.RpcGroup<Endpoints<G>> {
const groups = Object.values((api as unknown as HttpApi.Top).groups)
return RpcGroup.make(
...groups.flatMap((group) =>
Object.values(group.endpoints)
.filter((endpoint) => !omitEndpoints.has(endpoint.identifier))
.map(fromEndpoint),
),
) as unknown as RpcGroup.RpcGroup<Endpoints<G>>
}
export type Rpcs = Endpoints<(typeof ClientApi.groups)[keyof typeof ClientApi.groups]>
export const Group: RpcGroup.RpcGroup<Rpcs> = makeGroup(ClientApi)
-81
View File
@@ -1,81 +0,0 @@
import { expect, test } from "bun:test"
import { Schema } from "effect"
import { Event } from "@opencode-ai/schema/event"
import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema } from "effect/unstable/httpapi"
import { RpcSchema } from "effect/unstable/rpc"
import { ClientApi } from "../src/client.js"
import { InvalidRequestError, SessionNotFoundError, UnauthorizedError } from "../src/errors.js"
import { OpenCodeRpc } from "../src/rpc.js"
test("every HTTP operation except the raw PTY sockets has a native RPC", () => {
const expected = Object.values(ClientApi.groups).flatMap((group) =>
Object.values(group.endpoints).map((endpoint) => endpoint.identifier),
)
expect([...OpenCodeRpc.Group.requests.keys()].sort()).toEqual(
expected.filter((name) => !OpenCodeRpc.omitEndpoints.has(name)).sort(),
)
})
test("request envelopes preserve decoded numeric queries and validate required params", () => {
const list = OpenCodeRpc.fromEndpoint(ClientApi.groups["server.session"].endpoints["session.list"])
expect(Schema.decodeUnknownSync(list.payloadSchema)({ query: { limit: 10 } })).toEqual({ query: { limit: 10 } })
expect(() => Schema.decodeUnknownSync(list.payloadSchema)({ query: { limit: "10" } })).toThrow()
expect(() => Schema.decodeUnknownSync(list.payloadSchema)({ query: { limit: -1 } })).toThrow()
const get = OpenCodeRpc.fromEndpoint(ClientApi.groups["server.session"].endpoints["session.get"])
expect(() => Schema.decodeUnknownSync(get.payloadSchema)({})).toThrow()
})
test("SSE streams retain their typed items, without SSE framing", () => {
const rpc = OpenCodeRpc.fromEndpoint(ClientApi.groups["server.session"].endpoints["session.log"])
expect(RpcSchema.isStreamSchema(rpc.successSchema)).toBe(true)
const item = { type: "log.synced" as const, aggregateID: "ses_test", seq: Event.Seq.make(1) }
expect(Schema.decodeUnknownSync(rpc.successSchema.success)(item)).toEqual(item)
expect(() => Schema.decodeUnknownSync(rpc.successSchema.success)({ type: "not-an-event" })).toThrow()
const events = OpenCodeRpc.fromEndpoint(ClientApi.groups["server.event"].endpoints["event.subscribe"])
expect(
Schema.decodeUnknownSync(events.successSchema.success)({ id: "evt_connected", type: "server.connected", data: {} }),
).toEqual({ id: Event.ID.make("evt_connected"), type: "server.connected", data: {} })
})
test("binary file reads have explicit path and base64 JSON codecs", () => {
const rpc = OpenCodeRpc.fromEndpoint(ClientApi.groups["server.fs"].endpoints["fs.read"])
expect(Schema.decodeUnknownSync(rpc.payloadSchema)({ params: { path: "a.bin" }, query: {} })).toEqual({
params: { path: "a.bin" },
query: {},
})
const value = { content: new Uint8Array([0, 255, 128]), mime: "application/octet-stream" }
const encoded = Schema.encodeSync(rpc.successSchema)(value)
expect(encoded).toEqual({ content: "AP+A", mime: "application/octet-stream" })
expect(Schema.decodeUnknownSync(rpc.successSchema)(JSON.parse(JSON.stringify(encoded)))).toEqual(value)
})
test("NoContent remains void and endpoint plus middleware errors remain typed", () => {
const rpc = OpenCodeRpc.fromEndpoint(HttpApiEndpoint.delete("test.remove", "/test"))
expect(Schema.encodeSync(rpc.successSchema)(undefined)).toBeNull()
expect(Schema.decodeUnknownSync(rpc.successSchema)(null)).toBeUndefined()
const get = OpenCodeRpc.fromEndpoint(ClientApi.groups["server.session"].endpoints["session.get"])
for (const error of [
new InvalidRequestError({ message: "invalid" }),
new UnauthorizedError({ message: "unauthorized" }),
new SessionNotFoundError({ sessionID: "ses_test", message: "missing" }),
]) {
expect(Schema.decodeUnknownSync(get.errorSchema)(Schema.encodeSync(get.errorSchema)(error))).toEqual(error)
}
})
test("makeGroup retains concrete server middleware errors and stream errors", () => {
class TestError extends Schema.TaggedError<TestError>()("TestError", { message: Schema.String }) {}
class Middleware extends HttpApiMiddleware.Service<Middleware>()("test/rpc", { error: TestError }) {}
const api = HttpApi.make("test").add(
HttpApiGroup.make("test").add(
HttpApiEndpoint.get("test.stream", "/test", {
success: HttpApiSchema.StreamSse({ data: Schema.Number, error: TestError }),
}).middleware(Middleware),
),
)
const rpc = OpenCodeRpc.makeGroup(api).requests.get("test.stream")!
const error = new TestError({ message: "failed" })
expect(Schema.decodeUnknownSync(rpc.errorSchema)(Schema.encodeSync(rpc.errorSchema)(error))).toEqual(error)
expect(Schema.decodeUnknownSync(rpc.successSchema.error)({ _tag: "TestError", message: "failed" })).toEqual(error)
expect(Schema.decodeUnknownSync(rpc.successSchema.success)(42)).toBe(42)
})
-90
View File
@@ -1,90 +0,0 @@
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { ClientApi } from "@opencode-ai/protocol/client"
import { OpenCodeRpc } from "@opencode-ai/protocol/rpc"
import { AbsolutePath } from "@opencode-ai/schema/schema"
import { Effect, Layer } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpServer } from "effect/unstable/http"
import { HttpApiClient } from "effect/unstable/httpapi"
import { RpcClient, RpcSerialization } from "effect/unstable/rpc"
import { Socket } from "effect/unstable/socket"
import { ServerProcess } from "../src/process"
// A loopback transport microbenchmark, not an end-to-end desktop performance claim.
// Both clients decode the same schemas and read the same 50-session page.
await Effect.gen(function* () {
const directory = yield* Effect.acquireRelease(
Effect.promise(() => fs.mkdtemp(path.join(os.tmpdir(), "opencode-rpc-bench-"))),
(directory) => Effect.promise(() => fs.rm(directory, { recursive: true, force: true })),
)
const password = crypto.randomUUID()
const server = yield* ServerProcess.start<never, never>({
hostname: "127.0.0.1",
port: 0,
password,
database: { path: ":memory:" },
config: { directory: path.join(directory, "config"), project: false },
models: { fetch: false },
fs: { filewatcher: false, fff: false },
})
const url = HttpServer.formatAddress(server.address)
const http = yield* HttpApiClient.make(ClientApi, {
baseUrl: url,
transformClient: (client) =>
HttpClient.mapRequest(
client,
HttpClientRequest.setHeader("authorization", `Basic ${btoa(`opencode:${password}`)}`),
),
}).pipe(Effect.provide(FetchHttpClient.layer))
const socket = new URL("/api/rpc", url)
socket.protocol = "ws:"
socket.searchParams.set("auth_token", btoa(`opencode:${password}`))
const protocol = yield* Layer.build(
RpcClient.layerProtocolSocket({ retryTransientErrors: false }).pipe(
Layer.provide(RpcSerialization.layerJson),
Layer.provide(Socket.layerWebSocket(socket.href).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal))),
),
)
const rpc = yield* RpcClient.make(OpenCodeRpc.Group).pipe(Effect.provideContext(protocol))
yield* Effect.forEach(
Array.from({ length: 50 }, (_, index) => index),
(index) =>
rpc["session.create"]({
payload: { title: `Benchmark ${index}`, location: { directory: AbsolutePath.make(directory) } },
}),
)
const calls: ReadonlyArray<{ transport: string; call: Effect.Effect<unknown, unknown> }> = [
{ transport: "HTTP", call: http["server.session"]["session.list"]({ query: {} }) },
{ transport: "RPC", call: rpc["session.list"]({ query: {} }) },
]
for (const concurrency of [1, 16]) {
for (const { transport, call } of calls) {
yield* Effect.forEach(Array.from({ length: 30 }), () => call, { concurrency })
const start = performance.now()
const samples = yield* Effect.forEach(
Array.from({ length: 300 }),
() =>
Effect.gen(function* () {
const start = performance.now()
yield* call
return performance.now() - start
}),
{ concurrency },
)
const total = performance.now() - start
samples.sort((a, b) => a - b)
console.log(
JSON.stringify({
transport,
concurrency,
requests: samples.length,
elapsedMs: Math.round(total),
requestsPerSecond: Math.round((samples.length / total) * 1000),
p50Ms: Number(samples[Math.floor(samples.length * 0.5)]!.toFixed(2)),
p95Ms: Number(samples[Math.floor(samples.length * 0.95)]!.toFixed(2)),
}),
)
}
}
}).pipe(Effect.timeout("60 seconds"), Effect.scoped, Effect.runPromise)
-11
View File
@@ -22,7 +22,6 @@ export type Error = SubscriberOverflowError | EncodingError
export interface Interface {
readonly subscribe: Effect.Effect<Stream.Stream<string, Error>, never, Scope.Scope>
readonly subscribeEvents: Effect.Effect<Stream.Stream<OpenCodeEvent, Error>, never, Scope.Scope>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/server/EventFeed") {}
@@ -38,7 +37,6 @@ export const make = Effect.fn("EventFeed.make")(function* (
const capacity = options?.capacity ?? SubscriberCapacity
const render = options?.encode ?? frame
const subscribers = new Set<Queue.Queue<string, Error>>()
const events = new Set<Queue.Queue<OpenCodeEvent, Error>>()
const fail = (error: Error) =>
Effect.sync(() => {
@@ -49,11 +47,6 @@ export const make = Effect.fn("EventFeed.make")(function* (
const publish = Effect.fnUntraced(function* (event: Event.Payload) {
if (!isOpenCodeEvent(event)) return
for (const subscriber of events) {
if (Queue.offerUnsafe(subscriber, event)) continue
events.delete(subscriber)
Queue.failCauseUnsafe(subscriber, Cause.fail(new SubscriberOverflowError({ capacity })))
}
if (subscribers.size === 0) return
const encoded = yield* Effect.try({
try: () => render(event),
@@ -79,10 +72,6 @@ export const make = Effect.fn("EventFeed.make")(function* (
yield* Effect.addFinalizer(() => unsubscribe)
return Service.of({
subscribeEvents: Effect.acquireRelease(
Queue.dropping<OpenCodeEvent, Error>(capacity).pipe(Effect.tap((queue) => Effect.sync(() => events.add(queue)))),
(queue) => Effect.sync(() => events.delete(queue)).pipe(Effect.andThen(Queue.shutdown(queue)), Effect.asVoid),
).pipe(Effect.map(Stream.fromQueue)),
subscribe: Effect.acquireRelease(
Queue.dropping<string, Error>(capacity).pipe(Effect.tap((queue) => Effect.sync(() => subscribers.add(queue)))),
(queue) =>
+6 -8
View File
@@ -6,19 +6,17 @@ import { HttpApiBuilder } from "effect/unstable/httpapi"
import { Api } from "../api"
import { response } from "../location"
export const readFile = Effect.fn("Server.readFile")(function* (path: RelativePath) {
const fs = yield* FileSystem.Service
return yield* fs.read({ path })
})
export const FileSystemHandler = HttpApiBuilder.group(Api, "server.fs", (handlers) =>
Effect.gen(function* () {
return handlers
.handleRaw("fs.read", (ctx) =>
Effect.gen(function* () {
const file = yield* readFile(
RelativePath.make(decodeURIComponent(new URL(ctx.request.url, "http://localhost").pathname.slice(13))),
)
const fs = yield* FileSystem.Service
const file = yield* fs.read({
path: RelativePath.make(
decodeURIComponent(new URL(ctx.request.url, "http://localhost").pathname.slice(13)),
),
})
return HttpServerResponse.uint8Array(file.content, { contentType: file.mime })
}),
)
@@ -12,7 +12,6 @@ import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi"
import { Socket } from "effect/unstable/socket"
import { Api } from "../api"
import { CorsConfig, isAllowedRequestOrigin } from "../cors"
import { runPtySocket } from "./pty-socket"
export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experimental", (handlers) =>
Effect.gen(function* () {
@@ -192,7 +191,7 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment
}
})
yield* runPtySocket(
yield* Effect.race(
drain,
socket.runRaw(
(message) =>
@@ -222,9 +221,9 @@ export const PersistentPtyHandler = HttpApiBuilder.group(Api, "server.experiment
),
{ onOpen },
),
() => attachment?.detach(),
).pipe(
Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void),
Effect.ensuring(Effect.sync(() => attachment?.detach())),
Effect.orDie,
)
return HttpServerResponse.empty()
+1 -12
View File
@@ -1,18 +1,9 @@
import { Catalog } from "@opencode-ai/core/catalog"
import { ProviderNotFoundError, ServiceUnavailableError } from "@opencode-ai/protocol/errors"
import { Effect } from "effect"
import { HttpApiBuilder } from "effect/unstable/httpapi"
import { Api } from "../api"
import { ProviderNotFoundError } from "@opencode-ai/protocol/errors"
import { response } from "../location"
import { pluginReadiness } from "./plugin-readiness"
const flushPlugins = pluginReadiness(
() =>
new ServiceUnavailableError({
message: "Provider catalog initialization timed out",
service: "provider.catalog",
}),
)
export const ProviderHandler = HttpApiBuilder.group(Api, "server.provider", (handlers) =>
Effect.gen(function* () {
@@ -20,7 +11,6 @@ export const ProviderHandler = HttpApiBuilder.group(Api, "server.provider", (han
.handle(
"provider.list",
Effect.fn(function* () {
yield* flushPlugins
const catalog = yield* Catalog.Service
return yield* response(catalog.provider.available())
}),
@@ -28,7 +18,6 @@ export const ProviderHandler = HttpApiBuilder.group(Api, "server.provider", (han
.handle(
"provider.get",
Effect.fn(function* (ctx) {
yield* flushPlugins
const catalog = yield* Catalog.Service
const provider = yield* catalog.provider.get(ctx.params.providerID)
if (!provider)
@@ -1,9 +0,0 @@
import { Effect } from "effect"
export function runPtySocket<A, E, R, A2, E2, R2>(
drain: Effect.Effect<A, E, R>,
socket: Effect.Effect<A2, E2, R2>,
detach: () => void,
) {
return Effect.raceFirst(drain, socket).pipe(Effect.ensuring(Effect.sync(detach)))
}
+2 -3
View File
@@ -17,7 +17,6 @@ import {
} from "@opencode-ai/protocol/groups/pty"
import { response } from "../location"
import { PtyEnvironment } from "../pty-environment"
import { runPtySocket } from "./pty-socket"
const ticketScope = Effect.gen(function* () {
const location = yield* Location.Service
@@ -210,15 +209,15 @@ export const PtyHandler = HttpApiBuilder.group(Api, "server.pty", (handlers) =>
}
})
yield* runPtySocket(
yield* Effect.race(
drain,
socket.runRaw((message) => {
const decoded = PtyProtocol.decodeInput(message)
if (decoded !== undefined) attachment.write(decoded)
}),
attachment.detach,
).pipe(
Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void),
Effect.ensuring(Effect.sync(() => attachment.detach())),
Effect.orDie,
)
return HttpServerResponse.empty()
+1 -5
View File
@@ -37,8 +37,6 @@ import { Api } from "./api"
import { ServerAuth } from "./auth"
import { CorsConfig } from "./cors"
import { handlers } from "./handlers"
import { rpcRoutes } from "./rpc"
import { EventFeed } from "./event-feed"
import { authorizationLayer } from "./middleware/authorization"
import { schemaErrorLayer } from "./middleware/schema-error"
import { PtyEnvironment } from "./pty-environment"
@@ -151,9 +149,7 @@ function makeRoutes<AuthError, AuthServices>(
),
ServerInfo.layer(serviceURLs, options.app),
)
const api = Layer.merge(HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }), rpcRoutes).pipe(
Layer.provide(Layer.succeed(CorsConfig, options)),
Layer.provide(EventFeed.layer.pipe(Layer.provide(services))),
const api = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
Layer.provide(handlers.pipe(Layer.provide(services), Layer.provide(Layer.succeed(CorsConfig, options)))),
Layer.provide(formLocationLayer),
Layer.provide(sessionLocationLayer),
-161
View File
@@ -1,161 +0,0 @@
import { Event } from "@opencode-ai/schema/event"
import { RelativePath } from "@opencode-ai/core/schema"
import { Context, Effect, Layer, Scope, Stream } from "effect"
import { Headers, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"
import { HttpApiGroup, HttpApiEndpoint } from "effect/unstable/httpapi"
import { Rpc, RpcGroup, RpcSchema, RpcSerialization, RpcServer } from "effect/unstable/rpc"
import { OpenCodeRpc } from "@opencode-ai/protocol/rpc"
import { Api } from "./api"
import { ServerAuth } from "./auth"
import { CorsConfig, isAllowedRequestOrigin } from "./cors"
import { EventFeed } from "./event-feed"
import type { handlers } from "./handlers"
import { readFile } from "./handlers/fs"
import { LocationMiddleware } from "./location"
import { Authorization, authorizedRequest } from "./middleware/authorization"
import { FormLocationMiddleware } from "./middleware/form-location"
import { SessionLocationMiddleware } from "./middleware/session-location"
import { SchemaErrorMiddleware } from "./middleware/schema-error"
type Services =
| Layer.Success<typeof handlers>
| ServerAuth.Config
| EventFeed.Service
| LocationMiddleware
| FormLocationMiddleware
| SessionLocationMiddleware
| Authorization
| SchemaErrorMiddleware
type Input = {
readonly params?: Readonly<Record<string, string>>
readonly query?: { readonly location?: { readonly directory?: string; readonly workspace?: string } }
readonly payload?: unknown
readonly headers?: Readonly<Record<string, string | undefined>>
readonly location?: { readonly directory?: string; readonly workspace?: string }
}
type Middleware = (
effect: Effect.Effect<unknown, unknown, unknown>,
options: { readonly group: HttpApiGroup.Top; readonly endpoint: HttpApiEndpoint.Top },
) => Effect.Effect<unknown, unknown, unknown>
type Handler = {
readonly endpoint: HttpApiEndpoint.Top
readonly uninterruptible: boolean
readonly handler: (
input: Input & {
readonly request: HttpServerRequest.HttpServerRequest
readonly group: HttpApiGroup.Top
readonly endpoint: HttpApiEndpoint.Top
},
) => Effect.Effect<unknown, unknown, unknown>
}
export const rpcRoutes = HttpRouter.use((router) =>
Effect.gen(function* () {
const services = yield* Effect.context<Services>()
const config = yield* ServerAuth.Config
const cors = yield* CorsConfig
const feed = yield* EventFeed.Service
const group = OpenCodeRpc.makeGroup(Api)
// HttpApiBuilder stores its decoded handlers beside the built routes. Keep this
// dependency on Effect's handler registry here, rather than duplicating handlers
// or routing RPC calls through HTTP serialization and parsing.
const entries = (Object.values(Api.groups) as unknown as ReadonlyArray<HttpApiGroup.Top>).flatMap((definition) => {
const implementation = services.mapUnsafe.get(definition.key) as {
readonly handlers: ReadonlyMap<string, Handler>
}
return Array.from(implementation.handlers.values(), (handler) => ({ definition, ...handler }))
})
yield* router.add(
"GET",
"/api/rpc",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest
if (!(yield* authorizedRequest(request, config)))
return HttpServerResponse.empty({
status: 401,
headers: { "www-authenticate": 'Basic realm="Secure Area"' },
})
if (!isAllowedRequestOrigin(request.headers.origin, request.headers.host, cors))
return HttpServerResponse.empty({ status: 403 })
// Handler resources belong to an RPC request, not the WebSocket upgrade.
const context = Context.merge(services, yield* Effect.context<never>()).pipe(Context.omit(Scope.Scope))
const implementations = Object.fromEntries(
entries.flatMap((entry) => {
const rpc = group.requests.get(entry.endpoint.identifier)
if (!rpc) return []
const streaming = RpcSchema.isStreamSchema(rpc.successSchema)
const invoke = (input: Input) => {
const url = new URL(request.url, "http://localhost")
url.pathname = entry.endpoint.path
const location = input.location ?? input.query?.location
if (location) {
if (location.directory) url.searchParams.set("location[directory]", location.directory)
if (location.workspace) url.searchParams.set("location[workspace]", location.workspace)
else url.searchParams.delete("location[workspace]")
}
const headers = Headers.merge(Headers.fromInput(input.headers), request.headers)
const current = request.modify({
url: `${url.pathname}${url.search}`,
headers: location ? Headers.remove(headers, "x-opencode-workspace") : headers,
})
const run = Effect.gen(function* () {
if (rpc._tag === "event.subscribe") {
const live = yield* feed.subscribeEvents
return Stream.make({ id: Event.ID.create(), type: "server.connected" as const, data: {} }).pipe(
Stream.concat(live),
Stream.orDie,
)
}
if (rpc._tag === "fs.read") return yield* readFile(RelativePath.make(input.params?.path ?? ""))
const result = yield* entry.handler({
...input,
request: current,
group: entry.definition,
endpoint: entry.endpoint,
})
// Streams are consumed after middleware returns; retain the location
// services selected for this call, not the connection's last location.
if (Stream.isStream(result)) return Stream.provideContext(result, yield* Effect.context<never>())
return result
}) as Effect.Effect<unknown, unknown, unknown>
const wrapped = Array.from(entry.endpoint.middlewares).reduce((effect, key) => {
// Authentication belongs to the upgrade, not client-supplied frame headers.
if (key.key === Authorization.key) return effect
const middleware = Context.getUnsafe(context, key) as Middleware
if (typeof middleware !== "function") throw new Error(`Unsupported RPC middleware: ${key.key}`)
return middleware(effect, { group: entry.definition, endpoint: entry.endpoint })
}, run)
const effect = (entry.uninterruptible ? Effect.uninterruptible(wrapped) : wrapped).pipe(
Effect.provideService(HttpServerRequest.HttpServerRequest, current),
Effect.provideService(HttpRouter.RouteContext, {
params: input.params ?? {},
route: HttpRouter.route(
entry.endpoint.method,
entry.endpoint.path as HttpRouter.PathInput,
HttpServerResponse.empty(),
),
}),
Effect.provideContext(context as Context.Context<unknown>),
)
return streaming
? Stream.unwrap(effect as Effect.Effect<Stream.Stream<unknown, unknown>, unknown>)
: effect
}
return [[rpc._tag, invoke]]
}),
)
const runtime = group as unknown as RpcGroup.RpcGroup<Rpc.Any>
const implementation = yield* runtime.toHandlers(implementations as unknown as RpcGroup.HandlersFrom<Rpc.Any>)
const websocket = yield* RpcServer.toHttpEffectWebsocket(runtime, { disableFatalDefects: true }).pipe(
Effect.provideContext(implementation),
Effect.provide(RpcSerialization.layerJson),
)
return yield* websocket
}),
)
}),
)
-34
View File
@@ -39,40 +39,6 @@ function makeSource() {
}
describe("EventFeed", () => {
it.effect("delivers typed RPC events without SSE encoding and filters internal events", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, {
capacity: 1,
encode: () => {
throw new Error("RPC-only subscribers must not encode SSE")
},
})
const stream = yield* feed.subscribeEvents
yield* source.publish(internal("one"))
yield* source.publish(internal("two"))
const payload = event("rpc")
yield* source.publish(payload)
expect(yield* stream.pipe(Stream.take(1), Stream.runCollect)).toEqual([payload])
}),
)
it.effect("bounds RPC subscriber lag independently of HTTP subscribers", () =>
Effect.gen(function* () {
const source = makeSource()
const feed = yield* EventFeed.make(source.observe, { capacity: 1 })
const slow = yield* feed.subscribeEvents
yield* source.publish(event("one"))
const http = yield* feed.subscribe
const payload = event("two")
yield* source.publish(payload)
const exit = yield* slow.pipe(Stream.runCollect, Effect.exit)
expect(Exit.isFailure(exit)).toBeTrue()
expect(Option.getOrUndefined(Exit.findErrorOption(exit))).toBeInstanceOf(EventFeed.SubscriberOverflowError)
expect(yield* http.pipe(Stream.take(1), Stream.runCollect)).toEqual([EventFeed.frame(payload)])
}),
)
test("preserves the public SSE frame encoding", () => {
const payload = event("wire")
expect(EventFeed.frame(payload)).toBe(`data: ${JSON.stringify(payload)}\n\n`)
-64
View File
@@ -1,64 +0,0 @@
import fs from "node:fs/promises"
import path from "node:path"
import { expect } from "bun:test"
import { Effect } from "effect"
import { tmpdir } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { startServer } from "./fixture/server"
it.live(
"waits for plugin initialization on the first provider list request",
() =>
Effect.gen(function* () {
const fixture = yield* configuredProvider("opencode-provider-list-endpoint-")
const url = new URL("/api/provider", fixture.server.base)
url.searchParams.set("location[directory]", fixture.path)
const response = yield* Effect.promise(() => fetch(url, { headers: fixture.server.headers }))
expect(response.status).toBe(200)
const body: unknown = yield* Effect.promise(() => response.json())
if (!isRecord(body) || !Array.isArray(body["data"])) throw new Error("Expected a provider list response")
expect(body["data"].some((provider) => isRecord(provider) && provider["id"] === "custom")).toBeTrue()
}),
15_000,
)
it.live(
"waits for plugin initialization on the first provider get request",
() =>
Effect.gen(function* () {
const fixture = yield* configuredProvider("opencode-provider-get-endpoint-")
const url = new URL("/api/provider/custom", fixture.server.base)
url.searchParams.set("location[directory]", fixture.path)
const response = yield* Effect.promise(() => fetch(url, { headers: fixture.server.headers }))
expect(response.status).toBe(200)
const body: unknown = yield* Effect.promise(() => response.json())
if (!isRecord(body) || !isRecord(body["data"])) throw new Error("Expected a provider response")
expect(body["data"]["id"]).toBe("custom")
}),
15_000,
)
const configuredProvider = Effect.fnUntraced(function* (prefix: string) {
const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir(prefix)))
yield* Effect.promise(() =>
fs.writeFile(
path.join(tmp.path, "opencode.json"),
JSON.stringify({
providers: {
custom: {
package: "@opencode-ai/ai/providers/openai-compatible",
settings: { apiKey: "secret" },
models: { chat: {} },
},
},
}),
),
)
return { server: yield* startServer(tmp.path), path: tmp.path }
})
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
-16
View File
@@ -1,16 +0,0 @@
import { expect } from "bun:test"
import { Effect, Option, Result } from "effect"
import { it } from "../../core/test/lib/effect"
import { runPtySocket } from "../src/handlers/pty-socket"
it.live("detaches when the socket fails while the outbox drain is blocked", () =>
Effect.gen(function* () {
const state = { detached: false }
const result = yield* runPtySocket(Effect.never, Effect.fail("socket closed"), () => {
state.detached = true
}).pipe(Effect.result, Effect.timeoutOption("100 millis"))
expect(Option.isSome(result) && Result.isFailure(result.value)).toBeTrue()
expect(state.detached).toBeTrue()
}),
)
@@ -1,4 +1,4 @@
import { expect, setDefaultTimeout } from "bun:test"
import { expect } from "bun:test"
import { Agent } from "@opencode-ai/core/agent"
import { Bus } from "@opencode-ai/core/bus"
import { Model } from "@opencode-ai/core/model"
@@ -12,8 +12,6 @@ import { Effect, Layer } from "effect"
import { it } from "../../core/test/lib/effect"
import { ServerFetch } from "../src/fetch"
setDefaultTimeout(30_000)
it.live("updates completed assistant message content through the session HTTP API", () =>
Effect.gen(function* () {
const state = {
-333
View File
@@ -1,333 +0,0 @@
import { expect } from "bun:test"
import fs from "node:fs/promises"
import path from "node:path"
import { NodeSocket } from "@effect/platform-node"
import { OpenCodeRpc } from "@opencode-ai/protocol/rpc"
import { SessionNotFoundError } from "@opencode-ai/protocol/errors"
import { AbsolutePath } from "@opencode-ai/schema/schema"
import { Pty } from "@opencode-ai/schema/pty"
import { Session } from "@opencode-ai/schema/session"
import { Cause, Deferred, Effect, Exit, Fiber, Layer, Queue, Schema, Scope, Stream } from "effect"
import { HttpServer, HttpServerRequest } from "effect/unstable/http"
import { Rpc, RpcClient, RpcGroup, RpcSerialization } from "effect/unstable/rpc"
import { Socket } from "effect/unstable/socket"
import { tmpdir } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { ServerProcess } from "../src/process"
const authorization = `Basic ${btoa("opencode:secret")}`
const fixture = Effect.fn(function* <R extends Rpc.Any>(
group: RpcGroup.RpcGroup<R>,
transform?: ServerProcess.Transform,
origin = "http://localhost:3000",
) {
const tmp = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir("opencode-rpc-")),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
)
const global = path.join(tmp.path, "config")
const directories = [path.join(tmp.path, "first"), path.join(tmp.path, "second")]
yield* Effect.promise(() => Promise.all([global, ...directories].map((dir) => fs.mkdir(dir))))
const server = yield* ServerProcess.start<never, never>(
{
hostname: "127.0.0.1",
port: 0,
password: "secret",
cors: ["https://configured.example"],
app: { version: "test-version" },
database: { path: ":memory:" },
events: { persist: true },
config: { directory: global, project: false },
models: { fetch: false },
fs: { filewatcher: false, fff: false },
},
undefined,
transform,
)
const url = HttpServer.formatAddress(server.address)
const sockets: WebSocket[] = []
const protocol = yield* Layer.build(
RpcClient.layerProtocolSocket({ retryTransientErrors: false }).pipe(
Layer.provide(RpcSerialization.layerJson),
Layer.provide(
Socket.layerWebSocket(new URL("/api/rpc", url).href.replace("http:", "ws:")).pipe(
Layer.provide(
Layer.succeed(Socket.WebSocketConstructor, (url) => {
const socket = new NodeSocket.NodeWS.WebSocket(url, {
headers: { authorization, origin },
}) as unknown as WebSocket
sockets.push(socket)
return socket
}),
),
),
),
),
)
const rpc = yield* RpcClient.make(group).pipe(Effect.provideContext(protocol))
const request = (pathname: string, init?: RequestInit) =>
Effect.promise(() =>
fetch(new URL(pathname, url), {
...init,
headers: { authorization, "content-type": "application/json", ...init?.headers },
}),
)
return {
rpc,
request,
url,
sockets,
first: { directory: AbsolutePath.make(directories[0]!) },
second: { directory: AbsolutePath.make(directories[1]!) },
}
})
it.live(
"multiplexes concurrent RPC calls and shares session state with HTTP",
() =>
Effect.gen(function* () {
const { rpc, request, first, sockets } = yield* fixture(OpenCodeRpc.Group)
const sessions = yield* Effect.all(
Array.from({ length: 8 }, (_, index) =>
rpc["session.create"]({ payload: { title: `parallel-${index}`, location: first } }),
),
{ concurrency: "unbounded" },
)
expect(new Set(sessions.map((session) => session.data.id)).size).toBe(8)
expect(sessions.map((session) => session.data.title)).toEqual(
Array.from({ length: 8 }, (_, index) => `parallel-${index}`),
)
const sessionID = sessions[0]!.data.id
const http = yield* request(`/api/session/${sessionID}`)
expect(http.status).toBe(200)
expect(
Schema.decodeUnknownSync(Schema.Struct({ data: Session.Info }))(yield* Effect.promise(() => http.json())),
).toEqual(yield* rpc["session.get"]({ params: { sessionID } }))
expect(
yield* rpc["session.rename"]({ params: { sessionID }, payload: { title: "renamed by RPC" } }),
).toBeUndefined()
const renamed = yield* request(`/api/session/${sessionID}`)
expect(yield* Effect.promise(() => renamed.json())).toMatchObject({ data: { title: "renamed by RPC" } })
expect(
(yield* request(`/api/session/${sessionID}/rename`, {
method: "POST",
body: JSON.stringify({ title: "renamed by HTTP" }),
})).status,
).toBe(204)
expect((yield* rpc["session.get"]({ params: { sessionID } })).data.title).toBe("renamed by HTTP")
expect(yield* rpc["session.remove"]({ params: { sessionID } })).toBeUndefined()
const missing = yield* rpc["session.get"]({ params: { sessionID } }).pipe(
Effect.catchTag("SessionNotFoundError", Effect.succeed),
)
expect(missing).toBeInstanceOf(SessionNotFoundError)
expect(missing).toMatchObject({ _tag: "SessionNotFoundError", sessionID })
const absent = yield* request(`/api/session/${sessionID}`)
expect(absent.status).toBe(404)
expect(yield* Effect.promise(() => absent.json())).toMatchObject({ _tag: "SessionNotFoundError", sessionID })
expect(sockets).toHaveLength(1)
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"reads binary files and MIME types at two locations over one RPC connection",
() =>
Effect.gen(function* () {
const { rpc, request, first, second, sockets } = yield* fixture(OpenCodeRpc.Group)
const filename = "space # percent% question? plus+.png"
const firstBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 255, 128])
const secondBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 127, 1, 254])
yield* Effect.promise(() =>
Promise.all([
Bun.write(path.join(first.directory, filename), firstBytes),
Bun.write(path.join(second.directory, filename), secondBytes),
]),
)
const files = yield* Effect.all(
[first, second].map((location) => rpc["fs.read"]({ params: { path: filename }, query: {}, location })),
{ concurrency: "unbounded" },
)
expect(files.map((file) => file.content)).toEqual([firstBytes, secondBytes])
expect(files.map((file) => file.mime)).toEqual(["image/png", "image/png"])
const query = new URLSearchParams({ "location[directory]": first.directory })
const http = yield* request(`/api/fs/read/${encodeURIComponent(filename)}?${query}`)
expect(http.status).toBe(200)
expect(http.headers.get("content-type")).toBe(files[0]!.mime)
expect(Array.from(new Uint8Array(yield* Effect.promise(() => http.arrayBuffer())))).toEqual(
Array.from(files[0]!.content),
)
const lists = yield* Effect.all(
[first, second].map((location) => rpc["fs.list"]({ query: {}, location })),
{ concurrency: "unbounded" },
)
expect(lists.map((list) => list.location.directory)).toEqual([first.directory, second.directory])
expect(sockets).toHaveLength(1)
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"streams the connected event and later domain events alongside unary RPC calls",
() =>
Effect.gen(function* () {
const { rpc, first, sockets } = yield* fixture(OpenCodeRpc.Group)
yield* Effect.gen(function* () {
const events = yield* rpc["event.subscribe"]({}, { asQueue: true })
expect(yield* Queue.take(events)).toMatchObject({ type: "server.connected", data: {} })
const created = yield* rpc["session.create"]({ payload: { title: "observed", location: first } })
const received = yield* Stream.fromQueue(events).pipe(
Stream.filter((event) => event.type === "session.created"),
Stream.take(1),
Stream.runCollect,
)
expect(received).toMatchObject([{ type: "session.created", data: { sessionID: created.data.id } }])
}).pipe(Effect.scoped)
expect(yield* rpc["health.get"]({})).toMatchObject({ healthy: true, version: "test-version" })
expect(sockets).toHaveLength(1)
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"cancels event subscriptions without accumulating upgrade finalizers",
() =>
Effect.gen(function* () {
const captured = yield* Deferred.make<Scope.Scope>()
const { rpc, sockets } = yield* fixture(OpenCodeRpc.Group, (app) =>
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest
if (request.url === "/api/rpc") {
const scope = yield* Scope.Scope
yield* Deferred.succeed(captured, scope)
}
return yield* app
}),
)
yield* rpc["health.get"]({})
const scope = yield* Deferred.await(captured)
const finalizerCount = () => {
const state = scope.state
if (state._tag !== "Open") throw new Error("WebSocket upgrade scope must remain open")
return state.finalizers?.size ?? 0
}
const baseline = finalizerCount()
for (let index = 0; index < 5; index++) {
yield* Effect.gen(function* () {
const events = yield* rpc["event.subscribe"]({}, { asQueue: true })
expect(yield* Queue.take(events)).toMatchObject({ type: "server.connected" })
// The subscription belongs to its RPC scope even while it is active.
expect(finalizerCount()).toBe(baseline)
}).pipe(Effect.scoped)
expect(yield* rpc["health.get"]({})).toMatchObject({ healthy: true, version: "test-version" })
expect(finalizerCount()).toBe(baseline)
}
expect(sockets).toHaveLength(1)
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"replays session logs and cancels a live stream without closing the RPC connection",
() =>
Effect.gen(function* () {
const { rpc, first, sockets } = yield* fixture(OpenCodeRpc.Group)
const session = yield* rpc["session.create"]({ payload: { title: "before replay", location: first } })
const params = { sessionID: session.data.id }
yield* rpc["session.rename"]({ params, payload: { title: "in replay" } })
const replay = yield* rpc["session.log"]({ params, query: { follow: false } }).pipe(Stream.runCollect)
expect(replay.map((event) => event.type)).toEqual(["session.created", "session.renamed", "log.synced"])
expect(replay[1]).toMatchObject({ data: { sessionID: params.sessionID, title: "in replay" } })
const watermark = replay.find((event) => event.type === "log.synced")!
expect(watermark).toMatchObject({ type: "log.synced", aggregateID: params.sessionID })
const synced = yield* Deferred.make<void>()
const renamed = yield* Deferred.make<void>()
const follow = yield* rpc["session.log"]({ params, query: { after: watermark.seq, follow: true } }).pipe(
Stream.runForEach((event) =>
event.type === "log.synced"
? Deferred.succeed(synced, undefined)
: event.type === "session.renamed" && event.data.title === "after replay"
? Deferred.succeed(renamed, undefined)
: Effect.void,
),
Effect.forkScoped,
)
yield* Deferred.await(synced)
yield* rpc["session.rename"]({ params, payload: { title: "after replay" } })
yield* Deferred.await(renamed)
yield* Fiber.interrupt(follow)
expect((yield* rpc["session.get"]({ params })).data.title).toBe("after replay")
expect(yield* rpc["health.get"]({})).toMatchObject({ healthy: true })
expect(sockets).toHaveLength(1)
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"validates malformed RPC payloads on the server without poisoning the connection",
() =>
Effect.gen(function* () {
// The permissive client codec sends invalid data instead of rejecting it before transport.
const { rpc, request, first, sockets } = yield* fixture(
RpcGroup.make(
Rpc.make("session.create", { payload: Schema.Unknown, success: Schema.Unknown, error: Schema.Unknown }),
Rpc.make("health.get", { payload: Schema.Unknown, success: Schema.Unknown, error: Schema.Unknown }),
),
)
const invalid = yield* rpc["session.create"]({ payload: { title: 42, location: first } }).pipe(Effect.exit)
expect(Exit.isFailure(invalid)).toBe(true)
if (Exit.isFailure(invalid)) expect(Cause.pretty(invalid.cause)).toContain("title")
const http = yield* request("/api/session", {
method: "POST",
body: JSON.stringify({ title: 42, location: first }),
})
expect(http.status).toBe(400)
const list = yield* request("/api/session")
expect(yield* Effect.promise(() => list.json())).toMatchObject({ data: [] })
expect(yield* rpc["health.get"]({})).toMatchObject({ healthy: true })
expect(sockets).toHaveLength(1)
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"accepts configured origins and rejects missing credentials and untrusted origins before upgrading RPC",
() =>
Effect.gen(function* () {
const { rpc, url } = yield* fixture(OpenCodeRpc.Group, undefined, "https://configured.example")
const denied = yield* Effect.all(
[
new Headers(),
new Headers({ authorization: `Basic ${btoa("opencode:wrong")}` }),
new Headers({ authorization, origin: "https://untrusted.example" }),
new Headers({ authorization, origin: "null" }),
].map((headers) => Effect.promise(() => fetch(new URL("/api/rpc", url), { headers }))),
{ concurrency: "unbounded" },
)
expect(denied.map((response) => response.status)).toEqual([401, 401, 403, 403])
expect(denied.every((response) => !response.headers.has("sec-websocket-accept"))).toBe(true)
expect(yield* rpc["health.get"]({})).toMatchObject({ healthy: true })
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
it.live(
"forwards declared PTY ticket headers to the shared business handler",
() =>
Effect.gen(function* () {
const { rpc, first } = yield* fixture(OpenCodeRpc.Group)
const input = { params: { ptyID: Pty.ID.make("pty_missing") }, query: {}, location: first }
const denied = yield* rpc["pty.connectToken"]({ ...input, headers: {} }).pipe(
Effect.catchTag("ForbiddenError", Effect.succeed),
)
expect(denied).toMatchObject({ _tag: "ForbiddenError" })
const missing = yield* rpc["pty.connectToken"]({ ...input, headers: { "x-opencode-ticket": "1" } }).pipe(
Effect.catchTag("PtyNotFoundError", Effect.succeed),
)
expect(missing).toMatchObject({ _tag: "PtyNotFoundError", ptyID: input.params.ptyID })
}).pipe(Effect.timeout("20 seconds")),
30_000,
)
@@ -1,75 +0,0 @@
import { expect, story } from "../../storybook/playwright/story"
story.describe("touch timeline", () => {
story.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } })
story("keeps message actions and metadata visible without hover", async ({ mount, page }) => {
const timeline = await mount("current-session-timeline-rows--conversation", { args: { scenario: "interruption" } })
expect(await page.evaluate(() => matchMedia("(hover: none)").matches)).toBe(true)
for (const action of [
{ slot: "user-message-copy-wrapper", name: "Copy message" },
{ slot: "text-part-copy-wrapper", name: "Copy response" },
]) {
const actions = timeline.locator(`[data-slot="${action.slot}"]`)
await expect(actions).toHaveCount(1)
await expect(actions).toHaveCSS("opacity", "1")
await expect(actions).toHaveCSS("pointer-events", "auto")
await expect(actions.getByRole("button", { name: action.name, exact: true })).toBeVisible()
}
await expect(timeline.locator('[data-slot="user-message-meta"]')).toContainText("Build")
await expect(timeline.locator('[data-slot="user-message-meta-tail"]')).not.toBeEmpty()
await expect(timeline.locator('[data-slot="text-part-meta"]')).toContainText("Build")
await expect(timeline.locator('[data-slot="text-part-meta"]')).toContainText("Sonnet")
})
story("keeps shell copy visible without hover", async ({ mount }) => {
const timeline = await mount("current-session-terminal-work--expanded-shell")
const copy = timeline.locator('[data-slot="bash-copy"]')
await expect(copy).toHaveCount(1)
await expect(copy).toHaveCSS("opacity", "1")
await expect(copy).toHaveCSS("pointer-events", "auto")
})
story("keeps error copy visible without hover", async ({ mount, page }) => {
const errors = await mount("components-tool-error-card--all")
const patch = errors.locator('[data-kind="tool-error-card"]').filter({ hasText: "Patch" })
await patch.getByRole("button", { name: /Patch.*Verification failed/ }).tap()
await page.touchscreen.tap(385, 800)
const copy = patch.locator('[data-slot="tool-error-card-copy"]')
await expect(copy).toHaveCSS("opacity", "1")
await expect(copy).toHaveCSS("pointer-events", "auto")
})
story("keeps fenced code copy visible without hover", async ({ mount }) => {
const markdown = await mount("components-markdown--complete-response")
const code = markdown.locator('[data-component="markdown-code"]').filter({ hasText: "export const value = 42" })
await expect(code).toHaveCount(1)
await expect(code.locator('[data-slot="markdown-copy-button"]')).toHaveCSS("opacity", "1")
})
})
story("desktop message actions still appear on hover and keyboard focus", async ({ mount, page }) => {
const timeline = await mount("current-session-timeline-rows--conversation", { args: { scenario: "interruption" } })
expect(await page.evaluate(() => matchMedia("(hover: hover)").matches)).toBe(true)
for (const action of [
{ slot: "user-message-copy-wrapper", name: "Copy message" },
{ slot: "text-part-copy-wrapper", name: "Copy response" },
]) {
const actions = timeline.locator(`[data-slot="${action.slot}"]`)
await expect(actions).toHaveCount(1)
await expect(actions).toHaveCSS("opacity", "0")
await expect(actions).toHaveCSS("pointer-events", "none")
await actions.locator("..").hover()
await expect(actions).toHaveCSS("opacity", "1")
await expect(actions).toHaveCSS("pointer-events", "auto")
await page.mouse.move(0, 0)
await expect(actions).toHaveCSS("opacity", "0")
await actions.getByRole("button", { name: action.name, exact: true }).focus()
await expect(actions).toHaveCSS("opacity", "1")
await expect(actions).toHaveCSS("pointer-events", "auto")
await page.getByRole("button", { name: "Reset", exact: true }).focus()
}
})

Some files were not shown because too many files have changed in this diff Show More