diff --git a/.github/workflows/check-process-daemon.yml b/.github/workflows/check-process-daemon.yml index 46e25428a4fc..d8324a729489 100644 --- a/.github/workflows/check-process-daemon.yml +++ b/.github/workflows/check-process-daemon.yml @@ -203,7 +203,7 @@ jobs: $output = & $binary --version if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } Write-Output $output - if ($output -ne "opencode-pty $version (protocol 7)") { throw "Unexpected executable version: $output" } + if ($output -notmatch "^opencode-pty $([regex]::Escape($version)) \(protocol \d+\)$") { throw "Unexpected executable version: $output" } - name: Document current coverage if: always() run: | diff --git a/.github/workflows/release-process-daemon.yml b/.github/workflows/release-process-daemon.yml index 147f3ddf58b2..881865581945 100644 --- a/.github/workflows/release-process-daemon.yml +++ b/.github/workflows/release-process-daemon.yml @@ -25,7 +25,6 @@ defaults: env: CARGO_TERM_COLOR: always - PROTOCOL_VERSION: 7 ZIG_VERSION: 0.16.0 GNU_GLIBC_VERSION: "2.30" CARGO_ZIGBUILD_VERSION: 0.23.2 @@ -33,6 +32,8 @@ env: jobs: checks: runs-on: ubuntu-22.04 + outputs: + protocol: ${{ steps.protocol.outputs.protocol }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5 @@ -45,6 +46,12 @@ jobs: echo "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin" >> "$GITHUB_PATH" - name: Install Rust run: rustup toolchain install 1.90.0 --profile minimal --component clippy --component rustfmt + - name: Read protocol version + id: protocol + run: | + protocol="$(sed -nE 's/^pub const PROTOCOL_VERSION: u32 = ([0-9]+);$/\1/p' src/protocol.rs)" + test -n "$protocol" + echo "protocol=$protocol" >> "$GITHUB_OUTPUT" - name: Validate tag run: | package_version="$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "opencode-pty") | .version')" @@ -80,6 +87,7 @@ jobs: target: aarch64-apple-darwin runs-on: ${{ matrix.runner }} env: + PROTOCOL_VERSION: ${{ needs.checks.outputs.protocol }} MACOSX_DEPLOYMENT_TARGET: "11.0" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 @@ -165,6 +173,7 @@ jobs: shell: pwsh working-directory: packages/process-daemon env: + PROTOCOL_VERSION: ${{ needs.checks.outputs.protocol }} CARGO_BUILD_TARGET: ${{ matrix.target }} RUSTUP_TOOLCHAIN: 1.90.0-x86_64-pc-windows-msvc # Portable CPU for Ghostty (see build.rs) and no Visual C++ runtime dependency. @@ -238,12 +247,14 @@ jobs: if-no-files-found: error release: - needs: [build, build-windows] + needs: [checks, build, build-windows] runs-on: ubuntu-22.04 permissions: contents: write id-token: write attestations: write + env: + PROTOCOL_VERSION: ${{ needs.checks.outputs.protocol }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index 4506cf49fefa..3a8acaa600b8 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -16,4 +16,7 @@ "tools": { "github-pr-search": false, }, + "experimental": { + "part_rows": true, + }, } diff --git a/AGENTS.md b/AGENTS.md index d4282d4db0ec..7fdbe171b152 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,6 +180,14 @@ const table = sqliteTable("session", { - A breaking move of shipped SDK or plugin API (including moving it under `experimental`) keeps the old path and type names as deprecated aliases of the new ones until the next minor, each marked `@deprecated` with the replacement and "Removed in the next minor". Generated SDK moves get them from the codegen (`compile(..., { aliases: true })` in `packages/client/script/generate.ts`), not by hand. - Experimental plugin hooks are named `experimental.*` (`experimental.ws.handshake`). +### Feature Flags + +- When you open a PR, decide whether the change needs a flag: new user-visible behavior, risky core changes, and anything not ready to release get one; fixes, refactors, docs and tests do not. +- Gate risky behavior, or behavior that lands over several PRs, with a key and a description in `packages/schema/src/config/flag.ts`, and read it with `Flag.enabled("")` from `@opencode/core/flag`. +- Flags are on in local and dev builds and off in releases; `experimental.` in config and `OPENCODE_FLAGS="key,-other"` override that. +- Say in the PR body which flag guards the change. To try every flag at once, use `OPENCODE_FLAGS=all` or `experimental.all_flags: true`; a `-` opt-out or `experimental.: false` still wins, and neither `all` nor `all_flags` is a flag key. +- Ship a feature by deleting its flag and the checks that read it. + ## Testing - Avoid mocks as much as possible, you shouldn't be using globalThis.\* at all unless it's the only option. diff --git a/bun.lock b/bun.lock index ba71a25146f7..60b5189f7596 100644 --- a/bun.lock +++ b/bun.lock @@ -1055,7 +1055,7 @@ "@effect/platform-node-shared": "4.1.0", "@effect/sql-sqlite-bun": "4.1.0", "@effect/sql-sqlite-node": "4.1.0", - "@hona/strobe": "0.6.0", + "@hona/strobe": "0.8.0", "@kobalte/core": "0.13.13", "@lydell/node-pty": "1.2.0-beta.12", "@npmcli/arborist": "9.4.0", @@ -1695,17 +1695,17 @@ "@happy-dom/global-registrator": ["@happy-dom/global-registrator@20.0.11", "", { "dependencies": { "@types/node": "^20.0.0", "happy-dom": "^20.0.11" } }, "sha512-GqNqiShBT/lzkHTMC/slKBrvN0DsD4Di8ssBk4aDaVgEn+2WMzE6DXxq701ndSXj7/0cJ8mNT71pM7Bnrr6JRw=="], - "@hona/strobe": ["@hona/strobe@0.6.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.6.0", "@hona/strobe-darwin-x64": "0.6.0", "@hona/strobe-linux-arm64": "0.6.0", "@hona/strobe-linux-x64": "0.6.0", "@hona/strobe-win32-x64": "0.6.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-KkGO9k3tLwZq0X4epJgrAFNQyO515969aTfkC8CBjMWchRuofW66LbucYP+up3UP6Fb5kg7VUuP1yb8Dcdls0Q=="], + "@hona/strobe": ["@hona/strobe@0.8.0", "", { "optionalDependencies": { "@hona/strobe-darwin-arm64": "0.8.0", "@hona/strobe-darwin-x64": "0.8.0", "@hona/strobe-linux-arm64": "0.8.0", "@hona/strobe-linux-x64": "0.8.0", "@hona/strobe-win32-x64": "0.8.0" }, "bin": { "strobe": "bin/strobe.js" } }, "sha512-Nz5W+FKooIUNGcazTphZN43Q7Y1aLtW94+Ixj6q2LnMDcPbkUdKJTDwXwJvs8DH9h+sCzBByjXAMnngcLKhuVA=="], - "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.6.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-7d1IFyjXYl1GiGyWPT1Yqvc9XkZJy7a5/E4JfvinupenszJTXkFZrQCz1JuuAyHqhKc5zchmlvCVll2bGCIu2A=="], + "@hona/strobe-darwin-arm64": ["@hona/strobe-darwin-arm64@0.8.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-mbiwzobUq8uoxY/h5x95lzBzsKm54ePAEjUX7bQVzwNsSQnmuepDg7cOB4pPm9L5+5ngbiNsjHeZlvYrFW5Cbg=="], - "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.6.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-o5HAqoSN/DLIGJb0VSIzBTP4iyys9gDPkQotVqhgxgvG687P6w7uV+c2ZBXT9O1DQxraTbIc61PI1e54fhtskA=="], + "@hona/strobe-darwin-x64": ["@hona/strobe-darwin-x64@0.8.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-OwAnAw6ZzK3KzEopcZcNY7JW5RdAIzkOnE6/IIvctI/MXYkKc7A1ovd71mXhOqBKtsGXOErwjxoFGMepv4iQsw=="], - "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.6.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-wvmWlB5vYJ0DTCpbboTMB6xW4I5SQkYz2P92lAoqlHZq1CV+smMLCOwjs8Ml1Cz9IsLbUNQ6zR/ggWuE7GRhOQ=="], + "@hona/strobe-linux-arm64": ["@hona/strobe-linux-arm64@0.8.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-FP7PMXgCxV62InY4WMbl4DgyLuvbIEdz1jQhLrSQ47RHFBtn3gHok6/duBGO7PTRUIwYHh+L0U1NL9WG3J86FQ=="], - "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.6.0", "", { "os": "linux", "cpu": "x64" }, "sha512-0C7lK/bakN4EGKCCbKOMmBGqfB/iz3cDQJC8RNRSpgVXTbtmitRywTs1UK11WbMhB0AkaSVqBfA2FYFXILePSg=="], + "@hona/strobe-linux-x64": ["@hona/strobe-linux-x64@0.8.0", "", { "os": "linux", "cpu": "x64" }, "sha512-sAX/KRgfMvV0YcBcHjOAgmpwABeogHy1sYuASLvpAI3RupbG534Q10PqSlWf8r1fBYXu48QjkKilfg/rzlIJGg=="], - "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.6.0", "", { "os": "win32", "cpu": "x64" }, "sha512-XSAeRz0Z+g/8Z3cU/c8I80yiH5Z96xXvw4f1e2kBUm9ukrFFDkm1mheP5KLsx7Nq/aNtsqTXLLiw1mmwHuioVA=="], + "@hona/strobe-win32-x64": ["@hona/strobe-win32-x64@0.8.0", "", { "os": "win32", "cpu": "x64" }, "sha512-fB0Lub5cqoJlDEqhqC0K6E4KJP+3Fc9ncRhdTnXUd9wL+csjRIrmpLOq5e8R1PFzhFcgHl+jEmY3i67H+bfezg=="], "@hono/node-server": ["@hono/node-server@2.1.5", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q=="], diff --git a/package.json b/package.json index eafe87521fbc..1d2d6099f889 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "@effect/sql-sqlite-node": "4.1.0", "@npmcli/arborist": "9.4.0", "@types/bun": "1.4.3", - "@hona/strobe": "0.6.0", + "@hona/strobe": "0.8.0", "@types/cross-spawn": "6.0.6", "@octokit/rest": "22.0.0", "@opentui/core": "0.8.1", diff --git a/packages/ai/README.md b/packages/ai/README.md index 2f0f102e9c89..fd1b9783dd72 100644 --- a/packages/ai/README.md +++ b/packages/ai/README.md @@ -37,7 +37,7 @@ const program = Effect.gen(function* () { model: openai.responses("gpt-4o-mini"), // `.chat(...)` selects the Chat Completions API instead system: "You are concise.", prompt: "Say hello in one short sentence.", - generation: { maxTokens: 40 }, + maxTokens: 40, }) console.log(response.text) }) @@ -409,7 +409,7 @@ shared host; the entry above follows the base URL table. Dedicated hosts can be Replay complete `response.message` values to retain `reasoning_content` separately from answer text. Qwen 3.8 defaults to preserving thinking; older models have different defaults. Additional options include `toolStream`, `parallelToolCalls`, `repetitionPenalty`, `responseFormat`, - `enableSearch`, and native `searchOptions`. `generation.topK` lowers to `top_k`. + `enableSearch`, and native `searchOptions`. `topK` lowers to `top_k`. `clearThinking` is a hosted GLM control, and `thinking.type` is available for hosted MiniMax models. - **Messages:** `effort` → `output_config.effort`. `thinking.type` accepts enabled/disabled with an optional `budgetTokens` (or native `budget_tokens`). `outputConfig.format` accepts a JSON schema. @@ -578,7 +578,7 @@ const request = ai.request({ model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3") prompt: "What is 173 multiplied by 219?", providerOptions: { thinking: { type: "adaptive" } }, - generation: { maxTokens: 1536 }, + maxTokens: 1536, }) const response = await Effect.runPromise(ai.generate(request).pipe(Effect.provide(AIClient.layer))) @@ -616,7 +616,7 @@ const request = ai.request({ model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses prompt: "What is 173 multiplied by 219? Reply with the integer.", providerOptions: { reasoningEffort: "low" }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }) ``` @@ -638,7 +638,7 @@ Responses and Chat support only `toolChoice: "auto"` (the default). Messages als its documented forced `"any"` choice currently returns HTTP 400. Messages defaults to adaptive thinking with `display: "omitted"`, preserving encrypted `redacted_thinking` in `response.message`. Use `providerOptions: { effort: "low" }` for depth or `thinking: { type: "enabled", budgetTokens: 1024 }` -for budget compatibility (with `generation.maxTokens > 1024`). +for budget compatibility (with `maxTokens > 1024`). Add `tools: [Meta.webSearch()]` to a Spark Responses or Messages request for hosted web search. Responses exposes hosted results and URL citations in text-part `providerMetadata.meta.annotations`. @@ -1620,7 +1620,7 @@ Additional provider entrypoints include: Request options in order of stability: -1. **`generation`** — portable knobs (`maxTokens`, `temperature`, `topP`, `topK`, penalties, seed, stop). +1. **Portable knobs** — `maxTokens`, `temperature`, `topP`, `topK`, `frequencyPenalty`, `presencePenalty`, `seed` and `stop`, at the top level of a text request. `GENERATION_KEYS` lists them. 2. **`promptCacheKey`** — stable cache affinity lowered by every protocol that supports it. 3. **`providerOptions: { ... }`** — flat options inferred from the selected model (OpenAI `store`, Anthropic `thinking`, Gemini `thinkingConfig`, OpenRouter routing). 4. **`http: { body, headers, query }`** — last-resort serializable overlays merged into the final HTTP request. Reach for this only when a stable typed path doesn't yet exist. diff --git a/packages/ai/example/tutorial.ts b/packages/ai/example/tutorial.ts index d4101475b274..f02a2890d420 100644 --- a/packages/ai/example/tutorial.ts +++ b/packages/ai/example/tutorial.ts @@ -28,7 +28,7 @@ const apiKey = Config.Redacted("OPENAI_API_KEY") // image generation. const openai = OpenAI.configure({ apiKey, - generation: { maxTokens: 160 }, + maxTokens: 160, providerOptions: { store: false, }, @@ -40,8 +40,8 @@ const model = openai.responses("gpt-4o-mini") // // Options can live on both the configured route/provider facade and the request: // -// - `generation`: common controls such as max tokens, temperature, topP/topK, -// penalties, seed, and stop sequences. +// - `maxTokens`, `temperature`, `topP`, `topK`, penalties, `seed` and `stop`: +// common controls set at the top level. // - `promptCacheKey`: stable cache affinity for protocols that support it. // - `providerOptions`: model-typed provider-native behavior. For example, // OpenAI store behavior, Anthropic thinking, Gemini thinking config, or @@ -54,7 +54,8 @@ const request = ai.request({ model, system: "You are concise and practical.", prompt: "Tell me a joke", - generation: { maxTokens: 80, temperature: 0.7 }, + maxTokens: 80, + temperature: 0.7, promptCacheKey: "tutorial-joke", }) @@ -100,7 +101,8 @@ const streamWithTools = Effect.gen(function* () { const request = ai.request({ model, prompt: "Use get_weather for San Francisco, then answer in one sentence.", - generation: { maxTokens: 80, temperature: 0 }, + maxTokens: 80, + temperature: 0, tools, }) const events = Array.from(yield* ai.stream(request).pipe(Stream.runCollect)) @@ -139,7 +141,8 @@ const generateStructuredObject = Effect.gen(function* () { system: "Return only structured weather data.", prompt: "Give me today's weather for San Francisco.", schema: WeatherReport, - generation: { maxTokens: 120, temperature: 0 }, + maxTokens: 120, + temperature: 0, }) console.log("\n== structured output ==") diff --git a/packages/ai/src/llm.ts b/packages/ai/src/llm.ts index 6dc070b1aaec..bf35b69f87bf 100644 --- a/packages/ai/src/llm.ts +++ b/packages/ai/src/llm.ts @@ -12,9 +12,9 @@ import { type TriggerCompactOptions, } from "./route/client.js" import { - GenerationOptions, InvalidProviderOutputError, InvalidRequestError, + mergeGeneration, AIError, LLMEvent, LLMResponse, @@ -31,6 +31,7 @@ import { ToolEntry, Usage, type LanguageModelProviderOptions, + type GenerationOptionsFields, type LLMRequest, type ToolEntryInput, withPartial, @@ -48,13 +49,13 @@ export type PromptOrMessages = | { readonly messages: ReadonlyArray; readonly prompt?: never } interface TextRequestFields - extends BaseRequest>> { + extends BaseRequest>>, + GenerationOptionsFields { readonly id?: string readonly system?: string | SystemPart | ReadonlyArray /** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */ readonly tools?: ReadonlyArray readonly toolChoice?: ToolChoice.Input - readonly generation?: GenerationOptions.Input readonly cache?: CachePolicy /** Stable cache affinity for protocols that support provider-managed prompt caching. */ readonly promptCacheKey?: string @@ -300,7 +301,7 @@ export const request = (input: LLMRequestInpu messages: input.prompt === undefined ? (input.messages ?? []).map(Message.make) : [Message.user(input.prompt)], tools: input.tools?.map((item) => ("_definition" in item ? item._definition : ToolEntry.make(item))) ?? [], toolChoice: input.toolChoice ? ToolChoice.make(input.toolChoice) : undefined, - generation: input.generation === undefined ? undefined : GenerationOptions.make(input.generation), + ...mergeGeneration(input), providerOptions: input.providerOptions, headers: input.headers, fetch: input.fetch, diff --git a/packages/ai/src/protocols/alibaba-chat.ts b/packages/ai/src/protocols/alibaba-chat.ts index 910117da969a..6913c1cbe20d 100644 --- a/packages/ai/src/protocols/alibaba-chat.ts +++ b/packages/ai/src/protocols/alibaba-chat.ts @@ -1,6 +1,6 @@ import { Effect, Schema } from "effect" import { Protocol } from "../route/protocol.js" -import type { LanguageModelCompatibility } from "../schema/index.js" +import type { LanguageModelCompatibility, Capabilities } from "../schema/index.js" import { OpenAIChat } from "./openai-chat.js" import { JsonObject, ProviderShared } from "./shared.js" import { cacheControl } from "./utils/cache.js" @@ -41,11 +41,12 @@ export type OptionsInput = typeof Options.Type export const compatibility = { maxTokensField: "max_completion_tokens", - supportsStrictMode: false, reasoningField: "reasoning_content", zaiToolStream: false, } satisfies LanguageModelCompatibility +export const capabilities = { tools: { strict: false } } satisfies Capabilities + export const protocol = Protocol.make({ id: "alibaba-chat", body: { @@ -72,7 +73,7 @@ export const protocol = Protocol.make({ thinking_budget: opts.thinkingBudget === undefined ? undefined - : ProviderShared.fitThinkingBudget(opts.thinkingBudget, req.generation?.maxTokens), + : ProviderShared.fitThinkingBudget(opts.thinkingBudget, req.maxTokens), preserve_thinking: opts.preserveThinking, clear_thinking: opts.clearThinking, thinking: opts.thinking, @@ -81,7 +82,7 @@ export const protocol = Protocol.make({ opts.parallelToolCalls ?? (req.toolChoice?.disableParallelToolUse === undefined ? undefined : !req.toolChoice.disableParallelToolUse), repetition_penalty: opts.repetitionPenalty, - top_k: req.generation?.topK, + top_k: req.topK, response_format: opts.responseFormat, enable_search: opts.enableSearch, search_options: opts.searchOptions, diff --git a/packages/ai/src/protocols/anthropic-messages.ts b/packages/ai/src/protocols/anthropic-messages.ts index d6eee0f4eb30..5fd3b33b96a0 100644 --- a/packages/ai/src/protocols/anthropic-messages.ts +++ b/packages/ai/src/protocols/anthropic-messages.ts @@ -745,6 +745,8 @@ const requireThinkingSignature = (request: LLMRequest) => { // Opus 4.8 and every Claude 5 model accept mid-conversation system messages; later versions inherit support. const supportsNativeSystemUpdates = (request: LLMRequest) => { + const override = request.model.capabilities?.systemUpdates + if (override !== undefined) return override const version = claudeVersion(request.model.id) if (version === undefined) return false if (version.family === "opus" && version.major === 4) return version.minor >= 8 @@ -913,15 +915,14 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi return messages }) -// TODO: Move per-model capability heuristics (`supportsEffortUpdates`, `supportsNativeSystemUpdates`, -// `supportsThinkingBlockBinding`) into explicit model/provider `compatibility` metadata so the protocol -// only reads `request.model.compatibility`. +// The model-ID checks below are fallbacks for models that leave `capabilities.reasoning.updates`, +// `capabilities.systemUpdates` and `compatibility.supportsThinkingBlockBinding` unset. const isThinkingOff = Schema.is(AnthropicThinkingDisabled) // Per-turn effort started with Claude Opus 5 and every Claude 5.1 model; later versions of any family inherit it. const supportsEffortUpdates = (request: LLMRequest) => { if (isThinkingOff(request.providerOptions?.thinking)) return false - const override = request.model.compatibility?.supportsEffortUpdates + const override = request.model.capabilities?.reasoning?.updates if (override !== undefined) return override const version = claudeVersion(request.model.id) if (version === undefined) return false @@ -956,7 +957,6 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques const outputConfig = options.output_config ?? options.outputConfig const format = outputConfig?.format ?? undefined const updates = resolveEffortUpdates(request, options.effort ?? outputConfig?.effort ?? undefined) - const generation = request.generation // Allocate the 4-breakpoint budget in invalidation order: tools → system → // messages. Tools live highest in the cache hierarchy, so when callers // over-mark we keep their tool hints and shed the message-tail ones first. @@ -978,7 +978,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP) const output_config = updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format } - const maxTokens = generation?.maxTokens ?? DEFAULT_MAX_TOKENS + const maxTokens = request.maxTokens ?? DEFAULT_MAX_TOKENS const body = { model: request.model.id, system, @@ -987,10 +987,10 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques tool_choice: toolChoice, stream: true as const, max_tokens: maxTokens, - temperature: generation?.temperature, - top_p: generation?.topP, - top_k: generation?.topK, - stop_sequences: generation?.stop, + temperature: request.temperature, + top_p: request.topP, + top_k: request.topK, + stop_sequences: request.stop, thinking: applyThinkingBindingDefault(request.model, fitThinking(options.thinking, maxTokens)), output_config, // top-level passthrough per SDK MessageCreateParamsBase:4638,4643,4649,4654,4670 diff --git a/packages/ai/src/protocols/bedrock-converse.ts b/packages/ai/src/protocols/bedrock-converse.ts index 6495524c6819..85d798a702df 100644 --- a/packages/ai/src/protocols/bedrock-converse.ts +++ b/packages/ai/src/protocols/bedrock-converse.ts @@ -561,12 +561,11 @@ const applyThinkingBindingDefault = (request: LLMRequest, thinking: Readonly { @@ -584,7 +583,7 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: })(), ) const additionalModelRequestFields = { - ...(generation?.topK === undefined ? {} : { top_k: generation.topK }), + ...(request.topK === undefined ? {} : { top_k: request.topK }), ...(thinking === undefined ? {} : { thinking }), ...(options.effort === undefined ? {} : effortFields(request.model, options.effort)), // Converse takes Anthropic betas in the body, and Bedrock rejects `block_binding` without this one. @@ -608,16 +607,16 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: const inferenceConfig = (() => { if ( maxTokens === undefined && - generation?.temperature === undefined && - generation?.topP === undefined && - (generation?.stop === undefined || generation.stop.length === 0) + request.temperature === undefined && + request.topP === undefined && + (request.stop === undefined || request.stop.length === 0) ) return undefined return { maxTokens, - temperature: generation?.temperature, - topP: generation?.topP, - stopSequences: generation?.stop, + temperature: request.temperature, + topP: request.topP, + stopSequences: request.stop, } })() return { diff --git a/packages/ai/src/protocols/cohere-chat.ts b/packages/ai/src/protocols/cohere-chat.ts index bf509418eda2..c1944f9db8f4 100644 --- a/packages/ai/src/protocols/cohere-chat.ts +++ b/packages/ai/src/protocols/cohere-chat.ts @@ -233,16 +233,16 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMR token_budget: options.thinking.tokenBudget === undefined ? undefined - : ProviderShared.fitThinkingBudget(options.thinking.tokenBudget, request.generation?.maxTokens), + : ProviderShared.fitThinkingBudget(options.thinking.tokenBudget, request.maxTokens), }, - max_tokens: request.generation?.maxTokens, - temperature: request.generation?.temperature, - p: request.generation?.topP, - k: request.generation?.topK, - seed: request.generation?.seed, - stop_sequences: request.generation?.stop, - frequency_penalty: request.generation?.frequencyPenalty, - presence_penalty: request.generation?.presencePenalty, + max_tokens: request.maxTokens, + temperature: request.temperature, + p: request.topP, + k: request.topK, + seed: request.seed, + stop_sequences: request.stop, + frequency_penalty: request.frequencyPenalty, + presence_penalty: request.presencePenalty, } }) diff --git a/packages/ai/src/protocols/gemini.ts b/packages/ai/src/protocols/gemini.ts index 22389c0e6547..0a9feee962c0 100644 --- a/packages/ai/src/protocols/gemini.ts +++ b/packages/ai/src/protocols/gemini.ts @@ -444,17 +444,16 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) { const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMRequest) { const flattened = ProviderShared.flattenToolRequest(request) const hasTools = flattened.tools.length > 0 - const generation = request.generation const options = yield* decodeOptions(request.providerOptions ?? {}) const generationConfig = { - maxOutputTokens: generation?.maxTokens, - temperature: generation?.temperature, - topP: generation?.topP, - topK: generation?.topK, - frequencyPenalty: generation?.frequencyPenalty, - presencePenalty: generation?.presencePenalty, - seed: generation?.seed, - stopSequences: generation?.stop, + maxOutputTokens: request.maxTokens, + temperature: request.temperature, + topP: request.topP, + topK: request.topK, + frequencyPenalty: request.frequencyPenalty, + presencePenalty: request.presencePenalty, + seed: request.seed, + stopSequences: request.stop, // Gemini accepts a budget above `maxOutputTokens`, but thinking then leaves the answer empty. thinkingConfig: options.thinkingConfig === undefined @@ -467,7 +466,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque ? undefined : ProviderShared.fitThinkingBudget( options.thinkingConfig.thinkingBudget, - generation?.maxTokens, + request.maxTokens, MIN_THINKING_BUDGET, ), }, diff --git a/packages/ai/src/protocols/google-interactions.ts b/packages/ai/src/protocols/google-interactions.ts index 9cf3cc738106..858849f8c7c0 100644 --- a/packages/ai/src/protocols/google-interactions.ts +++ b/packages/ai/src/protocols/google-interactions.ts @@ -338,11 +338,7 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque const flattened = ProviderShared.flattenToolRequest(request) if (flattened.tools.some((tool) => tool.native !== undefined)) return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported") - if ( - request.generation?.topK !== undefined || - request.generation?.frequencyPenalty !== undefined || - request.generation?.presencePenalty !== undefined - ) + if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined) return yield* ProviderShared.invalidRequest( "Google Interactions does not support topK, frequencyPenalty, or presencePenalty", ) @@ -373,11 +369,11 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque })) : undefined, generation_config: { - max_output_tokens: request.generation?.maxTokens, - temperature: request.generation?.temperature, - top_p: request.generation?.topP, - seed: request.generation?.seed, - stop_sequences: request.generation?.stop, + max_output_tokens: request.maxTokens, + temperature: request.temperature, + top_p: request.topP, + seed: request.seed, + stop_sequences: request.stop, thinking_level: options.thinkingLevel, thinking_summaries: options.thinkingSummaries, tool_choice: choice, diff --git a/packages/ai/src/protocols/mistral-chat.ts b/packages/ai/src/protocols/mistral-chat.ts index 6e9975c26624..be8765da7193 100644 --- a/packages/ai/src/protocols/mistral-chat.ts +++ b/packages/ai/src/protocols/mistral-chat.ts @@ -392,13 +392,13 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque tools: flattened.tools.length > 0 ? flattened.tools.map(lowerTool) : undefined, tool_choice: toolChoice, stream: true as const, - max_tokens: request.generation?.maxTokens, - random_seed: request.generation?.seed, - temperature: request.generation?.temperature, - top_p: request.generation?.topP, - frequency_penalty: request.generation?.frequencyPenalty, - presence_penalty: request.generation?.presencePenalty, - stop: request.generation?.stop, + max_tokens: request.maxTokens, + random_seed: request.seed, + temperature: request.temperature, + top_p: request.topP, + frequency_penalty: request.frequencyPenalty, + presence_penalty: request.presencePenalty, + stop: request.stop, prompt_cache_key: ProviderShared.sendsPromptCacheKey(request) ? (options.promptCacheKey ?? request.promptCacheKey) : undefined, diff --git a/packages/ai/src/protocols/open-responses-channel.ts b/packages/ai/src/protocols/open-responses-channel.ts index ab47b0a05353..e54680fc66a5 100644 --- a/packages/ai/src/protocols/open-responses-channel.ts +++ b/packages/ai/src/protocols/open-responses-channel.ts @@ -85,11 +85,7 @@ const observer = (options: Options) => { if (event.type === "response.created") { const created = event.response?.id if (responseID) - return yield* ProviderShared.eventError( - options.id, - `${options.name} emitted duplicate response.created`, - frame, - ) + return yield* ProviderShared.eventError(options.id, `${options.name} emitted duplicate response.created`, frame) if (!created) return yield* ProviderShared.eventError( options.id, @@ -108,11 +104,7 @@ const observer = (options: Options) => { frame, ) if (event.response?.id && event.response.id !== responseID) - return yield* ProviderShared.eventError( - options.id, - `${options.name} response ID changed during execution`, - frame, - ) + return yield* ProviderShared.eventError(options.id, `${options.name} response ID changed during execution`, frame) if (event.type === "response.completed") { terminal = true return { type: "completed", frame } diff --git a/packages/ai/src/protocols/open-responses.ts b/packages/ai/src/protocols/open-responses.ts index 5172546ecaa2..27fe1865e127 100644 --- a/packages/ai/src/protocols/open-responses.ts +++ b/packages/ai/src/protocols/open-responses.ts @@ -815,16 +815,15 @@ export const lowerConversation = Effect.fnUntraced(function* (request: LLMReques }) export const lowerGeneration = (request: LLMRequest, options = OpenResponsesOptions.resolve(request)) => { - const generation = request.generation const cacheKey = ProviderShared.promptCacheKey(request) const parallelToolCalls = resolveParallelToolCalls(request, options) return { stream: true as const, - max_output_tokens: generation?.maxTokens, - temperature: generation?.temperature, - top_p: generation?.topP, - presence_penalty: generation?.presencePenalty, - frequency_penalty: generation?.frequencyPenalty, + max_output_tokens: request.maxTokens, + temperature: request.temperature, + top_p: request.topP, + presence_penalty: request.presencePenalty, + frequency_penalty: request.frequencyPenalty, ...(options.store !== undefined ? { store: options.store } : {}), ...(options.metadata ? { metadata: options.metadata } : {}), ...(options.safetyIdentifier ? { safety_identifier: options.safetyIdentifier } : {}), diff --git a/packages/ai/src/protocols/openai-chat.ts b/packages/ai/src/protocols/openai-chat.ts index cd76637892c2..35c17d045cc0 100644 --- a/packages/ai/src/protocols/openai-chat.ts +++ b/packages/ai/src/protocols/openai-chat.ts @@ -830,7 +830,7 @@ const lowerOptions = (request: LLMRequest, supportsStore: boolean, hasActiveTool // the key where compatibility explicitly allows it. Header-based affinity // (x-session-affinity, x-grok-conv-id, ...) is unaffected. const cacheKey = - (request.model.compatibility?.supportsPromptCacheKey ?? false) ? ProviderShared.promptCacheKey(request) : undefined + (request.model.capabilities?.promptCacheKey ?? false) ? ProviderShared.promptCacheKey(request) : undefined return { ...(supportsStore ? { store: options.store ?? false } : {}), ...(cacheKey ? { prompt_cache_key: cacheKey } : {}), @@ -856,15 +856,13 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* ( return yield* ProviderShared.invalidRequest( `OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`, ) - const generation = request.generation const flattened = ProviderShared.flattenToolRequest(request) const provider = request.model.provider const baseURL = request.model.route.endpoint.baseURL const detectedMaxTokensField = detectMaxTokensField(provider, baseURL) const maxTokensField = request.model.compatibility?.maxTokensField ?? detectedMaxTokensField - const supportsStore = request.model.compatibility?.supportsStore ?? detectSupportsStore(provider, baseURL) - const supportsStrictMode = - request.model.compatibility?.supportsStrictMode ?? detectSupportsStrictMode(provider, baseURL) + const supportsStore = request.model.capabilities?.store ?? detectSupportsStore(provider, baseURL) + const supportsStrictMode = request.model.capabilities?.tools?.strict ?? detectSupportsStrictMode(provider, baseURL) const zaiToolStream = request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id) const hasHistory = hasToolHistory(request.messages) @@ -882,17 +880,17 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* ( : flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))), tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined, stream: true as const, - ...((request.model.compatibility?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}), + ...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}), ...(zaiToolStream && hasActiveTools ? { tool_stream: true } : {}), ...(maxTokensField === "max_completion_tokens" - ? { max_completion_tokens: generation?.maxTokens } - : { max_tokens: generation?.maxTokens }), - temperature: generation?.temperature, - top_p: generation?.topP, - frequency_penalty: generation?.frequencyPenalty, - presence_penalty: generation?.presencePenalty, - seed: generation?.seed, - stop: generation?.stop, + ? { max_completion_tokens: request.maxTokens } + : { max_tokens: request.maxTokens }), + temperature: request.temperature, + top_p: request.topP, + frequency_penalty: request.frequencyPenalty, + presence_penalty: request.presencePenalty, + seed: request.seed, + stop: request.stop, ...lowerOptions(request, supportsStore, hasActiveTools), } }) diff --git a/packages/ai/src/protocols/openai-compatible-responses.ts b/packages/ai/src/protocols/openai-compatible-responses.ts index 26c35fc49c17..19966c9a3e5b 100644 --- a/packages/ai/src/protocols/openai-compatible-responses.ts +++ b/packages/ai/src/protocols/openai-compatible-responses.ts @@ -15,7 +15,7 @@ export const route = Route.make({ protocol: OpenResponses.protocol, endpoint: Endpoint.path(OpenResponses.PATH), transport: OpenResponses.httpTransport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) export * as OpenAICompatibleResponses from "./openai-compatible-responses.js" diff --git a/packages/ai/src/protocols/openai-responses.ts b/packages/ai/src/protocols/openai-responses.ts index 4e905856ff9f..d50c44a3a56d 100644 --- a/packages/ai/src/protocols/openai-responses.ts +++ b/packages/ai/src/protocols/openai-responses.ts @@ -167,7 +167,7 @@ const supportsEffortUpdates = (request: LLMRequest) => { if (request.providerOptions?.contextManagement !== undefined) return false if (request.providerOptions?.reasoningMode === "pro") return false if (Schema.is(Schema.Struct({ mode: Schema.Literal("pro") }))(request.http?.body?.reasoning)) return false - const override = request.model.compatibility?.supportsEffortUpdates + const override = request.model.capabilities?.reasoning?.updates if (override !== undefined) return override const match = /(?:^|\/)gpt-(\d+)(?:\.\d+)?(?:-|$)/i.exec(request.model.id) return match !== null && Number(match[1]) >= 6 @@ -360,7 +360,7 @@ export const route = Route.make({ endpoint, auth, transport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) export * as OpenAIResponses from "./openai-responses.js" diff --git a/packages/ai/src/protocols/shared.ts b/packages/ai/src/protocols/shared.ts index 6913ab77168d..47414d12e9bd 100644 --- a/packages/ai/src/protocols/shared.ts +++ b/packages/ai/src/protocols/shared.ts @@ -88,7 +88,7 @@ export const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64 // Body-level `prompt_cache_key` is off when caching is disabled or the model // explicitly rejects the field. Header-based affinity is unaffected. export const sendsPromptCacheKey = (request: LLMRequest) => - request.cache !== "none" && request.model.compatibility?.supportsPromptCacheKey !== false + request.cache !== "none" && request.model.capabilities?.promptCacheKey !== false // OpenAI limits `prompt_cache_key` to 64 chars; DeepSeek and Zai inherit the same // limit via their OpenAI-compatible APIs. Clamp with unicode-aware slicing. diff --git a/packages/ai/src/protocols/venice-chat.ts b/packages/ai/src/protocols/venice-chat.ts index d61f7848a880..e99c3899f0d3 100644 --- a/packages/ai/src/protocols/venice-chat.ts +++ b/packages/ai/src/protocols/venice-chat.ts @@ -1,6 +1,12 @@ import { Effect, Schema } from "effect" import { Protocol } from "../route/protocol.js" -import { AIError, LLMEvent, type LanguageModelCompatibility, type LLMRequest } from "../schema/index.js" +import { + AIError, + LLMEvent, + type LanguageModelCompatibility, + type LLMRequest, + type Capabilities, +} from "../schema/index.js" import { classifyProviderFailure } from "../provider-error.js" import { OpenAIChat } from "./openai-chat.js" import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js" @@ -188,7 +194,7 @@ const fromRequest = Effect.fn("VeniceChat.fromRequest")(function* (request: LLMR }) return { ...body, - max_completion_tokens: options.maxCompletionTokens ?? options.maxTokens ?? request.generation?.maxTokens, + max_completion_tokens: options.maxCompletionTokens ?? options.maxTokens ?? request.maxTokens, reasoning_effort: undefined, reasoning: options.reasoningEffort === undefined @@ -206,7 +212,7 @@ const fromRequest = Effect.fn("VeniceChat.fromRequest")(function* (request: LLMR prompt_cache_retention: options.promptCacheRetention ?? body.prompt_cache_retention, parallel_tool_calls: options.parallelToolCalls, min_p: options.minP, - top_k: request.generation?.topK, + top_k: request.topK, repetition_penalty: options.repetitionPenalty, stop_token_ids: options.stopTokenIds, logprobs: options.logprobs, @@ -325,9 +331,10 @@ const onHalt = Effect.fn("VeniceChat.onHalt")(function* (state: State) { export const compatibility = { maxTokensField: "max_completion_tokens", - supportsPromptCacheKey: true, } satisfies LanguageModelCompatibility +export const capabilities = { promptCacheKey: true } satisfies Capabilities + export const protocol = Protocol.make({ id: "venice-chat", body: { schema: Body, from: fromRequest }, diff --git a/packages/ai/src/protocols/xai-responses.ts b/packages/ai/src/protocols/xai-responses.ts index dd4b1928b579..8850ac367eea 100644 --- a/packages/ai/src/protocols/xai-responses.ts +++ b/packages/ai/src/protocols/xai-responses.ts @@ -71,7 +71,7 @@ const fromRequest = Effect.fn("XAIResponses.fromRequest")(function* (request: LL ...body, presence_penalty: undefined, frequency_penalty: undefined, - top_k: request.generation?.topK, + top_k: request.topK, min_p: options.minP, } }) diff --git a/packages/ai/src/protocols/zai-chat.ts b/packages/ai/src/protocols/zai-chat.ts index 8b410ebc603a..5b8cdd4e800a 100644 --- a/packages/ai/src/protocols/zai-chat.ts +++ b/packages/ai/src/protocols/zai-chat.ts @@ -1,6 +1,6 @@ import { Effect, Schema } from "effect" import { Protocol } from "../route/protocol.js" -import type { LanguageModelCompatibility, LLMRequest } from "../schema/index.js" +import type { LanguageModelCompatibility, LLMRequest, Capabilities } from "../schema/index.js" import { OpenAIChat } from "./openai-chat.js" import { ProviderShared } from "./shared.js" import { OpenResponsesOptions } from "./utils/open-responses-options.js" @@ -56,11 +56,12 @@ const fromRequest = Effect.fn("ZAIChat.fromRequest")(function* (request: LLMRequ export const compatibility = { maxTokensField: "max_tokens", - supportsStrictMode: false, reasoningField: "reasoning_content", zaiToolStream: false, } satisfies LanguageModelCompatibility +export const capabilities = { tools: { strict: false } } satisfies Capabilities + export const protocol = Protocol.make({ id: "zai-chat", body: { schema: Body, from: fromRequest }, diff --git a/packages/ai/src/providers/alibaba.ts b/packages/ai/src/providers/alibaba.ts index c7007acc59b8..31ebe2b90aea 100644 --- a/packages/ai/src/providers/alibaba.ts +++ b/packages/ai/src/providers/alibaba.ts @@ -5,7 +5,7 @@ import { AlibabaImages } from "../protocols/alibaba-images.js" import { AlibabaMessages } from "../protocols/alibaba-messages.js" import { AlibabaResponses } from "../protocols/alibaba-responses.js" import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" import { MediaRoute } from "../route/media.js" @@ -15,6 +15,7 @@ import { ToolDefinition, type ModelID, type ProviderOptions, + type RequestOptions, } from "../schema/index.js" export const id = ProviderID.make("alibaba") @@ -39,7 +40,7 @@ type Location = AtLeastOne<{ }> & { readonly workspaceID?: string } export type Config = Location & - Omit & + Omit & ProviderAuthOption<"optional"> & { readonly providerOptions?: ChatOptionsInput | MessagesOptionsInput | ResponsesOptionsInput } @@ -103,7 +104,9 @@ export const configure = (input: Config) => { const opts = { ...rest, auth: AuthOptions.bearer(input, ["DASHSCOPE_API_KEY", "ALIBABA_API_KEY"]) } const common = { ...opts, endpoint: { baseURL: baseURL ?? `https://${host}/compatible-mode/v1` } } const chat = (id: string | ModelID) => - chatRoute.with(common).model({ id, compatibility: AlibabaChat.compatibility }) + chatRoute + .with(common) + .model({ id, compatibility: AlibabaChat.compatibility, capabilities: AlibabaChat.capabilities }) const messages = (id: string | ModelID) => messagesRoute .with({ diff --git a/packages/ai/src/providers/amazon-bedrock-mantle.ts b/packages/ai/src/providers/amazon-bedrock-mantle.ts index 1ffa2636156e..94ec349fff63 100644 --- a/packages/ai/src/providers/amazon-bedrock-mantle.ts +++ b/packages/ai/src/providers/amazon-bedrock-mantle.ts @@ -1,4 +1,4 @@ -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import type { ProviderPackage } from "../provider-package.js" import { AnthropicMessages } from "../protocols/anthropic-messages.js" @@ -6,7 +6,7 @@ import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponses } from "../protocols/open-responses.js" import { BedrockAuth, type Credentials } from "../protocols/utils/bedrock-auth.js" import { claudeVersion } from "../protocols/utils/claude-model.js" -import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js" +import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options.js" export const id = ProviderID.make("amazon-bedrock") @@ -14,7 +14,7 @@ export const id = ProviderID.make("amazon-bedrock") export type OpenAIOptionsInput = OpenAIProviderOptionsInput export type MessagesOptionsInput = AnthropicMessages.ProviderOptionsInput -export type Config = Omit & { +export type Config = Omit & { /** Bedrock API key. Falls back to `AWS_BEARER_TOKEN_BEDROCK`; bearer auth takes precedence over SigV4. */ readonly apiKey?: string /** `sigv4` ignores `apiKey` fallbacks from the environment; `bearer` requires a token. */ @@ -55,7 +55,7 @@ const responsesRoute = Route.make({ protocol: OpenResponses.protocol, endpoint: Endpoint.path(OpenResponses.PATH), transport: OpenResponses.httpTransport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) const chatRoute = OpenAIChat.route.with({ @@ -73,7 +73,7 @@ const messagesRoute = Route.make({ // Mantle rejects mid-conversation `output_config` on Opus 5.0; support starts at 5.1+. supportsEffortUpdates: (request) => { if (!(AnthropicMessages.protocol.supportsEffortUpdates?.(request) ?? false)) return false - if (request.model.compatibility?.supportsEffortUpdates !== undefined) return true + if (request.model.capabilities?.reasoning?.updates !== undefined) return true const version = claudeVersion(request.model.id) return version !== undefined && (version.major > 5 || (version.major === 5 && version.minor >= 1)) }, @@ -173,7 +173,7 @@ const fromSettings = ({ auth, baseURL, credentials, - generation: topP === undefined ? undefined : { topP }, + topP, headers, http: body === undefined ? undefined : { body }, profile, diff --git a/packages/ai/src/providers/amazon-bedrock.ts b/packages/ai/src/providers/amazon-bedrock.ts index 27f1edf88eda..490e0fbd8531 100644 --- a/packages/ai/src/providers/amazon-bedrock.ts +++ b/packages/ai/src/providers/amazon-bedrock.ts @@ -1,13 +1,12 @@ -import type { RouteDefaultsInput } from "../route/client.js" import type { ProviderPackage } from "../provider-package.js" -import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js" +import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import * as BedrockConverse from "../protocols/bedrock-converse.js" import type { BedrockCredentials } from "../protocols/bedrock-converse.js" import { BedrockAuth } from "../protocols/utils/bedrock-auth.js" export const id = ProviderID.make("amazon-bedrock") -export type Config = RouteDefaultsInput & { +export type Config = RequestOptions & { /** Bedrock API key. Falls back to `AWS_BEARER_TOKEN_BEDROCK`; bearer auth takes precedence over SigV4. */ readonly apiKey?: string /** `sigv4` ignores `apiKey` fallbacks from the environment; `bearer` requires a token. */ @@ -73,7 +72,7 @@ export const model: ProviderPackage.Model & { readonly provider?: string readonly baseURL: string diff --git a/packages/ai/src/providers/anthropic.ts b/packages/ai/src/providers/anthropic.ts index 8071da941c50..43b265f3e567 100644 --- a/packages/ai/src/providers/anthropic.ts +++ b/packages/ai/src/providers/anthropic.ts @@ -1,8 +1,7 @@ -import type { RouteDefaultsInput } from "../route/client.js" import { Auth } from "../route/auth.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import type { ProviderPackage } from "../provider-package.js" -import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js" +import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { AnthropicMessages } from "../protocols/anthropic-messages.js" import { AnthropicCompatible } from "./anthropic-compatible.js" @@ -14,7 +13,7 @@ export const id = ProviderID.make("anthropic") export const routes = [AnthropicMessages.route] -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: AnthropicMessages.ProviderOptionsInput diff --git a/packages/ai/src/providers/azure.ts b/packages/ai/src/providers/azure.ts index a3e8793e3fdf..c3c60cbc71cd 100644 --- a/packages/ai/src/providers/azure.ts +++ b/packages/ai/src/providers/azure.ts @@ -1,10 +1,16 @@ import { Auth } from "../route/auth.js" import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js" -import type { Route, RouteDefaultsInput, CompactionOperations } from "../route/client.js" +import type { Route, CompactionOperations } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import type { ProviderPackage } from "../provider-package.js" import { MediaRoute } from "../route/media.js" -import { ProviderConfigurationError, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { + ProviderConfigurationError, + ProviderID, + type ModelID, + type ProviderOptions, + type RequestOptions, +} from "../schema/index.js" import { AnthropicMessages } from "../protocols/anthropic-messages.js" import { OpenAIImages } from "../protocols/openai-images.js" import * as OpenAIChat from "../protocols/openai-chat.js" @@ -20,7 +26,7 @@ const RESPONSES_WEBSOCKET_ROTATE_AFTER_MS = 55 * 60 * 1000 type AzureURL = AtLeastOne<{ readonly resourceName: string; readonly baseURL: string }> export type Config = AzureURL & - RouteDefaultsInput & + RequestOptions & ProviderAuthOption<"optional"> & { readonly apiVersion?: string readonly queryParams?: Record @@ -133,7 +139,7 @@ export const configure = (input: Config) => { const chat = (modelID: string | ModelID) => configuredRoute(chatRoute, input, modelID) .with(withOpenAIOptions(modelID, modelDefaults)) - .model({ id: modelID, compatibility: { supportsPromptCacheKey: true } }) + .model({ id: modelID, capabilities: { promptCacheKey: true } }) const messages = (modelID: string | ModelID) => messagesRoute diff --git a/packages/ai/src/providers/baseten.ts b/packages/ai/src/providers/baseten.ts index 245e2241ef56..f9e4185a16b4 100644 --- a/packages/ai/src/providers/baseten.ts +++ b/packages/ai/src/providers/baseten.ts @@ -3,17 +3,17 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { SystemOne } from "../protocols/system-one.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { DecisionRoute } from "../route/decision.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("baseten") const baseURL = "https://inference.baseten.co/v1" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput diff --git a/packages/ai/src/providers/cerebras.ts b/packages/ai/src/providers/cerebras.ts index 2034236896e0..17049c405fca 100644 --- a/packages/ai/src/providers/cerebras.ts +++ b/packages/ai/src/providers/cerebras.ts @@ -1,16 +1,16 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("cerebras") const baseURL = "https://api.cerebras.ai/v1" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput @@ -43,8 +43,8 @@ export const configure = (input: Config = {}) => { compatibility: { maxTokensField: "max_tokens", reasoningField: "reasoning", - supportsPromptCacheKey: true, }, + capabilities: { promptCacheKey: true }, }), configure, } diff --git a/packages/ai/src/providers/cloudflare-ai-gateway.ts b/packages/ai/src/providers/cloudflare-ai-gateway.ts index 9fba8996508b..09ce25a36d79 100644 --- a/packages/ai/src/providers/cloudflare-ai-gateway.ts +++ b/packages/ai/src/providers/cloudflare-ai-gateway.ts @@ -4,8 +4,7 @@ import { CloudflareRunDecisions } from "../protocols/cloudflare-run-decisions.js import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../protocols/index.js" import { Auth } from "../route/auth.js" import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js" -import type { RouteDefaultsInput } from "../route/client.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import { encodeJson } from "../utils/json.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { CloudflareShared } from "./cloudflare-shared.js" @@ -29,7 +28,7 @@ type GatewayOptions = { export type Config = GatewayURL & GatewayOptions & - Omit & + Omit & ProviderAuthOption<"optional"> & { readonly gatewayApiKey?: string | Redacted.Redacted | Config.Config readonly providerOptions?: OpenAIProviderOptionsInput diff --git a/packages/ai/src/providers/cloudflare-workers-ai.ts b/packages/ai/src/providers/cloudflare-workers-ai.ts index 728801e1009a..def5db10bca9 100644 --- a/packages/ai/src/providers/cloudflare-workers-ai.ts +++ b/packages/ai/src/providers/cloudflare-workers-ai.ts @@ -4,10 +4,10 @@ import { CloudflareRunDecisions } from "../protocols/cloudflare-run-decisions.js import { CloudflareWorkersAIImages } from "../protocols/cloudflare-workers-ai-images.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { CloudflareShared } from "./cloudflare-shared.js" @@ -20,7 +20,7 @@ type WorkersAIURL = AtLeastOne<{ }> export type Config = WorkersAIURL & - Omit & + Omit & ProviderAuthOption<"optional"> & { readonly providerOptions?: OpenAIProviderOptionsInput } diff --git a/packages/ai/src/providers/cohere.ts b/packages/ai/src/providers/cohere.ts index 8c9fcdc286cd..cd4f3982d1cf 100644 --- a/packages/ai/src/providers/cohere.ts +++ b/packages/ai/src/providers/cohere.ts @@ -1,9 +1,9 @@ import { CohereChat } from "../protocols/cohere-chat.js" import { OpenAIChat } from "../protocols/openai-chat.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { ProviderID, type ModelID, type OpenString } from "../schema/index.js" +import { ProviderID, type ModelID, type OpenString, type RequestOptions } from "../schema/index.js" import type { ProviderPackage } from "../provider-package.js" import { bearerRouteDefaults, toConfig } from "./settings.js" @@ -11,7 +11,7 @@ export const id = ProviderID.make("cohere") const COMPATIBILITY_BASE_URL = "https://api.cohere.ai/compatibility/v1" export type ChatOptionsInput = { readonly reasoningEffort?: OpenString<"none" | "high"> } export type ProviderOptions = CohereChat.ProviderOptionsInput & ChatOptionsInput -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: ProviderOptions @@ -43,8 +43,8 @@ export const configure = (input: Config = {}) => { compatibility: { maxTokensField: "max_tokens", reasoningField: "reasoning_content", - supportsStrictMode: false, }, + capabilities: { tools: { strict: false } }, }), configure, } diff --git a/packages/ai/src/providers/deepinfra.ts b/packages/ai/src/providers/deepinfra.ts index 573c487fe560..ae11b2ba3a48 100644 --- a/packages/ai/src/providers/deepinfra.ts +++ b/packages/ai/src/providers/deepinfra.ts @@ -1,16 +1,16 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("deepinfra") const baseURL = "https://api.deepinfra.com/v1/openai" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput @@ -49,8 +49,8 @@ export const configure = (input: Config = {}) => { compatibility: { maxTokensField: "max_tokens", reasoningField: "reasoning_content", - supportsPromptCacheKey: true, }, + capabilities: { promptCacheKey: true }, }), configure, } diff --git a/packages/ai/src/providers/deepseek.ts b/packages/ai/src/providers/deepseek.ts index 98262990d60d..38fc384f89ea 100644 --- a/packages/ai/src/providers/deepseek.ts +++ b/packages/ai/src/providers/deepseek.ts @@ -1,16 +1,16 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("deepseek") const baseURL = "https://api.deepseek.com/v1" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput diff --git a/packages/ai/src/providers/digitalocean.ts b/packages/ai/src/providers/digitalocean.ts index 700947d3ab93..78da6eb2236a 100644 --- a/packages/ai/src/providers/digitalocean.ts +++ b/packages/ai/src/providers/digitalocean.ts @@ -5,11 +5,11 @@ import { OpenResponses } from "../protocols/open-responses.js" import { SystemOne } from "../protocols/system-one.js" import { cacheControl } from "../protocols/utils/cache.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" import { Protocol } from "../route/protocol.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" import { bearerRouteDefaults } from "./settings.js" @@ -17,7 +17,7 @@ import { bearerRouteDefaults } from "./settings.js" export const id = ProviderID.make("digitalocean") const baseURL = "https://inference.do-ai.run/v1" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput | OpenResponsesProviderOptionsInput @@ -51,7 +51,7 @@ const responsesRoute = Route.make({ protocol: OpenResponses.protocol, endpoint: Endpoint.path("/responses", { baseURL }), transport: OpenResponses.httpTransport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) export const routes = [route, responsesRoute] @@ -81,9 +81,7 @@ export const configure = (input: Config = {}) => { const chat = (modelID: string | ModelID) => configured.model({ id: modelID, - compatibility: { - supportsPromptCacheKey: true, - }, + capabilities: { promptCacheKey: true }, }) return { id, diff --git a/packages/ai/src/providers/fireworks.ts b/packages/ai/src/providers/fireworks.ts index aa9dbcb851cf..41f12c71b1df 100644 --- a/packages/ai/src/providers/fireworks.ts +++ b/packages/ai/src/providers/fireworks.ts @@ -1,16 +1,16 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("fireworks") const baseURL = "https://api.fireworks.ai/inference/v1" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput @@ -38,7 +38,7 @@ export const configure = (input: Config = {}) => { return { id, model: (modelID: string | ModelID) => - configured.model({ id: modelID, compatibility: { supportsPromptCacheKey: true } }), + configured.model({ id: modelID, capabilities: { promptCacheKey: true } }), configure, } } diff --git a/packages/ai/src/providers/google-vertex-chat.ts b/packages/ai/src/providers/google-vertex-chat.ts index 53526463688e..f35218d20f28 100644 --- a/packages/ai/src/providers/google-vertex-chat.ts +++ b/packages/ai/src/providers/google-vertex-chat.ts @@ -1,14 +1,14 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" export const id = ProviderID.make("google-vertex") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & GoogleVertexShared.OAuthOptions & { readonly baseURL?: string readonly location?: string diff --git a/packages/ai/src/providers/google-vertex-interactions.ts b/packages/ai/src/providers/google-vertex-interactions.ts index 39e1b0040f1b..f3aa1e681a63 100644 --- a/packages/ai/src/providers/google-vertex-interactions.ts +++ b/packages/ai/src/providers/google-vertex-interactions.ts @@ -1,17 +1,17 @@ import type { ProviderPackage } from "../provider-package.js" import { GoogleInteractions } from "../protocols/google-interactions.js" import { Auth } from "../route/auth.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" -import { ProviderConfigurationError, ProviderID, type ModelID } from "../schema/index.js" +import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" export type GoogleInteractionsOptionsInput = GoogleInteractions.OptionsInput export const id = ProviderID.make("google-vertex") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & GoogleVertexShared.ApiKeyOptions & { readonly baseURL?: string readonly location?: string diff --git a/packages/ai/src/providers/google-vertex-messages.ts b/packages/ai/src/providers/google-vertex-messages.ts index 43d72f567f13..97bb8e66d060 100644 --- a/packages/ai/src/providers/google-vertex-messages.ts +++ b/packages/ai/src/providers/google-vertex-messages.ts @@ -2,10 +2,10 @@ import { Effect, Schema, Struct } from "effect" import type { ProviderPackage } from "../provider-package.js" import { AnthropicMessages } from "../protocols/anthropic-messages.js" import { Auth } from "../route/auth.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Protocol } from "../route/protocol.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" export type AnthropicOptionsInput = AnthropicMessages.OptionsInput @@ -17,7 +17,7 @@ const HEADER_VERSION = "2023-06-01" as const export const id = ProviderID.make("google-vertex") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & GoogleVertexShared.OAuthOptions & { readonly baseURL?: string readonly location?: string diff --git a/packages/ai/src/providers/google-vertex-mistral.ts b/packages/ai/src/providers/google-vertex-mistral.ts index 09d1ff5d7515..59eaed1c56ef 100644 --- a/packages/ai/src/providers/google-vertex-mistral.ts +++ b/packages/ai/src/providers/google-vertex-mistral.ts @@ -2,16 +2,16 @@ import { Effect, Schema, Struct } from "effect" import type { ProviderPackage } from "../provider-package.js" import { MistralChat } from "../protocols/mistral-chat.js" import { Auth } from "../route/auth.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Protocol } from "../route/protocol.js" import { HttpTransport } from "../route/transport/index.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" export const id = ProviderID.make("google-vertex") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & GoogleVertexShared.OAuthOptions & { readonly baseURL?: string readonly location?: string diff --git a/packages/ai/src/providers/google-vertex-responses.ts b/packages/ai/src/providers/google-vertex-responses.ts index b86c840c7994..523d847ddb0f 100644 --- a/packages/ai/src/providers/google-vertex-responses.ts +++ b/packages/ai/src/providers/google-vertex-responses.ts @@ -1,14 +1,14 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenResponses } from "../protocols/open-responses.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" export const id = ProviderID.make("google-vertex") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & GoogleVertexShared.OAuthOptions & { readonly baseURL?: string readonly location?: string @@ -32,7 +32,7 @@ const route = Route.make({ protocol: OpenResponses.protocol, endpoint: Endpoint.path(OpenResponses.PATH), transport: OpenResponses.httpTransport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) export const routes = [route] diff --git a/packages/ai/src/providers/google-vertex-shared.ts b/packages/ai/src/providers/google-vertex-shared.ts index fbf1572640d2..9590ff187575 100644 --- a/packages/ai/src/providers/google-vertex-shared.ts +++ b/packages/ai/src/providers/google-vertex-shared.ts @@ -2,8 +2,8 @@ import type { AnyAuthClient, GoogleAuthOptions } from "google-auth-library" import { Effect, Redacted } from "effect" import type { ProviderPackage } from "../provider-package.js" import { Auth, MissingCredentialError } from "../route/auth.js" -import type { CompactionOperations, Route, RouteDefaultsInput } from "../route/client.js" -import { ProviderConfigurationError, ProviderID } from "../schema/index.js" +import type { CompactionOperations, Route } from "../route/client.js" +import { ProviderConfigurationError, ProviderID, type RequestOptions } from "../schema/index.js" const SCOPE = "https://www.googleapis.com/auth/cloud-platform" const id = ProviderID.make("google-vertex") @@ -117,7 +117,7 @@ export const oauth = (input: OAuthOptions, project?: string) => { export const oauthRoute = ( route: Route, label: string, - input: RouteDefaultsInput & + input: RequestOptions & OAuthOptions & { readonly baseURL?: string; readonly location?: string; readonly project?: string }, url: (project: string, location: string) => string, ) => { diff --git a/packages/ai/src/providers/google-vertex.ts b/packages/ai/src/providers/google-vertex.ts index ffff60709986..6d60157f03bf 100644 --- a/packages/ai/src/providers/google-vertex.ts +++ b/packages/ai/src/providers/google-vertex.ts @@ -4,7 +4,7 @@ import { Gemini } from "../protocols/gemini.js" import { GoogleImages } from "../protocols/google-images.js" import { ProviderShared } from "../protocols/shared.js" import { Auth } from "../route/auth.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" import { @@ -13,6 +13,7 @@ import { type LLMRequest, type ModelID, type ProviderOptions, + type RequestOptions, } from "../schema/index.js" import { GoogleVertexShared } from "./google-vertex-shared.js" @@ -24,7 +25,7 @@ export type GeminiProviderOptionsInput = GeminiOptionsInput export const id = ProviderID.make("google-vertex") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & GoogleVertexShared.ApiKeyOptions & { readonly baseURL?: string readonly location?: string diff --git a/packages/ai/src/providers/google.ts b/packages/ai/src/providers/google.ts index 330c690a1bf2..d5fb4cb7966c 100644 --- a/packages/ai/src/providers/google.ts +++ b/packages/ai/src/providers/google.ts @@ -1,9 +1,8 @@ -import type { RouteDefaultsInput } from "../route/client.js" import { Auth } from "../route/auth.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import { MediaRoute } from "../route/media.js" import type { ProviderPackage } from "../provider-package.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import { Gemini } from "../protocols/gemini.js" import { GoogleInteractions } from "../protocols/google-interactions.js" import { GoogleImages } from "../protocols/google-images.js" @@ -24,7 +23,7 @@ export const id = ProviderID.make("google") export const routes = [Gemini.route, GoogleInteractions.route] -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: Gemini.ProviderOptionsInput & GoogleInteractions.ProviderOptionsInput diff --git a/packages/ai/src/providers/groq.ts b/packages/ai/src/providers/groq.ts index 25106e44aeff..c77695138ee7 100644 --- a/packages/ai/src/providers/groq.ts +++ b/packages/ai/src/providers/groq.ts @@ -3,10 +3,10 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { ProviderShared } from "../protocols/shared.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Protocol } from "../route/protocol.js" -import { ProviderID, type ModelID, type LLMRequest } from "../schema/index.js" +import { ProviderID, type ModelID, type LLMRequest, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" @@ -21,7 +21,7 @@ export type ProviderOptions = Pick & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: ProviderOptions @@ -83,8 +83,8 @@ export const configure = (input: Config = {}) => { maxTokensField: "max_completion_tokens", reasoningField: "reasoning", requireReasoning: false, - supportsStrictMode: false, }, + capabilities: { tools: { strict: false } }, }), configure, } diff --git a/packages/ai/src/providers/meta.ts b/packages/ai/src/providers/meta.ts index 6260d781ea9b..7100017c232f 100644 --- a/packages/ai/src/providers/meta.ts +++ b/packages/ai/src/providers/meta.ts @@ -5,10 +5,10 @@ import { MetaResponses } from "../protocols/meta-responses.js" import { MetaMessages } from "../protocols/meta-messages.js" import { MetaImages } from "../protocols/meta-images.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" -import { ProviderID, ToolDefinition, type ModelID, type OpenString } from "../schema/index.js" +import { ProviderID, ToolDefinition, type ModelID, type OpenString, type RequestOptions } from "../schema/index.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" @@ -75,7 +75,7 @@ export const imageGeneration = (options: ImageGenerationOptions = {}) => }, }) -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: ProviderOptionsInput @@ -95,7 +95,7 @@ const responsesRoute = Route.make({ endpoint: Endpoint.path("/responses", { baseURL }), // Meta Responses does not support WebSocket upgrades; always use HTTP/SSE. transport: MetaResponses.httpTransport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) const chatRoute = Route.make({ @@ -114,7 +114,7 @@ const messagesRoute = Route.make({ protocol: MetaMessages.protocol, endpoint: Endpoint.path("/messages", { baseURL }), framing: AnthropicMessages.framing, - defaults: { providerOptions: { thinking: { type: "adaptive", display: "omitted" } } }, + options: { providerOptions: { thinking: { type: "adaptive", display: "omitted" } } }, }) export const routes = [responsesRoute, chatRoute, messagesRoute] @@ -129,7 +129,8 @@ export const configure = (input: Config = {}) => { const chat = (modelID: string | ModelID) => configuredChat.model({ id: modelID, - compatibility: { maxTokensField: "max_completion_tokens", supportsPromptCacheKey: true }, + compatibility: { maxTokensField: "max_completion_tokens" }, + capabilities: { promptCacheKey: true }, }) const messages = (modelID: string | ModelID) => configuredMessages.model({ diff --git a/packages/ai/src/providers/minimax.ts b/packages/ai/src/providers/minimax.ts index 406ff50ccca7..18f515194a3b 100644 --- a/packages/ai/src/providers/minimax.ts +++ b/packages/ai/src/providers/minimax.ts @@ -6,12 +6,18 @@ import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponses } from "../protocols/open-responses.js" import { ProviderShared } from "../protocols/shared.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" import { MediaRoute } from "../route/media.js" import { Protocol } from "../route/protocol.js" -import { ProviderID, type LLMRequest, type ModelID, type ProviderOptions } from "../schema/index.js" +import { + ProviderID, + type LLMRequest, + type ModelID, + type ProviderOptions, + type RequestOptions, +} from "../schema/index.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("minimax") @@ -36,7 +42,7 @@ export type ResponsesOptionsInput = { export type ProviderOptionsInput = MessagesOptionsInput | ChatOptionsInput | ResponsesOptionsInput -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { /** Overrides the selected API's base URL, including its version prefix. */ readonly baseURL?: string @@ -119,7 +125,7 @@ export const configure = (input: Config = {}) => { const chat = (modelID: string | ModelID) => chatRoute.with(defaults).model({ id: modelID, - compatibility: { supportsStrictMode: false }, + capabilities: { tools: { strict: false } }, }) const responses = (modelID: string | ModelID) => responsesRoute.with(defaults).model({ id: modelID }) diff --git a/packages/ai/src/providers/mistral.ts b/packages/ai/src/providers/mistral.ts index 87e86edbbb89..aeb9776c7751 100644 --- a/packages/ai/src/providers/mistral.ts +++ b/packages/ai/src/providers/mistral.ts @@ -1,15 +1,14 @@ import type { ProviderPackage } from "../provider-package.js" import { MistralChat } from "../protocols/mistral-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import type { RouteDefaultsInput } from "../route/client.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("mistral") export type ProviderOptions = MistralChat.ProviderOptionsInput -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: ProviderOptions diff --git a/packages/ai/src/providers/moonshot.ts b/packages/ai/src/providers/moonshot.ts index 25dbb504c4c9..8f09f2601a80 100644 --- a/packages/ai/src/providers/moonshot.ts +++ b/packages/ai/src/providers/moonshot.ts @@ -5,11 +5,11 @@ import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponses } from "../protocols/open-responses.js" import { ProviderShared } from "../protocols/shared.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" import { Protocol } from "../route/protocol.js" -import { ProviderID, type LLMRequest, type ModelID } from "../schema/index.js" +import { ProviderID, type LLMRequest, type ModelID, type RequestOptions } from "../schema/index.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("moonshotai") @@ -36,7 +36,7 @@ export type ResponsesOptionsInput = { readonly safetyIdentifier?: string } -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { /** Overrides the selected API's base URL, including its version prefix. */ readonly baseURL?: string @@ -106,11 +106,10 @@ export const configure = (input: Config = {}) => { id: modelID, compatibility: { maxTokensField: "max_tokens", - supportsStrictMode: false, - supportsPromptCacheKey: true, sanitizer: "moonshot", reasoningField: "reasoning_content", }, + capabilities: { tools: { strict: false }, promptCacheKey: true }, }) const messages = (modelID: string | ModelID) => messagesRoute.with(defaults).model({ diff --git a/packages/ai/src/providers/openai-compatible-responses.ts b/packages/ai/src/providers/openai-compatible-responses.ts index 652e0f1e595a..72c224865187 100644 --- a/packages/ai/src/providers/openai-compatible-responses.ts +++ b/packages/ai/src/providers/openai-compatible-responses.ts @@ -1,8 +1,7 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAICompatibleResponses } from "../protocols/openai-compatible-responses.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" -import type { RouteDefaultsInput } from "../route/client.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" import { toConfig } from "./settings.js" @@ -10,7 +9,7 @@ export type { OpenResponsesOptionsInput, OpenResponsesProviderOptionsInput } fro export const id = ProviderID.make("openai-compatible") -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & ProviderAuthOption<"optional"> & { readonly provider?: string readonly baseURL: string diff --git a/packages/ai/src/providers/openai-compatible.ts b/packages/ai/src/providers/openai-compatible.ts index d3203c0500b0..40902ca4212c 100644 --- a/packages/ai/src/providers/openai-compatible.ts +++ b/packages/ai/src/providers/openai-compatible.ts @@ -1,8 +1,13 @@ -import { mergeProviderOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { + mergeProviderOptions, + ProviderID, + type ModelID, + type ProviderOptions, + type RequestOptions, +} from "../schema/index.js" import { OpenAICompatibleChat } from "../protocols/openai-compatible-chat.js" import { OpenAIImages } from "../protocols/openai-images.js" import { MediaRoute } from "../route/media.js" -import type { RouteDefaultsInput } from "../route/client.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" import type { ProviderPackage } from "../provider-package.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" @@ -10,7 +15,7 @@ import { toConfig } from "./settings.js" export const id = ProviderID.make("openai-compatible") -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly provider?: string readonly baseURL: string diff --git a/packages/ai/src/providers/openai.ts b/packages/ai/src/providers/openai.ts index d52f9b2042ff..ed23c02a7363 100644 --- a/packages/ai/src/providers/openai.ts +++ b/packages/ai/src/providers/openai.ts @@ -1,8 +1,15 @@ import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" -import type { Route, RouteDefaultsInput, CompactionOperations } from "../route/client.js" +import type { Route, CompactionOperations } from "../route/client.js" import { MediaRoute } from "../route/media.js" import type { ProviderPackage } from "../provider-package.js" -import { ProviderID, ToolDefinition, type ModelID, type OpenString, type ProviderOptions } from "../schema/index.js" +import { + ProviderID, + ToolDefinition, + type ModelID, + type OpenString, + type ProviderOptions, + type RequestOptions, +} from "../schema/index.js" import * as OpenAIChat from "../protocols/openai-chat.js" import * as OpenAIResponses from "../protocols/openai-responses.js" import { withOpenAIOptions, type OpenAIProviderOptionsInput } from "./openai-options.js" @@ -24,7 +31,7 @@ export const routes = [OpenAIResponses.route, OpenAIChat.route] // This provider facade wraps the lower-level Responses and Chat model factories // with OpenAI-specific conveniences: typed options, API-key sugar, env fallback, // and default option normalization. -export type Config = RouteDefaultsInput & +export type Config = RequestOptions & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly queryParams?: Record @@ -98,7 +105,7 @@ export const configure = (input: Config = {}) => { const chat = (id: string | ModelID) => chatRoute.with(withOpenAIOptions(id, modelDefaults)).model({ id, - compatibility: { supportsPromptCacheKey: true }, + capabilities: { promptCacheKey: true }, }) const deployment = MediaRoute.deployment(input, auth(input)) const media = { diff --git a/packages/ai/src/providers/openrouter.ts b/packages/ai/src/providers/openrouter.ts index 0ba083118a84..8860216cca3f 100644 --- a/packages/ai/src/providers/openrouter.ts +++ b/packages/ai/src/providers/openrouter.ts @@ -1,9 +1,15 @@ import { Effect, Schema } from "effect" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Protocol } from "../route/protocol.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { ProviderID, type ModelID, type OpenString, type ProviderOptions } from "../schema/index.js" +import { + ProviderID, + type ModelID, + type OpenString, + type ProviderOptions, + type RequestOptions, +} from "../schema/index.js" import type { ProviderPackage } from "../provider-package.js" import { SystemOne } from "../protocols/system-one.js" import { OpenAIImages, type OpenAIImageSizing } from "../protocols/openai-images.js" @@ -87,7 +93,7 @@ export interface OpenRouterDecisionOptions { readonly user?: string } -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenRouterProviderOptionsInput | OpenRouterResponsesProviderOptionsInput @@ -147,7 +153,7 @@ export const protocol = Protocol.make({ reasoning_details: reasoningDetails, } }, - }).pipe(Effect.map((body) => bodyOptions(body, request.providerOptions, request.generation?.maxTokens))), + }).pipe(Effect.map((body) => bodyOptions(body, request.providerOptions, request.maxTokens))), }, stream: OpenAIChat.protocol.stream, }) @@ -238,7 +244,7 @@ const responsesRoute = Route.make({ protocol: responsesProtocol, endpoint: Endpoint.path("/responses", { baseURL }), transport: HttpTransport.sseJson.with(), - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) export const routes = [route, responsesRoute] @@ -272,7 +278,7 @@ export const configure = (input: Config = {}) => { providerOptions, }) const chat = (modelID: string | ModelID) => - chatRoute.model({ id: modelID, compatibility: { supportsPromptCacheKey: true } }) + chatRoute.model({ id: modelID, capabilities: { promptCacheKey: true } }) return { id, model: chat, diff --git a/packages/ai/src/providers/settings.ts b/packages/ai/src/providers/settings.ts index 6161b9e8b884..15926a76ffd2 100644 --- a/packages/ai/src/providers/settings.ts +++ b/packages/ai/src/providers/settings.ts @@ -31,7 +31,7 @@ export function toConfig({ apiKey, baseURL, body, headers, ...providerOptions }: type BearerInput = ProviderAuthOption<"optional"> & { readonly baseURL?: string } /** - * Turns provider config into route defaults with `Authorization: Bearer` auth. The endpoint falls back to + * Turns provider config into route options with `Authorization: Bearer` auth. The endpoint falls back to * `baseURL` when given, otherwise it is left to the route. */ export function bearerRouteDefaults( diff --git a/packages/ai/src/providers/togetherai.ts b/packages/ai/src/providers/togetherai.ts index c6fc26511226..a8857bb6f852 100644 --- a/packages/ai/src/providers/togetherai.ts +++ b/packages/ai/src/providers/togetherai.ts @@ -1,16 +1,16 @@ import type { ProviderPackage } from "../provider-package.js" import { OpenAIChat } from "../protocols/openai-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenAIProviderOptionsInput } from "./openai-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("togetherai") const baseURL = "https://api.together.xyz/v1" -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: OpenAIProviderOptionsInput @@ -40,7 +40,8 @@ export const configure = (input: Config = {}) => { model: (modelID: string | ModelID) => configured.model({ id: modelID, - compatibility: { maxTokensField: "max_tokens", supportsStrictMode: false }, + compatibility: { maxTokensField: "max_tokens" }, + capabilities: { tools: { strict: false } }, }), configure, } diff --git a/packages/ai/src/providers/venice.ts b/packages/ai/src/providers/venice.ts index 7ce5555e54ef..e1fac0d3c469 100644 --- a/packages/ai/src/providers/venice.ts +++ b/packages/ai/src/providers/venice.ts @@ -3,14 +3,14 @@ import { VeniceChat } from "../protocols/venice-chat.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponses } from "../protocols/open-responses.js" import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" export const id = ProviderID.make("venice") export type ChatOptionsInput = VeniceChat.OptionsInput -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly queryParams?: Readonly> @@ -40,7 +40,7 @@ const responsesRoute = Route.make({ protocol: OpenResponses.protocol, endpoint: Endpoint.path("/responses", { baseURL }), transport: OpenResponses.httpTransport, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) export const routes = [route, responsesRoute] @@ -52,7 +52,11 @@ export const configure = (input: Config = {}) => { auth: AuthOptions.bearer(input, "VENICE_API_KEY"), } const chat = (modelID: string | ModelID) => - route.with(options).model({ id: modelID, compatibility: VeniceChat.compatibility }) + route.with(options).model({ + id: modelID, + compatibility: VeniceChat.compatibility, + capabilities: VeniceChat.capabilities, + }) const responses = (modelID: string | ModelID) => responsesRoute.with(options).model({ id: modelID }) return { id, model: chat, chat, responses, configure } diff --git a/packages/ai/src/providers/vercel-ai-gateway.ts b/packages/ai/src/providers/vercel-ai-gateway.ts index 7bf81949776a..ed318201709a 100644 --- a/packages/ai/src/providers/vercel-ai-gateway.ts +++ b/packages/ai/src/providers/vercel-ai-gateway.ts @@ -9,7 +9,7 @@ import { ProviderShared } from "../protocols/shared.js" import { gatewayProtocol } from "../protocols/utils/gateway-protocol.js" import type { ProviderPackage } from "../provider-package.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" import { MediaRoute } from "../route/media.js" @@ -21,6 +21,7 @@ import { ProviderMetadata, ReasoningEffort, type ProviderOptions, + type RequestOptions, } from "../schema/index.js" import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js" import { bearerRouteDefaults, toConfig } from "./settings.js" @@ -100,7 +101,7 @@ export type ProviderOptionsInput = OpenResponsesProviderOptionsInput & readonly cacheAnchorItems?: number } -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: ProviderOptionsInput @@ -174,7 +175,7 @@ const route = (input: { readonly api: "messages" | "responses" | "chat" readonly path: string readonly framing: Framing.Definition - readonly defaults?: RouteDefaultsInput + readonly options?: RequestOptions }) => Route.make({ id: input.id, @@ -185,7 +186,7 @@ const route = (input: { framing: input.framing, headers: ({ request }): Record => request.promptCacheKey ? { "x-session-affinity": request.promptCacheKey } : {}, - defaults: input.defaults, + options: input.options, }) const messagesRoute = route({ @@ -194,7 +195,7 @@ const messagesRoute = route({ api: "messages", path: "/messages", framing: AnthropicMessages.framing, - defaults: { headers: { "anthropic-version": "2023-06-01" } }, + options: { headers: { "anthropic-version": "2023-06-01" } }, }) const responsesRoute = route({ id: "vercel-ai-gateway-responses", @@ -202,7 +203,7 @@ const responsesRoute = route({ api: "responses", path: "/responses", framing: Framing.sse, - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) const chatRoute = route({ id: "vercel-ai-gateway-chat", diff --git a/packages/ai/src/providers/xai.ts b/packages/ai/src/providers/xai.ts index accba2ae901c..ef2ce340b960 100644 --- a/packages/ai/src/providers/xai.ts +++ b/packages/ai/src/providers/xai.ts @@ -1,8 +1,8 @@ import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import { OpenAIChat } from "../protocols/openai-chat.js" import { OpenResponsesChannel } from "../protocols/open-responses-channel.js" import { XAIResponses } from "../protocols/xai-responses.js" @@ -18,7 +18,7 @@ const baseURL = "https://api.x.ai/v1" export type XAIProviderOptionsInput = OpenAIOptionsInput & XAIResponses.OptionsInput & { readonly contextManagement?: never } -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: XAIProviderOptionsInput @@ -51,7 +51,7 @@ const responsesRoute = Route.make({ // rejects `instructions` next to `previous_response_id` and keeps the instructions of the response it continues. continuation: ({ instructions: _instructions, ...request }) => (request.store === false ? undefined : request), }), - defaults: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, + options: { providerOptions: { store: false, include: ["reasoning.encrypted_content"] } }, }) const chatRoute = Route.make({ diff --git a/packages/ai/src/providers/zai-coding-plan.ts b/packages/ai/src/providers/zai-coding-plan.ts index f4e28b2f476f..f2a9c3696fc3 100644 --- a/packages/ai/src/providers/zai-coding-plan.ts +++ b/packages/ai/src/providers/zai-coding-plan.ts @@ -5,10 +5,10 @@ import { OpenResponses } from "../protocols/open-responses.js" import { ZAIChat } from "../protocols/zai-chat.js" import { ZAIMessages } from "../protocols/zai-messages.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { Framing } from "../route/framing.js" -import { ProviderID, type ModelID } from "../schema/index.js" +import { ProviderID, type ModelID, type RequestOptions } from "../schema/index.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("zai-coding-plan") @@ -17,7 +17,7 @@ export type ChatOptionsInput = ZAIChat.OptionsInput export type MessagesOptionsInput = ZAIMessages.OptionsInput export type ResponsesOptionsInput = { readonly reasoningEffort?: ZAIChat.ReasoningEffort } -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { /** Overrides the selected API's complete base URL. */ readonly baseURL?: string @@ -61,7 +61,11 @@ export const routes = [chatRoute, messagesRoute, responsesRoute] export const configure = (input: Config = {}) => { const defaults = bearerRouteDefaults(input, "ZAI_API_KEY") const chat = (modelID: string | ModelID) => - chatRoute.with(defaults).model({ id: modelID, compatibility: ZAIChat.compatibility }) + chatRoute.with(defaults).model({ + id: modelID, + compatibility: ZAIChat.compatibility, + capabilities: ZAIChat.capabilities, + }) const messages = (modelID: string | ModelID) => messagesRoute .with(defaults) diff --git a/packages/ai/src/providers/zai.ts b/packages/ai/src/providers/zai.ts index 6dd41a3a61fe..133f71ef24fb 100644 --- a/packages/ai/src/providers/zai.ts +++ b/packages/ai/src/providers/zai.ts @@ -3,17 +3,17 @@ import { ZAIChat } from "../protocols/zai-chat.js" import { ZAIImages } from "../protocols/zai-images.js" import { OpenAIChat } from "../protocols/openai-chat.js" import type { ProviderAuthOption } from "../route/auth-options.js" -import { Route, type RouteDefaultsInput } from "../route/client.js" +import { Route } from "../route/client.js" import { Endpoint } from "../route/endpoint.js" import { MediaRoute } from "../route/media.js" -import { ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js" +import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js" import { bearerRouteDefaults, toConfig } from "./settings.js" export const id = ProviderID.make("zai") export type ChatOptionsInput = ZAIChat.OptionsInput -export type Config = Omit & +export type Config = Omit & ProviderAuthOption<"optional"> & { readonly baseURL?: string readonly providerOptions?: ChatOptionsInput @@ -41,7 +41,11 @@ export const routes = [chatRoute] export const configure = (input: Config = {}) => { const defaults = bearerRouteDefaults(input, "ZAI_API_KEY") const chat = (modelID: string | ModelID) => - chatRoute.with(defaults).model({ id: modelID, compatibility: ZAIChat.compatibility }) + chatRoute.with(defaults).model({ + id: modelID, + compatibility: ZAIChat.compatibility, + capabilities: ZAIChat.capabilities, + }) const media = MediaRoute.deployment(input, defaults.auth) const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => ZAIImages.model({ ...media, id: modelID, providerOptions }) diff --git a/packages/ai/src/public.ts b/packages/ai/src/public.ts index a7c9e6f48767..1eaa9d3fdfb4 100644 --- a/packages/ai/src/public.ts +++ b/packages/ai/src/public.ts @@ -12,8 +12,7 @@ export { ProviderMetadata, HttpTimeout, RequestEncoding, - GenerationOptions, - LanguageModelDefaults, + GENERATION_KEYS, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, @@ -93,8 +92,8 @@ export type { BaseRequest, ContentPartInput, GenerationOptionsFields, - GenerationOptionsInput, HttpOptions, + RequestOptions, LanguageModelInput, LanguageModelProviderOptions, LLMRequest, diff --git a/packages/ai/src/route/client.ts b/packages/ai/src/route/client.ts index d4ba775d19db..9781477d8f48 100644 --- a/packages/ai/src/route/client.ts +++ b/packages/ai/src/route/client.ts @@ -19,7 +19,6 @@ import { CompactionResponse, CompactionCheckpointResponse, AIErrorReason, - GenerationOptions, LLMResponse, ResponseFold, LanguageModel, @@ -31,10 +30,11 @@ import { ToolChoice, ToolEntry, type LLMRequest, - mergeGenerationOptions, + mergeGeneration, + mergeRequestOptions, mergeProviderOptions, mergeTransport, - type TransportOptions, + type RequestOptions, withPartial, } from "../schema/index.js" @@ -61,7 +61,8 @@ export interface Route< /** Deployment headers resolved once for every operation, before transport authentication. */ readonly headers?: (input: { readonly request: LLMRequest }) => Record readonly transport: Transport - readonly defaults: RouteDefaults + /** Options every model built on this route starts from. */ + readonly options?: RequestOptions readonly body: RouteBody readonly supportsEffortUpdates?: (request: LLMRequest) => boolean readonly sanitizer?: LanguageModelSanitizerCompatibility @@ -104,17 +105,7 @@ export type RouteLanguageModelInput = Omit -export interface RouteDefaults extends TransportOptions { - readonly generation?: GenerationOptions - readonly providerOptions?: ProviderOptions -} - -export interface RouteDefaultsInput extends TransportOptions { - readonly generation?: GenerationOptions.Input - readonly providerOptions?: ProviderOptions -} - -export interface RoutePatch extends RouteDefaultsInput { +export interface RoutePatch extends RequestOptions { readonly compact?: CompactionOperations readonly id?: string readonly provider?: string | ProviderID @@ -144,14 +135,6 @@ const makeRouteLanguageModel = ({ - ...base, - ...patch, - ...mergeTransport(base, patch), - generation: mergeGenerationOptions(base?.generation, patch.generation), - providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions), -}) - export interface Interface { readonly compact: CompactMethod readonly stream: StreamMethod @@ -262,18 +245,12 @@ export type Service = LLMClientService const resolveRequestOptions = (request: LLMRequest): LLMRequest => { const messages = normalizeToolHistory(request.messages) const normalized = messages === request.messages ? request : { ...request, messages } - const routeDefaults = normalized.model.route.defaults - const modelDefaults = normalized.model.defaults - const generation = mergeGenerationOptions(routeDefaults.generation, modelDefaults?.generation, normalized.generation) + const options = normalized.model.options return { ...normalized, - generation: generation ?? new GenerationOptions({}), - providerOptions: mergeProviderOptions( - routeDefaults.providerOptions, - modelDefaults?.providerOptions, - normalized.providerOptions, - ), - ...mergeTransport(routeDefaults, modelDefaults, normalized), + ...mergeGeneration(options, normalized), + providerOptions: mergeProviderOptions(options?.providerOptions, normalized.providerOptions), + ...mergeTransport(options, normalized), } } @@ -295,8 +272,8 @@ export interface MakeInput { readonly framing: Framing.Definition /** Static / per-request headers added before `auth` runs. */ readonly headers?: (input: { readonly request: LLMRequest }) => Record - /** Route/request defaults used when compiling requests for this route. */ - readonly defaults?: RouteDefaultsInput + /** Options every model built on this route starts from. */ + readonly options?: RequestOptions } export interface MakeTransportInput { @@ -317,8 +294,8 @@ export interface MakeTransportInput { readonly headers?: (input: { readonly request: LLMRequest }) => Record /** Runnable transport route. */ readonly transport: Transport - /** Route/request defaults used when compiling requests for this route. */ - readonly defaults?: RouteDefaultsInput + /** Options every model built on this route starts from. */ + readonly options?: RequestOptions } const streamError = (route: string, message: string, cause: Cause.Cause) => { @@ -383,9 +360,7 @@ function makeFromTransport( ), ) - type BuiltRouteInput = Omit, "defaults"> & { - readonly defaults?: RouteDefaults - } + type BuiltRouteInput = MakeTransportInput const build = (routeInput: BuiltRouteInput): Route => { const route: Route = { @@ -398,12 +373,12 @@ function makeFromTransport( auth: routeInput.auth ?? Auth.none, headers: routeInput.headers, transport: routeInput.transport, - defaults: routeInput.defaults ?? {}, + options: routeInput.options, body: protocol.body, supportsEffortUpdates: protocol.supportsEffortUpdates, sanitizer: protocol.sanitizer, with: (patch: RoutePatch) => { - const { compact, id, provider, providerMetadataKey, auth, transport, endpoint, ...defaults } = patch + const { compact, id, provider, providerMetadataKey, auth, transport, endpoint, ...options } = patch return build({ ...routeInput, compact: "compact" in patch ? compact : routeInput.compact, @@ -415,7 +390,7 @@ function makeFromTransport( auth: auth ?? routeInput.auth, endpoint: endpoint ? Endpoint.merge(routeInput.endpoint, endpoint) : routeInput.endpoint, transport: (transport as Transport | undefined) ?? routeInput.transport, - defaults: mergeRouteDefaults(route.defaults, defaults), + options: mergeRequestOptions(route.options, options), }) }, model: (input: RouteMappedLanguageModelInput) => @@ -515,7 +490,7 @@ function makeFromTransport( return route } - return build({ ...input, defaults: mergeRouteDefaults(undefined, input.defaults ?? {}) }) + return build({ ...input, options: mergeRequestOptions(input.options) }) } export function make( @@ -560,7 +535,7 @@ export function make( auth: input.auth, headers: input.headers, transport: HttpTransport.httpJson({ framing: input.framing }), - defaults: input.defaults, + options: input.options, }) } @@ -585,7 +560,6 @@ const restoreClasses = (request: LLMRequest): LLMRequest => ({ messages: request.messages.map(Message.make), tools: request.tools.map(ToolEntry.make), toolChoice: request.toolChoice === undefined ? undefined : ToolChoice.make(request.toolChoice), - generation: request.generation === undefined ? undefined : GenerationOptions.make(request.generation), }) const compile = Effect.fn("LLM.compile")(function* (request: LLMRequest, options?: StreamOptions) { diff --git a/packages/ai/src/route/index.ts b/packages/ai/src/route/index.ts index 9ff082b0c389..f820a788362e 100644 --- a/packages/ai/src/route/index.ts +++ b/packages/ai/src/route/index.ts @@ -2,8 +2,6 @@ export { Route, LLMClient } from "./client.js" export type { RouteLanguageModelInput, RouteRoutedLanguageModelInput, - RouteDefaults, - RouteDefaultsInput, AnyRoute, LLMClientService, StreamOptions, diff --git a/packages/ai/src/route/transport/websocket.ts b/packages/ai/src/route/transport/websocket.ts index 4e25c81ee997..2470a61b3ec4 100644 --- a/packages/ai/src/route/transport/websocket.ts +++ b/packages/ai/src/route/transport/websocket.ts @@ -74,6 +74,11 @@ const eventMessage = (event: Socket.WebSocketEvent) => { return event.type ?? "error" } +const systemCode = (cause: unknown) => + typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" + ? cause.code + : undefined + const binaryMessage = (data: unknown) => { if (data instanceof Uint8Array) return data if (data instanceof ArrayBuffer) return new Uint8Array(data) @@ -115,12 +120,15 @@ const waitOpen = (ws: Socket.WebSocketLike, input: WebSocketRequest) => { } const onError = (event: Socket.WebSocketEvent) => { cleanup() + const cause = "error" in event ? (event.error ?? event) : event resume( Effect.fail( transportError(`Failed to open WebSocket: ${eventMessage(event)}`, { - cause: "error" in event ? (event.error ?? event) : event, + cause, url: input.url, operation: "request", + // Bun puts the system code (ENOTFOUND, ECONNREFUSED) on the event's error; lift it like HTTP failures do. + code: systemCode(cause), phase: "connect", delivery: "not-sent", }), diff --git a/packages/ai/src/schema/messages.ts b/packages/ai/src/schema/messages.ts index f328006564a5..30dc991403fe 100644 --- a/packages/ai/src/schema/messages.ts +++ b/packages/ai/src/schema/messages.ts @@ -5,12 +5,12 @@ import { type BaseRequest, CacheHint, type CachePolicy, - type GenerationOptions, JsonSchema, type LanguageModel, type LanguageModelProviderOptions, ProviderMetadata, ReasoningEffort, + type GenerationOptionsFields, } from "./options.js" import { ProviderID } from "./ids.js" import { Media } from "../media.js" @@ -487,13 +487,13 @@ export namespace ToolChoice { * `{ ...request, messages: [...request.messages, next] }`, or pass the edited object back to `ai.request`. */ export interface LLMRequest - extends BaseRequest> { + extends BaseRequest>, + GenerationOptionsFields { readonly id?: string readonly system: ReadonlyArray readonly messages: ReadonlyArray readonly tools: ReadonlyArray readonly toolChoice?: ToolChoice - readonly generation?: GenerationOptions readonly cache?: CachePolicy /** Stable cache affinity for protocols that support provider-managed prompt caching. */ readonly promptCacheKey?: string diff --git a/packages/ai/src/schema/options.ts b/packages/ai/src/schema/options.ts index ed50b5ad72bc..f9d6bff13eff 100644 --- a/packages/ai/src/schema/options.ts +++ b/packages/ai/src/schema/options.ts @@ -131,25 +131,8 @@ export const mergeTransport = (...items: ReadonlyArray("LLM.GenerationOptions")({ - maxTokens: Schema.optional(Schema.Number), - temperature: Schema.optional(Schema.Number), - topP: Schema.optional(Schema.Number), - topK: Schema.optional(Schema.Number), - frequencyPenalty: Schema.optional(Schema.Number), - presencePenalty: Schema.optional(Schema.Number), - seed: Schema.optional(Schema.Number), - stop: Schema.optional(Schema.Array(Schema.String)), -}) {} - -export namespace GenerationOptions { - export type Input = GenerationOptions | ConstructorParameters[0] - - /** Normalize generation option input into the canonical `GenerationOptions` class. */ - export const make = (input: Input = {}) => (input instanceof GenerationOptions ? input : new GenerationOptions(input)) -} - -export type GenerationOptionsFields = { +/** Portable sampling knobs, set at the top level of text requests, model defaults and route defaults. */ +export interface GenerationOptionsFields { readonly maxTokens?: number readonly temperature?: number readonly topP?: number @@ -160,44 +143,39 @@ export type GenerationOptionsFields = { readonly stop?: ReadonlyArray } -export type GenerationOptionsInput = GenerationOptions | GenerationOptionsFields - -const latestGeneration = ( - items: ReadonlyArray, - key: Key, -) => items.findLast((item) => item?.[key] !== undefined)?.[key] - -export const mergeGenerationOptions = (...items: ReadonlyArray) => { - const result = new GenerationOptions({ - maxTokens: latestGeneration(items, "maxTokens"), - temperature: latestGeneration(items, "temperature"), - topP: latestGeneration(items, "topP"), - topK: latestGeneration(items, "topK"), - frequencyPenalty: latestGeneration(items, "frequencyPenalty"), - presencePenalty: latestGeneration(items, "presencePenalty"), - seed: latestGeneration(items, "seed"), - stop: latestGeneration(items, "stop"), - }) - return Object.values(result).some((value) => value !== undefined) ? result : undefined -} - -/** Request defaults a selected model applies under each request. */ -export interface LanguageModelDefaults extends TransportOptions { - readonly generation?: GenerationOptions +/** The keys of `GenerationOptionsFields`, for splitting a flat record into portable knobs and provider options. */ +export const GENERATION_KEYS: ReadonlySet = new Set([ + "maxTokens", + "temperature", + "topP", + "topK", + "frequencyPenalty", + "presencePenalty", + "seed", + "stop", +] satisfies ReadonlyArray) + +/** Pick the generation knobs out of each item; later items win per knob. */ +export const mergeGeneration = (...items: ReadonlyArray) => + Object.fromEntries( + [...GENERATION_KEYS].map((key) => [key, last(items.map((item) => item?.[key as keyof GenerationOptionsFields]))]), + ) as GenerationOptionsFields + +/** Request options a model applies under each request: the same keys as a request, and the request wins. */ +export interface RequestOptions extends TransportOptions, GenerationOptionsFields { readonly providerOptions?: ProviderOptions } -export namespace LanguageModelDefaults { - export interface Input extends TransportOptions { - readonly generation?: GenerationOptions.Input - readonly providerOptions?: ProviderOptions - } - - /** Normalize selected-model request defaults without applying precedence. */ - export const make = (input: Input): LanguageModelDefaults => ({ - ...input, - generation: input.generation === undefined ? undefined : GenerationOptions.make(input.generation), - }) +/** Merge model options; later items win per key. Empty results are `undefined`. */ +export const mergeRequestOptions = ( + ...items: ReadonlyArray +): RequestOptions | undefined => { + const merged = Object.entries({ + ...mergeTransport(...items), + ...mergeGeneration(...items), + providerOptions: mergeProviderOptions(...items.map((item) => item?.providerOptions)), + }).filter(([, value]) => value !== undefined) + return merged.length === 0 ? undefined : (Object.fromEntries(merged) as RequestOptions) } /** Provider-defined string enum: known values for autocomplete, any string accepted. */ @@ -232,22 +210,12 @@ export class LanguageModelCompatibility extends Schema.Class + readonly search?: boolean + /** Input formats accepted by custom (free-form) tools. */ + readonly freeform?: ReadonlyArray<"text" | "lark" | "regex"> + /** Accepts a changed tool list mid-conversation. */ + readonly updates?: boolean + } + readonly reasoning?: { + readonly supported?: boolean + readonly default?: + | { readonly type: "toggle"; readonly value: boolean } + | { readonly type: "effort"; readonly value: ReasoningEffort } + | { readonly type: "budget"; readonly value: number } + readonly toggle?: boolean + readonly effort?: ReadonlyArray + readonly budget?: { readonly min?: number; readonly max?: number } + /** Accepts per-message effort updates. Detected from the model ID when unset. */ + readonly updates?: boolean + } + readonly cache?: + | false + | { + readonly implicit?: true | { readonly ttl?: ReadonlyArray; readonly minTokens?: number } + readonly explicit?: + | true + | { + readonly ttl?: ReadonlyArray + readonly maxBreakpoints?: number + readonly targets?: ReadonlyArray<"tools" | "system" | "messages"> + readonly minTokens?: number + } + } + readonly structuredOutput?: boolean + readonly temperature?: boolean + readonly topP?: boolean + readonly topK?: boolean + /** Accepts mid-conversation system messages. Anthropic Messages detects it from the model ID when unset. */ + readonly systemUpdates?: boolean + /** Accepts `store`. OpenAI Chat detects it from the provider when unset. */ + readonly store?: boolean + /** Accepts `stream_options.include_usage`. OpenAI Chat defaults to true. */ + readonly streamUsage?: boolean + // Accepts `prompt_cache_key` in the request body. Chat omits the key unless + // this is true; other protocols omit it only when this is false. + // Session-affinity headers still flow regardless. + readonly promptCacheKey?: boolean + readonly serviceTier?: ReadonlyArray> +} + export class LanguageModel< Options extends ProviderOptions = ProviderOptions, Compact extends CompactionOperations | undefined = CompactionOperations | undefined, @@ -266,14 +292,16 @@ export class LanguageModel< readonly id: ModelID readonly provider: ProviderID readonly route: AnyRoute - readonly defaults?: LanguageModelDefaults + readonly options?: RequestOptions + readonly capabilities?: Capabilities readonly compatibility?: LanguageModelCompatibility constructor(input: LanguageModel.ConstructorInput) { this.id = input.id this.provider = input.provider this.route = input.route - this.defaults = input.defaults + this.options = input.options + this.capabilities = input.capabilities this.compatibility = input.compatibility } @@ -285,7 +313,9 @@ export class LanguageModel< id: ModelID.make(input.id), provider: ProviderID.make(input.provider), route: input.route, - defaults: input.defaults === undefined ? undefined : LanguageModelDefaults.make(input.defaults), + // The route's options are a preset under the model's own. + options: mergeRequestOptions(input.route.options, input.options), + capabilities: input.capabilities, compatibility: input.compatibility === undefined ? undefined : LanguageModelCompatibility.make(input.compatibility), }) @@ -298,7 +328,8 @@ export class LanguageModel< id: model.id, provider: model.provider, route: model.route, - defaults: model.defaults, + options: model.options, + capabilities: model.capabilities, compatibility: model.compatibility, } } @@ -330,17 +361,17 @@ export namespace LanguageModel { readonly id: ModelID readonly provider: ProviderID readonly route: AnyRoute - readonly defaults?: LanguageModelDefaults + readonly options?: RequestOptions + readonly capabilities?: Capabilities readonly compatibility?: LanguageModelCompatibility } export type Input = Omit< ConstructorInput, - "id" | "provider" | "defaults" | "compatibility" + "id" | "provider" | "compatibility" > & { readonly id: string | ModelID readonly provider: string | ProviderID - readonly defaults?: LanguageModelDefaults.Input readonly compatibility?: LanguageModelCompatibility.Input } } diff --git a/packages/ai/test/auth-options.types.ts b/packages/ai/test/auth-options.types.ts index 7f96b998dfec..cc9cff72b474 100644 --- a/packages/ai/test/auth-options.types.ts +++ b/packages/ai/test/auth-options.types.ts @@ -83,7 +83,7 @@ OpenAI.configure({ baseURL: "https://gateway.example.com/v1", }).responses("gpt-4.1-mini") OpenAI.configure({ - generation: { maxTokens: 100 }, + maxTokens: 100, providerOptions: { store: false }, }).responses("gpt-4.1-mini") @@ -100,7 +100,7 @@ OpenAI.configure({ apiKey: 123 }) OpenAI.configure({ bogus: true }) // @ts-expect-error common generation options remain typed. -OpenAI.configure({ generation: { maxTokens: "many" } }) +OpenAI.configure({ maxTokens: "many" }) // @ts-expect-error provider-native options remain typed. OpenAI.configure({ providerOptions: { store: "false" } }) diff --git a/packages/ai/test/compile.test.ts b/packages/ai/test/compile.test.ts index 20a28e837d27..abad911f7c80 100644 --- a/packages/ai/test/compile.test.ts +++ b/packages/ai/test/compile.test.ts @@ -45,13 +45,18 @@ describe("request option precedence", () => { const route = OpenAIChat.route.with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test"), - generation: { maxTokens: 10, temperature: 1, stop: ["route"] }, + maxTokens: 10, + temperature: 1, + stop: ["route"], providerOptions: { store: false, reasoningEffort: "low" }, }) const model = route.model({ id: "gpt-4o-mini", - defaults: { - generation: { maxTokens: 20, temperature: 0.5, frequencyPenalty: 0.25, stop: ["model"] }, + options: { + maxTokens: 20, + temperature: 0.5, + frequencyPenalty: 0.25, + stop: ["model"], providerOptions: { reasoningEffort: "medium" }, }, }) @@ -59,7 +64,9 @@ describe("request option precedence", () => { ai.request({ model, prompt: "Say hello.", - generation: { maxTokens: 30, topP: 0.9, stop: ["request"] }, + maxTokens: 30, + topP: 0.9, + stop: ["request"], providerOptions: { store: true }, }), ) @@ -196,7 +203,7 @@ describe("request option precedence", () => { }) .model({ id: "gpt-4o-mini", - defaults: { + options: { headers: { "x-model": "model", "x-shared": "model" }, http: { body: { metadata: { model: true, shared: "model" }, value: "model" }, @@ -447,7 +454,7 @@ describe("request option precedence", () => { const model = route.model({ id: "claude-sonnet-4-5" }) const withoutMaxTokens = yield* compileRequest(ai.request({ model, prompt: "Say hello.", cache: "none" })) const withMaxTokens = yield* compileRequest( - ai.request({ model, prompt: "Say hello.", cache: "none", generation: { maxTokens: 8_000 } }), + ai.request({ model, prompt: "Say hello.", cache: "none", maxTokens: 8_000 }), ) expect(withoutMaxTokens.body.max_tokens).toBe(32_000) diff --git a/packages/ai/test/continuation-scenarios.ts b/packages/ai/test/continuation-scenarios.ts index 538cf09b3a5c..ef409d9858fc 100644 --- a/packages/ai/test/continuation-scenarios.ts +++ b/packages/ai/test/continuation-scenarios.ts @@ -109,6 +109,7 @@ export function continuationRequest(input: { providerOptions: features.has("encrypted-reasoning") ? { store: false, include: ["reasoning.encrypted_content"], reasoningSummary: "auto" } : undefined, - generation: { maxTokens: 80, temperature: 0 }, + maxTokens: 80, + temperature: 0, }) } diff --git a/packages/ai/test/effort-updates.test.ts b/packages/ai/test/effort-updates.test.ts index 468ed2ea5c9e..7dedf329e295 100644 --- a/packages/ai/test/effort-updates.test.ts +++ b/packages/ai/test/effort-updates.test.ts @@ -12,15 +12,15 @@ import { it, testEffect } from "./lib/effect.js" import { dynamicResponse } from "./lib/http.js" import { sseEvents } from "./lib/sse.js" -const anthropic = (id: string, compatibility?: { readonly supportsEffortUpdates?: boolean }) => +const anthropic = (id: string, updates?: boolean) => AnthropicMessages.route .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") }) - .model({ id, compatibility }) + .model({ id, capabilities: updates === undefined ? undefined : { reasoning: { updates } } }) -const openai = (id: string, compatibility?: { readonly supportsEffortUpdates?: boolean }) => +const openai = (id: string, updates?: boolean) => OpenAIResponses.route .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") }) - .model({ id, compatibility }) + .model({ id, capabilities: updates === undefined ? undefined : { reasoning: { updates } } }) const opus5 = anthropic("claude-opus-5") const astra = openai("gpt-6-astra") @@ -250,14 +250,14 @@ describe("Anthropic Messages effort updates", () => { Effect.gen(function* () { const enabled = yield* compileRequest( ai.request({ - model: anthropic("claude-sonnet-5", { supportsEffortUpdates: true }), + model: anthropic("claude-sonnet-5", true), messages: conversation, providerOptions: { effort: "low" }, }), ) const disabled = yield* compileRequest( ai.request({ - model: anthropic("claude-opus-5", { supportsEffortUpdates: false }), + model: anthropic("claude-opus-5", false), messages: conversation, providerOptions: { effort: "low" }, }), @@ -506,14 +506,14 @@ describe("OpenAI Responses effort updates", () => { Effect.gen(function* () { const enabled = yield* compileRequest( ai.request({ - model: openai("gpt-5.5", { supportsEffortUpdates: true }), + model: openai("gpt-5.5", true), messages: conversation, providerOptions: { reasoningEffort: "low" }, }), ) const disabled = yield* compileRequest( ai.request({ - model: openai("gpt-6-astra", { supportsEffortUpdates: false }), + model: openai("gpt-6-astra", false), messages: conversation, providerOptions: { reasoningEffort: "low" }, }), diff --git a/packages/ai/test/generate-object.test.ts b/packages/ai/test/generate-object.test.ts index 2910564b625f..440314757ad5 100644 --- a/packages/ai/test/generate-object.test.ts +++ b/packages/ai/test/generate-object.test.ts @@ -217,9 +217,7 @@ describe("schema on ai.stream and ai.loop", () => { ), ) - const error = yield* ai - .generate({ model, prompt: "Pick a city.", schema: City, generation: { maxTokens: 1 } }) - .pipe(Effect.flip) + const error = yield* ai.generate({ model, prompt: "Pick a city.", schema: City, maxTokens: 1 }).pipe(Effect.flip) expect(error.message).toContain("output hit the token limit") expect(error.message).not.toContain("schema decode failed") diff --git a/packages/ai/test/llm-option-types.types.ts b/packages/ai/test/llm-option-types.types.ts index 3322254095d5..5b044f2b5f4c 100644 --- a/packages/ai/test/llm-option-types.types.ts +++ b/packages/ai/test/llm-option-types.types.ts @@ -145,3 +145,9 @@ ai.request({ model, prompt: "Hello", http: { query: { trace: "1" }, body: { extr ai.request({ model, prompt: "Hello", http: { headers: { "x-trace": "1" } } }) // @ts-expect-error Timeouts moved out of `http`. ai.request({ model, prompt: "Hello", http: { headerTimeout: 1_000 } }) + +// Portable knobs sit at the top level; editing one is a flat spread. +const knobs = ai.request({ model, prompt: "Hello", maxTokens: 256, temperature: 0, stop: ["END"] }) +ai.generate({ ...knobs, maxTokens: 512 }) +// @ts-expect-error The nested `generation` object was removed. +ai.request({ model, prompt: "Hello", generation: { maxTokens: 256 } }) diff --git a/packages/ai/test/llm.test.ts b/packages/ai/test/llm.test.ts index 6633447de27e..510cce982464 100644 --- a/packages/ai/test/llm.test.ts +++ b/packages/ai/test/llm.test.ts @@ -1,11 +1,10 @@ import { describe, expect, test } from "bun:test" import { Effect, Schema, Stream } from "effect" -import { ai, CacheHint, LLMEvent, LLMResponse, ToolEntry, ToolNamespace } from "../src/effect.js" +import { ai, CacheHint, GENERATION_KEYS, LLMEvent, LLMResponse, ToolEntry, ToolNamespace } from "../src/effect.js" import { OpenAI } from "../src/providers.js" import * as OpenAIChat from "../src/protocols/openai-chat.js" import * as OpenAIResponses from "../src/protocols/openai-responses.js" import { - GenerationOptions, Message, LanguageModel, SystemMessage, @@ -82,7 +81,7 @@ describe("llm constructors", () => { expect(request.messages[0]).toBeInstanceOf(UserMessage) expect(request.system).toEqual([{ type: "text", text: "You are concise." }]) expect(request.messages[0]?.content).toEqual([{ type: "text", text: "Say hello." }]) - expect(request.generation).toBeUndefined() + expect(request.maxTokens).toBeUndefined() expect(request.tools).toEqual([]) }) @@ -94,13 +93,13 @@ describe("llm constructors", () => { }) const updated = { ...base, - generation: GenerationOptions.make({ maxTokens: 20 }), + maxTokens: 20, messages: [...base.messages, Message.assistant("Hi.")], } expect(updated.id).toBe("req_1") expect(updated.model).toBe(base.model) - expect(updated.generation).toEqual({ maxTokens: 20 }) + expect(updated.maxTokens).toBe(20) expect(updated.messages.map((message) => message.role)).toEqual(["user", "assistant"]) expect(ai.request(updated)).toEqual(updated) expect(ai.request(updated).messages[1]).toBe(updated.messages[1]) @@ -114,25 +113,40 @@ describe("llm constructors", () => { expect(prompted.messages.map((message) => message.role)).toEqual(["user", "assistant", "user"]) }) + test("lists the portable knobs", () => { + expect([...GENERATION_KEYS]).toEqual([ + "maxTokens", + "temperature", + "topP", + "topK", + "frequencyPenalty", + "presencePenalty", + "seed", + "stop", + ]) + }) + test("keeps request options separate from route defaults", () => { const request = ai.request({ model: LanguageModel.make({ id: "fake-model", provider: "fake", route: chatRoute.with({ - generation: { maxTokens: 100, temperature: 1 }, + maxTokens: 100, + temperature: 1, providerOptions: { store: false, metadata: { model: true } }, http: { body: { metadata: { model: true } }, headers: { "x-shared": "model" }, query: { model: "1" } }, }), }), prompt: "Say hello.", - generation: { temperature: 0 }, + temperature: 0, providerOptions: { store: true, metadata: { request: true } }, headers: { "x-shared": "request" }, http: { body: { metadata: { request: true } }, query: { request: "1" } }, }) - expect(request.generation).toEqual({ temperature: 0 }) + expect(request.temperature).toBe(0) + expect(request.maxTokens).toBeUndefined() expect(request.providerOptions).toEqual({ store: true, metadata: { request: true } }) expect(request.headers).toEqual({ "x-shared": "request" }) expect(request.http).toEqual({ body: { metadata: { request: true } }, query: { request: "1" } }) @@ -146,7 +160,7 @@ describe("llm constructors", () => { }) const updated = LanguageModel.update(base, { route: responsesRoute, - defaults: { generation: { maxTokens: 20 } }, + options: { maxTokens: 20 }, compatibility: { sanitizer: "gemini", requireFinishReason: false }, }) const updatedInput = LanguageModel.input(updated) @@ -154,9 +168,9 @@ describe("llm constructors", () => { expect(updated).toBeInstanceOf(LanguageModel) expect(String(updated.id)).toBe("fake-model") expect(updated.route).toBe(responsesRoute) - expect(updated.defaults?.generation).toEqual({ maxTokens: 20 }) + expect(updated.options?.maxTokens).toBe(20) expect(updated.compatibility).toEqual({ sanitizer: "gemini", requireFinishReason: false }) - expect(updatedInput.defaults).toBe(updated.defaults) + expect(updatedInput.options).toBe(updated.options) expect(updatedInput.compatibility).toBe(updated.compatibility) expect(String(updatedInput.provider)).toBe("fake") expect(LanguageModel.update(updated, {})).toBe(updated) @@ -165,8 +179,9 @@ describe("llm constructors", () => { test("carries model defaults and compatibility through route model selection", () => { const model = chatRoute.model({ id: "kimi-k2", - defaults: { - generation: { maxTokens: 1_024, stop: ["END"] }, + options: { + maxTokens: 1_024, + stop: ["END"], providerOptions: { parallelToolCalls: false }, http: { body: { extra_body: true } }, }, @@ -174,11 +189,11 @@ describe("llm constructors", () => { }) const request = ai.request({ model, prompt: "Say hello." }) - expect(request.model.defaults?.generation).toEqual({ maxTokens: 1_024, stop: ["END"] }) - expect(request.model.defaults?.providerOptions).toEqual({ parallelToolCalls: false }) - expect(request.model.defaults?.http).toEqual({ body: { extra_body: true } }) + expect(request.model.options).toMatchObject({ maxTokens: 1_024, stop: ["END"] }) + expect(request.model.options?.providerOptions).toEqual({ parallelToolCalls: false }) + expect(request.model.options?.http).toEqual({ body: { extra_body: true } }) expect(request.model.compatibility).toEqual({ sanitizer: "moonshot" }) - expect(request.generation).toBeUndefined() + expect(request.maxTokens).toBeUndefined() expect(request.providerOptions).toBeUndefined() expect(request.http).toBeUndefined() }) diff --git a/packages/ai/test/provider-options/checkpoint.types.ts b/packages/ai/test/provider-options/checkpoint.types.ts index 59c12959fa44..2e1f5f4e4575 100644 --- a/packages/ai/test/provider-options/checkpoint.types.ts +++ b/packages/ai/test/provider-options/checkpoint.types.ts @@ -47,7 +47,7 @@ for (const selected of [ OpenAI.model("fixture", {}), model.route.with({ headers: { fixture: "test" } }).model({ id: "fixture" }), LanguageModel.make(LanguageModel.input(model)), - LanguageModel.update(model, { defaults: { generation: { maxTokens: 100 } } }), + LanguageModel.update(model, { options: { maxTokens: 100 } }), ]) { ai.compact(ai.request({ model: selected, prompt: "Hello" }), { mechanism: "trigger" }) } diff --git a/packages/ai/test/provider-options/compaction.types.ts b/packages/ai/test/provider-options/compaction.types.ts index 000076a2f4d2..158e680409bc 100644 --- a/packages/ai/test/provider-options/compaction.types.ts +++ b/packages/ai/test/provider-options/compaction.types.ts @@ -25,7 +25,7 @@ for (const model of [ Azure.responsesModel("fixture", { resourceName: "test" }), XAI.model("fixture", {}), openai.route.with({ headers: { "x-test": "test" } }).model({ id: "fixture" }), - LanguageModel.update(openai, { defaults: { generation: { maxTokens: 100 } } }), + LanguageModel.update(openai, { options: { maxTokens: 100 } }), LanguageModel.make(LanguageModel.input(openai)), ]) { ai.compact(ai.request({ model, prompt: "hello" })) diff --git a/packages/ai/test/provider-package.test.ts b/packages/ai/test/provider-package.test.ts index 7b53054f480a..1a330eeb8f73 100644 --- a/packages/ai/test/provider-package.test.ts +++ b/packages/ai/test/provider-package.test.ts @@ -29,8 +29,8 @@ describe("provider package entrypoints", () => { expect(model.route.endpoint.baseURL).toBe( `https://llm-fixture.eu-central-1.maas.aliyuncs.com/${index === 2 ? "apps/anthropic/v1" : "compatible-mode/v1"}`, ) - expect(model.route.defaults.headers).toEqual(settings.headers) - expect(model.route.defaults.http?.body).toEqual(settings.body) + expect(model.options?.headers).toEqual(settings.headers) + expect(model.options?.http?.body).toEqual(settings.body) }) }) @@ -53,8 +53,8 @@ describe("provider package entrypoints", () => { expect(selected.provider).toBe("moonshotai") expect(selected.route.id).toBe(routes[index]) expect(selected.route.endpoint.baseURL).toBe(settings.baseURL) - expect(selected.route.defaults.headers).toEqual(settings.headers) - expect(selected.route.defaults.http?.body).toEqual(settings.body) + expect(selected.options?.headers).toEqual(settings.headers) + expect(selected.options?.http?.body).toEqual(settings.body) }) }) @@ -91,9 +91,9 @@ describe("provider package entrypoints", () => { expect(selected.route.id).toBe(`${provider}-responses`) expect(selected.route.protocol).toBe(protocol) expect(selected.route.endpoint).toMatchObject({ baseURL, path: "/responses" }) - expect(selected.route.defaults.headers).toEqual(settings.headers) - expect(selected.route.defaults.http?.body).toEqual(settings.body) - expect(selected.route.defaults.providerOptions).toEqual({ + expect(selected.options?.headers).toEqual(settings.headers) + expect(selected.options?.http?.body).toEqual(settings.body) + expect(selected.options?.providerOptions).toEqual({ reasoningEffort: "low", store: false, include: ["reasoning.encrypted_content"], @@ -118,8 +118,8 @@ describe("provider package entrypoints", () => { const selected = module.model("command-a-03-2025", settings) expect(selected.provider).toBe("cohere") expect([selected.route.id, selected.route.endpoint.baseURL]).toEqual(routes[index]) - expect(selected.route.defaults.headers).toEqual(settings.headers) - expect(selected.route.defaults.http?.body).toEqual(settings.body) + expect(selected.options?.headers).toEqual(settings.headers) + expect(selected.options?.http?.body).toEqual(settings.body) }) }) @@ -142,8 +142,8 @@ describe("provider package entrypoints", () => { expect(selected.provider).toBe("minimax") expect(selected.route.id).toBe(routes[index]) expect(selected.route.endpoint.baseURL).toBe(settings.baseURL) - expect(selected.route.defaults.headers).toEqual(settings.headers) - expect(selected.route.defaults.http?.body).toEqual(settings.body) + expect(selected.options?.headers).toEqual(settings.headers) + expect(selected.options?.http?.body).toEqual(settings.body) }) }) @@ -175,8 +175,8 @@ describe("provider package entrypoints", () => { expect(selected.provider).toBe(index < 2 ? "zai" : "zai-coding-plan") expect(selected.route.id).toBe(routes[index]) expect(selected.route.endpoint.baseURL).toBe(settings.baseURL) - expect(selected.route.defaults.headers).toEqual(settings.headers) - expect(selected.route.defaults.http?.body).toEqual(settings.body) + expect(selected.options?.headers).toEqual(settings.headers) + expect(selected.options?.http?.body).toEqual(settings.body) }) }) @@ -193,9 +193,9 @@ describe("provider package entrypoints", () => { expect(deepinfra.route.id).toBe("deepinfra-chat") expect(deepinfra.route.endpoint.baseURL).toBe("https://provider.example.test/v1/openai") - expect(deepinfra.route.defaults.providerOptions).toEqual({ reasoningEffort: "high" }) - expect(deepinfra.route.defaults.headers).toEqual(settings.headers) - expect(deepinfra.route.defaults.http?.body).toEqual(settings.body) + expect(deepinfra.options?.providerOptions).toEqual({ reasoningEffort: "high" }) + expect(deepinfra.options?.headers).toEqual(settings.headers) + expect(deepinfra.options?.http?.body).toEqual(settings.body) }) test("maps Cloudflare package settings onto provider-owned models", async () => { @@ -213,9 +213,9 @@ describe("provider package entrypoints", () => { }) expect(selected.provider).toBe(provider.id) expect(selected.route.endpoint.baseURL).toBe(provider.baseURL({ accountId: "account" })) - expect(selected.route.defaults.headers).toMatchObject({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ custom: true }) - expect(selected.route.defaults.providerOptions).toEqual({ reasoningEffort: "high" }) + expect(selected.options?.headers).toMatchObject({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ custom: true }) + expect(selected.options?.providerOptions).toEqual({ reasoningEffort: "high" }) } }) @@ -239,11 +239,11 @@ describe("provider package entrypoints", () => { for (const selected of [openrouter, xai]) { expect(selected.route.endpoint.baseURL).toBe(settings.baseURL) - expect(selected.route.defaults.headers).toEqual(settings.headers) - expect(selected.route.defaults.http?.body).toEqual(settings.body) + expect(selected.options?.headers).toEqual(settings.headers) + expect(selected.options?.http?.body).toEqual(settings.body) } - expect(openrouter.route.defaults.providerOptions).toEqual({ usage: true }) - expect(xai.route.defaults.providerOptions).toMatchObject({ reasoningEffort: "high", store: false }) + expect(openrouter.options?.providerOptions).toEqual({ usage: true }) + expect(xai.options?.providerOptions).toMatchObject({ reasoningEffort: "high", store: false }) }) test("maps package settings onto the executable model", () => { @@ -256,8 +256,8 @@ describe("provider package entrypoints", () => { }) expect(selected.route.id).toBe("openai-responses") - expect(selected.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ service_tier: "priority" }) + expect(selected.options?.headers).toEqual({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ service_tier: "priority" }) }) test("maps OpenAI-compatible Responses settings onto the executable model", async () => { @@ -278,9 +278,9 @@ describe("provider package entrypoints", () => { baseURL: "https://responses.example.test/v1", path: "/responses", }) - expect(selected.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ service_tier: "priority" }) - expect(selected.route.defaults.providerOptions).toEqual({ + expect(selected.options?.headers).toEqual({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ service_tier: "priority" }) + expect(selected.options?.providerOptions).toEqual({ reasoningEffort: "low", store: true, include: ["reasoning.encrypted_content"], @@ -311,9 +311,9 @@ describe("provider package entrypoints", () => { body: {}, }).toString(), ).toBe("https://messages.example.test/v1/messages") - expect(selected.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ metadata: { user_id: "user_1" } }) - expect(selected.route.defaults.providerOptions).toEqual({ effort: "low" }) + expect(selected.options?.headers).toEqual({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ metadata: { user_id: "user_1" } }) + expect(selected.options?.providerOptions).toEqual({ effort: "low" }) }) test("maps Anthropic provider options onto the executable model", async () => { @@ -324,7 +324,7 @@ describe("provider package entrypoints", () => { }) expect(selected.route.id).toBe("anthropic-messages") - expect(selected.route.defaults.providerOptions).toEqual({ thinking: { type: "adaptive" } }) + expect(selected.options?.providerOptions).toEqual({ thinking: { type: "adaptive" } }) }) test("requires an Anthropic-compatible base URL at runtime", async () => { @@ -362,7 +362,7 @@ describe("provider package entrypoints", () => { project: "proj_123", }) - expect(selected.route.defaults.headers).toMatchObject({ + expect(selected.options?.headers).toMatchObject({ "OpenAI-Organization": "org_123", "OpenAI-Project": "proj_123", }) @@ -385,8 +385,8 @@ describe("provider package entrypoints", () => { expect(Azure.model("deployment", settings).route.id).toBe("azure-openai-responses") expect(responses.route.id).toBe("azure-openai-responses") expect(responses.route.endpoint.baseURL).toBe("https://opencode-test.openai.azure.com/openai/v1") - expect(responses.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(responses.route.defaults.http?.body).toEqual({ service_tier: "priority" }) + expect(responses.options?.headers).toEqual({ "x-application": "opencode" }) + expect(responses.options?.http?.body).toEqual({ service_tier: "priority" }) expect(chat.route.id).toBe("azure-openai-chat") }) @@ -424,9 +424,9 @@ describe("provider package entrypoints", () => { expect(selected.route.id).toBe("gemini") expect(selected.route.endpoint.baseURL).toBe("https://generativelanguage.test/v1beta") - expect(selected.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ safetySettings: [] }) - expect(selected.route.defaults.providerOptions).toEqual({ thinkingConfig: { thinkingBudget: 1_024 } }) + expect(selected.options?.headers).toEqual({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ safetySettings: [] }) + expect(selected.options?.providerOptions).toEqual({ thinkingConfig: { thinkingBudget: 1_024 } }) const interactions = GoogleInteractions.model("gemini-3.8-flash", { apiKey: "fixture", baseURL: "https://generativelanguage.test/v1beta", @@ -435,7 +435,7 @@ describe("provider package entrypoints", () => { }) expect(interactions.route.id).toBe("google-interactions") expect(interactions.route.endpoint.baseURL).toBe("https://generativelanguage.test/v1beta") - expect(interactions.route.defaults.providerOptions).toEqual({ thinkingLevel: "low", store: true }) + expect(interactions.options?.providerOptions).toEqual({ thinkingLevel: "low", store: true }) expect(Google.configure().interactions("gemini-3.8-flash").route.protocol).toBe("google-interactions") }) @@ -468,8 +468,8 @@ describe("provider package entrypoints", () => { expect(gemini.route.id).toBe("google-vertex-gemini") expect(gemini.route.protocol).toBe("gemini") expect(gemini.route.endpoint.baseURL).toBe("https://aiplatform.googleapis.com/v1/publishers/google") - expect(gemini.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(gemini.route.defaults.http?.body).toEqual({ safetySettings: [] }) + expect(gemini.options?.headers).toEqual({ "x-application": "opencode" }) + expect(gemini.options?.http?.body).toEqual({ safetySettings: [] }) expect( GoogleVertex.model("gemini-3.5-flash", { accessToken: "fixture", @@ -494,7 +494,7 @@ describe("provider package entrypoints", () => { baseURL: "https://aiplatform.googleapis.com/v1/projects/vertex-project/locations/global/endpoints/openapi", path: "/responses", }) - expect(responses.route.defaults.providerOptions).toEqual({ + expect(responses.options?.providerOptions).toEqual({ store: false, include: ["reasoning.encrypted_content"], }) @@ -518,9 +518,9 @@ describe("provider package entrypoints", () => { path: "/interactions", query: { alt: "sse" }, }) - expect(selected.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ generation_config: { temperature: 0.5 } }) - expect(selected.route.defaults.providerOptions).toEqual({ thinkingLevel: "low", store: false }) + expect(selected.options?.headers).toEqual({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ generation_config: { temperature: 0.5 } }) + expect(selected.options?.providerOptions).toEqual({ thinkingLevel: "low", store: false }) }) test("rejects conflicting Vertex auth settings at runtime", async () => { diff --git a/packages/ai/test/provider/alibaba-capabilities.recorded.test.ts b/packages/ai/test/provider/alibaba-capabilities.recorded.test.ts index fd2c82d5b67f..03478cecce81 100644 --- a/packages/ai/test/provider/alibaba-capabilities.recorded.test.ts +++ b/packages/ai/test/provider/alibaba-capabilities.recorded.test.ts @@ -34,7 +34,7 @@ for (const api of ["chat", "messages", "responses"] as const) { ? { enableThinking: enabled, ...(enabled ? { thinkingBudget: 1024 } : {}) } : { enableThinking: enabled }, prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const compiled = yield* compileRequest(request) expect(api === "messages" ? compiled.body.thinking.type : compiled.body.enable_thinking).toBe( @@ -68,7 +68,7 @@ for (const api of ["chat", "messages", "responses"] as const) { { type: "media", media: Media.bytes(bytes, "image/png") }, ]), ], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text.toLowerCase()).toContain("jiggling restroom prison") @@ -98,7 +98,7 @@ for (const api of ["chat", "messages", "responses"] as const) { }), ], toolChoice: { type: "tool", name: "get_weather" }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.toolCalls).toMatchObject([{ name: "get_weather", input: { city: "Paris" } }]) @@ -120,7 +120,7 @@ record("chat").effect.with( model: alibaba.chat("qwen3.8-max"), prompt: 'Return a JSON object with one key "city" set to the capital city of France.', providerOptions: { reasoningEffort: "none", responseFormat: { type: "json_object" } }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }), ) expect(JSON.parse(response.text)).toEqual({ city: "Paris" }) @@ -152,7 +152,7 @@ record("messages").effect.with( }, }, }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }), ) expect(JSON.parse(response.text)).toEqual({ city: "Paris" }) @@ -172,7 +172,7 @@ responses.effect.with( model: alibaba.responses("qwen3.8-max"), prompt: "Remember the password word apricot. Reply OK.", providerOptions: { store: true, reasoningEffort: "none" }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }), ) const id = first.events.find(LLMEvent.is.finish)?.providerMetadata?.alibaba?.responseId @@ -183,7 +183,7 @@ responses.effect.with( model: alibaba.responses("qwen3.8-max"), prompt: "What word did I ask you to remember? Reply with only the word.", providerOptions: { previousResponseId: id, store: true, reasoningEffort: "none" }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }), ) expect(second.text.toLowerCase()).toContain("apricot") @@ -203,7 +203,7 @@ responses.effect.with( "Use web search to find Alibaba Cloud Model Studio's official documentation, then use web_extractor to read the page. Give a brief summary with the source URL.", tools: [Alibaba.webSearch(), Alibaba.webExtractor()], providerOptions: { reasoningEffort: "low", store: false }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const response = yield* LLMClient.generate(request) expect(response.toolCalls).toEqual( @@ -240,7 +240,7 @@ responses.effect.with( "Use the code interpreter to compute the SHA-256 hash of the UTF-8 string hello (no newline). Reply with only the hash.", tools: [Alibaba.codeInterpreter()], providerOptions: { reasoningEffort: "low" }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.toolCalls).toEqual( diff --git a/packages/ai/test/provider/alibaba.recorded.test.ts b/packages/ai/test/provider/alibaba.recorded.test.ts index 91ff65f149e4..9bf2f3dd478b 100644 --- a/packages/ai/test/provider/alibaba.recorded.test.ts +++ b/packages/ai/test/provider/alibaba.recorded.test.ts @@ -39,7 +39,7 @@ for (const api of ["chat", "messages", "responses"] as const) { model: alibaba[api]("qwen3.8-max"), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", providerOptions: api === "messages" ? { effort } : { reasoningEffort: effort }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const compiled = yield* compileRequest(request) expect(compiled.body.enable_thinking).toBeUndefined() @@ -77,7 +77,7 @@ for (const api of ["chat", "messages", "responses"] as const) { prompt: "We have a budget of 38000 dollars for 219 trips costing 173 dollars each. Calculate whether that is affordable. If it is, use get_weather to look up the current weather in Paris. After receiving the result, report the weather in one short sentence.", tools: [weather], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const first = yield* LLMClient.generate(request) expect(first.toolCalls).toMatchObject([{ name: "get_weather", input: { city: "Paris" } }]) diff --git a/packages/ai/test/provider/alibaba.test.ts b/packages/ai/test/provider/alibaba.test.ts index 0b4536819d0f..25754b3adacd 100644 --- a/packages/ai/test/provider/alibaba.test.ts +++ b/packages/ai/test/provider/alibaba.test.ts @@ -163,7 +163,8 @@ it.effect("Alibaba keeps native reasoning controls and future efforts on their s model: provider.chat("qwen3.7-plus"), prompt: "Hello", tools: [tool], - generation: { maxTokens: 1234, topK: 20 }, + maxTokens: 1234, + topK: 20, providerOptions: { enableThinking, thinkingBudget: 512, @@ -234,7 +235,7 @@ it.effect("Alibaba fits explicit thinking budgets to half the output limit", () ai.request({ model: provider.chat("qwen3.7-plus"), prompt: "hi", - ...(maxTokens === undefined ? {} : { generation: { maxTokens } }), + ...(maxTokens === undefined ? {} : { maxTokens }), providerOptions: { enableThinking: true, thinkingBudget: 131_071 }, }), ).pipe(Effect.map((prepared) => prepared.body.thinking_budget)) @@ -242,7 +243,7 @@ it.effect("Alibaba fits explicit thinking budgets to half the output limit", () ai.request({ model: provider.messages("qwen3.7-plus"), prompt: "hi", - generation: { maxTokens: 32_000 }, + maxTokens: 32_000, providerOptions: { thinking: { type: "enabled", budgetTokens: 131_071 } }, }), ) diff --git a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts index d98c1ba06881..0c3676bc2fd4 100644 --- a/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts +++ b/packages/ai/test/provider/anthropic-messages-cache.recorded.test.ts @@ -21,7 +21,8 @@ const cacheRequest = ai.request({ // Manual hint on the system part is the only marker we want here — skip the // auto-policy's latest-user-message breakpoint so the cassette body matches. cache: "none", - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, }) const lookup = ToolDefinition.make({ @@ -54,7 +55,8 @@ const longToolTurnRequest = ai.request({ system: LARGE_CACHEABLE_SYSTEM, messages: longToolTurn, tools: [lookup], - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, }) const recorded = recordedTests({ diff --git a/packages/ai/test/provider/anthropic-messages.test.ts b/packages/ai/test/provider/anthropic-messages.test.ts index 207baeb27b55..b708df2bd2c4 100644 --- a/packages/ai/test/provider/anthropic-messages.test.ts +++ b/packages/ai/test/provider/anthropic-messages.test.ts @@ -52,7 +52,8 @@ const request = ai.request({ // This fixture predates the `cache: "auto"` default; pin the policy off so // existing wire-shape assertions only see the manual hint on the system part. cache: "none", - generation: { maxTokens: 20, temperature: 0 }, + maxTokens: 20, + temperature: 0, }) type AnthropicToolResult = Extract< @@ -147,12 +148,12 @@ describe("Anthropic Messages route", () => { Effect.gen(function* () { const enabled = yield* compileRequest({ ...request, - generation: { maxTokens: 4_096 }, + maxTokens: 4_096, providerOptions: { thinking: { type: "enabled", budgetTokens: 1_024 } }, }) const legacy = yield* compileRequest({ ...request, - generation: { maxTokens: 4_096 }, + maxTokens: 4_096, providerOptions: { thinking: { type: "enabled", budget_tokens: 2_048 } }, }) const disabled = yield* compileRequest({ ...request, providerOptions: { thinking: { type: "disabled" } } }) @@ -168,7 +169,7 @@ describe("Anthropic Messages route", () => { const thinking = (maxTokens: number) => compileRequest({ ...request, - generation: { maxTokens }, + maxTokens, providerOptions: { thinking: { type: "enabled", budgetTokens: 31_999 } }, }).pipe(Effect.map((prepared) => prepared.body.thinking)) diff --git a/packages/ai/test/provider/bedrock-converse-cache.recorded.test.ts b/packages/ai/test/provider/bedrock-converse-cache.recorded.test.ts index bbccc246764f..db310efeb106 100644 --- a/packages/ai/test/provider/bedrock-converse-cache.recorded.test.ts +++ b/packages/ai/test/provider/bedrock-converse-cache.recorded.test.ts @@ -25,7 +25,8 @@ const cacheRequest = ai.request({ // Manual hint on the system part is the only marker we want here — skip the // auto-policy's latest-user-message breakpoint so the cassette body matches. cache: "none", - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, }) const recorded = recordedTests({ diff --git a/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts b/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts index 42795ca3bfe2..ec0bbd13c8c3 100644 --- a/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts +++ b/packages/ai/test/provider/bedrock-converse-options.recorded.test.ts @@ -39,7 +39,7 @@ describe("Bedrock Converse options recorded", () => { }), prompt: "How many primes are below 60? Reply with the number only.", cache: "none", - generation: { maxTokens: 4_000 }, + maxTokens: 4_000, }), ) @@ -61,7 +61,7 @@ describe("Bedrock Converse options recorded", () => { }), prompt: "What is 17*23? Reply with the number only.", cache: "none", - generation: { maxTokens: 1_000 }, + maxTokens: 1_000, }), ) @@ -79,7 +79,7 @@ describe("Bedrock Converse options recorded", () => { model: bedrock("us.amazon.nova-2-lite-v1:0", { effort: "low" }), prompt: "What is 17*23? Reply with the number only.", cache: "none", - generation: { maxTokens: 1_000 }, + maxTokens: 1_000, }), ) @@ -108,7 +108,7 @@ describe("Bedrock Converse options recorded", () => { }), prompt: "What is 17*23?", cache: "none", - generation: { maxTokens: 200 }, + maxTokens: 200, }), ) diff --git a/packages/ai/test/provider/bedrock-converse-options.test.ts b/packages/ai/test/provider/bedrock-converse-options.test.ts index d7ebf72c7755..17e0dbc2f460 100644 --- a/packages/ai/test/provider/bedrock-converse-options.test.ts +++ b/packages/ai/test/provider/bedrock-converse-options.test.ts @@ -11,7 +11,7 @@ const bedrock = (id: string, settings: Omit) => - ai.request({ model, prompt: "Say hello.", cache: "none", generation: { maxTokens: 64 } }) + ai.request({ model, prompt: "Say hello.", cache: "none", maxTokens: 64 }) const body = (model: ReturnType) => compileRequest(request(model)).pipe(Effect.map((prepared) => prepared.body)) diff --git a/packages/ai/test/provider/bedrock-converse-thinking-binding.recorded.test.ts b/packages/ai/test/provider/bedrock-converse-thinking-binding.recorded.test.ts index 0e7873525241..c167ad8126d5 100644 --- a/packages/ai/test/provider/bedrock-converse-thinking-binding.recorded.test.ts +++ b/packages/ai/test/provider/bedrock-converse-thinking-binding.recorded.test.ts @@ -32,7 +32,7 @@ const first = ai.request({ system: "You are a concise assistant.", prompt: question, cache: "none", - generation: { maxTokens: 12_000 }, + maxTokens: 12_000, }) const recorded = recordedTests({ @@ -55,7 +55,7 @@ describe("Bedrock Converse thinking binding recorded", () => { system: "Reply with the single word 'Hello'.", prompt: "Say hello.", cache: "none", - generation: { maxTokens: 1_024 }, + maxTokens: 1_024, }), ) diff --git a/packages/ai/test/provider/bedrock-converse-thinking-binding.test.ts b/packages/ai/test/provider/bedrock-converse-thinking-binding.test.ts index a037495037b8..f3a12043b680 100644 --- a/packages/ai/test/provider/bedrock-converse-thinking-binding.test.ts +++ b/packages/ai/test/provider/bedrock-converse-thinking-binding.test.ts @@ -1,6 +1,6 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" -import { ai, GenerationOptions, LanguageModel } from "../../src/effect.js" +import { ai, LanguageModel, type GenerationOptionsFields } from "../../src/effect.js" import { compileRequest } from "../../src/route/client.js" import { AmazonBedrock } from "../../src/providers.js" import { it } from "../lib/effect.js" @@ -11,7 +11,7 @@ const beta = ["thinking-binding-controls-2026-08-01"] const bedrock = (id: string, settings: Parameters[1] = {}) => AmazonBedrock.model(id, { baseURL: "https://bedrock-runtime.test", apiKey: "test-bearer", ...settings }) -const fields = (model: LanguageModel, generation?: GenerationOptions) => +const fields = (model: LanguageModel, generation?: GenerationOptionsFields) => compileRequest( ai.request({ id: "req_1", @@ -19,7 +19,7 @@ const fields = (model: LanguageModel, generation?: GenerationOptions) => system: "You are concise.", prompt: "Say hello.", cache: "none", - generation, + ...generation, }), ).pipe(Effect.map((prepared) => prepared.body.additionalModelRequestFields)) @@ -66,7 +66,7 @@ describe("Bedrock Converse thinking block binding", () => { expect( yield* fields( bedrock("global.anthropic.claude-fable-5-1", { thinking: { type: "enabled", budgetTokens: 4_000 } }), - GenerationOptions.make({ maxTokens: 64_000, topK: 40 }), + { maxTokens: 64_000, topK: 40 }, ), ).toEqual({ top_k: 40, diff --git a/packages/ai/test/provider/bedrock-converse.test.ts b/packages/ai/test/provider/bedrock-converse.test.ts index 0f4e95b89bd6..92a78c22d8d9 100644 --- a/packages/ai/test/provider/bedrock-converse.test.ts +++ b/packages/ai/test/provider/bedrock-converse.test.ts @@ -7,7 +7,6 @@ import { HttpClientRequest } from "effect/http" import { ai, CacheHint, - GenerationOptions, type LanguageModel, LLMEvent, Media, @@ -148,7 +147,8 @@ const baseRequest = ai.request({ // Wire-shape assertions in this file predate the `cache: "auto"` default; // pin the policy off so they only exercise the lowering path itself. cache: "none", - generation: { maxTokens: 64, temperature: 0 }, + maxTokens: 64, + temperature: 0, }) describe("Bedrock Converse route", () => { @@ -213,7 +213,9 @@ describe("Bedrock Converse route", () => { Effect.gen(function* () { const prepared = yield* compileRequest({ ...baseRequest, - generation: GenerationOptions.make({ maxTokens: 64, temperature: 0, topK: 40 }), + maxTokens: 64, + temperature: 0, + topK: 40, }) // Converse's inferenceConfig has no topK; Anthropic/Nova read it from @@ -251,7 +253,8 @@ describe("Bedrock Converse route", () => { apiKey: "test-bearer", thinking: { type: "enabled", budgetTokens }, }), - generation: GenerationOptions.make({ maxTokens, topK }), + maxTokens, + topK, }).pipe(Effect.map((prepared) => prepared.body.additionalModelRequestFields)) expect(yield* fields(64_000, 31_999)).toEqual({ thinking: { type: "enabled", budget_tokens: 31_999 } }) @@ -1891,7 +1894,8 @@ describe("Bedrock Converse route", () => { Message.user([{ type: "text", text: "User prefix.", cache }]), Message.assistant([{ type: "text", text: "Assistant prefix.", cache }]), ], - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, }), ) @@ -2457,7 +2461,8 @@ describe("Bedrock Converse recorded", () => { system: "Reply with the single word 'Hello'.", prompt: "Say hello.", cache: "none", - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, }), ) @@ -2480,7 +2485,8 @@ describe("Bedrock Converse recorded", () => { tools: [weatherTool], toolChoice: ToolChoice.make(weatherTool), cache: "none", - generation: { maxTokens: 80, temperature: 0 }, + maxTokens: 80, + temperature: 0, }), ) @@ -2530,7 +2536,8 @@ describe("Bedrock Converse recorded", () => { ], tools: [weatherTool], cache: "none", - generation: { maxTokens: 40, temperature: 0 }, + maxTokens: 40, + temperature: 0, }), ) diff --git a/packages/ai/test/provider/bedrock-mantle.test.ts b/packages/ai/test/provider/bedrock-mantle.test.ts index 7effd316a656..134ccf4c6df5 100644 --- a/packages/ai/test/provider/bedrock-mantle.test.ts +++ b/packages/ai/test/provider/bedrock-mantle.test.ts @@ -237,7 +237,8 @@ describe("Amazon Bedrock Mantle recorded", () => { region: "us-east-1", }).responses("openai.gpt-oss-120b"), prompt: "Reply with exactly: hello", - generation: { maxTokens: 256, temperature: 0 }, + maxTokens: 256, + temperature: 0, }), ) @@ -288,7 +289,7 @@ describe("Amazon Bedrock Mantle Messages recorded", () => { thinking: { type: "adaptive", display: "summarized" }, effort: "medium", }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, }) const first = yield* LLMClient.generate(initial) expect(first.finishReason.normalized).toBe("tool-calls") @@ -343,7 +344,7 @@ describe("Amazon Bedrock Mantle Messages recorded", () => { providerOptions: { thinking: { type: "enabled", budgetTokens: 1024 }, }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, }) const compiled = yield* compileRequest(request) expect(compiled.body.thinking).toEqual({ type: "enabled", budget_tokens: 1024 }) @@ -370,7 +371,7 @@ describe("Amazon Bedrock Mantle Messages recorded", () => { thinking: { type: "adaptive", display: "summarized" }, effort: "high", }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, }) const firstCompiled = yield* compileRequest(firstRequest) expect(firstCompiled.body.thinking).toEqual({ @@ -396,7 +397,7 @@ describe("Amazon Bedrock Mantle Messages recorded", () => { thinking: { type: "adaptive", display: "summarized" }, effort: "low", }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, }) const secondCompiled = yield* compileRequest(secondRequest) expect(secondCompiled.body.output_config).toEqual({ effort: "high" }) @@ -428,7 +429,7 @@ describe("Amazon Bedrock Mantle Messages recorded", () => { thinking: { type: "adaptive", display: "summarized" }, effort: "low", }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }) const compiled = yield* compileRequest(request) expect(compiled.body.output_config).toEqual({ effort: "low" }) diff --git a/packages/ai/test/provider/checkpoint.test.ts b/packages/ai/test/provider/checkpoint.test.ts index 8290189dd2ea..7838ee78095d 100644 --- a/packages/ai/test/provider/checkpoint.test.ts +++ b/packages/ai/test/provider/checkpoint.test.ts @@ -156,7 +156,7 @@ testEffect( ai.request({ model: OpenAI.configure({ apiKey: "fixture" }).responses("gpt-5.5"), prompt: "Hello.", - generation: { maxTokens: 20_000 }, + maxTokens: 20_000, providerOptions: { textVerbosity: "low" }, http: { body: { text: { verbosity: "high", format: { type: "json_object" } } } }, }), @@ -181,7 +181,7 @@ testEffect( ai.request({ model: OpenAI.configure({ apiKey: "fixture" }).responses("gpt-5.5"), prompt: "Hello.", - generation: { maxTokens: 128 }, + maxTokens: 128, }), trigger, ) diff --git a/packages/ai/test/provider/cloudflare.test.ts b/packages/ai/test/provider/cloudflare.test.ts index cf58e06ca8a3..558d2b747688 100644 --- a/packages/ai/test/provider/cloudflare.test.ts +++ b/packages/ai/test/provider/cloudflare.test.ts @@ -153,7 +153,7 @@ describe("Cloudflare", () => { }), ) - expect(prepared.model.route.defaults.headers).toMatchObject({ "cf-aig-gateway-id": "default" }) + expect(prepared.model.options?.headers).toMatchObject({ "cf-aig-gateway-id": "default" }) }), ) diff --git a/packages/ai/test/provider/cohere.recorded.test.ts b/packages/ai/test/provider/cohere.recorded.test.ts index 3437f30218de..7e40ab37b136 100644 --- a/packages/ai/test/provider/cohere.recorded.test.ts +++ b/packages/ai/test/provider/cohere.recorded.test.ts @@ -17,7 +17,7 @@ recorded.effect( ai.request({ model: cohere.model("command-a-03-2025"), prompt: "Reply exactly: OK", - generation: { maxTokens: 64 }, + maxTokens: 64, }), ) expect(response.text.trim()).toMatch(/^OK\.?$/) @@ -38,7 +38,7 @@ recorded.effect( model: cohere.model("command-a-reasoning-08-2025"), prompt: "What is 17 times 23? Answer briefly.", providerOptions: { thinking: { type: "enabled", tokenBudget: 128 } }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, }), ) expect(response.reasoning.length).toBeGreaterThan(0) @@ -81,7 +81,7 @@ recorded.effect( model: cohere.chat("command-a-reasoning-08-2025"), prompt: "What is 17 times 23? Answer briefly.", providerOptions: { reasoningEffort: "high" }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, }), ) expect(response.reasoning.length).toBeGreaterThan(0) diff --git a/packages/ai/test/provider/cohere.test.ts b/packages/ai/test/provider/cohere.test.ts index 208970884494..350ee4e92f3a 100644 --- a/packages/ai/test/provider/cohere.test.ts +++ b/packages/ai/test/provider/cohere.test.ts @@ -14,7 +14,7 @@ test("Cohere exposes native and compatible endpoints without Core remapping", () expect(cohere.chat("command-a-03-2025").route.endpoint.baseURL).toBe("https://api.cohere.ai/compatibility/v1") expect( Cohere.model("command-a-03-2025", { apiKey: "fixture", headers: { "X-Test": "yes" }, body: { temperature: 0 } }) - .route.defaults?.http, + .options?.http, ).toMatchObject({ body: { temperature: 0 } }) }) @@ -32,7 +32,9 @@ it.effect("Cohere lowers native history, thinking, tools, and sampling", () => tools: [{ name: "lookup", description: "Look up a city", inputSchema: { type: "object", properties: {} } }], toolChoice: "required", providerOptions: { thinking: { tokenBudget: 128 } }, - generation: { maxTokens: 2048, topP: 0.9, topK: 10 }, + maxTokens: 2048, + topP: 0.9, + topK: 10, }), ) expect(prepared.body).toMatchObject({ @@ -69,7 +71,7 @@ it.effect("Cohere compatibility omits unsupported OpenAI fields", () => model: cohere.chat("command-a-reasoning-08-2025"), prompt: "Hello", providerOptions: { reasoningEffort: "high" }, - generation: { maxTokens: 64 }, + maxTokens: 64, }), ) expect(prepared.body).toMatchObject({ reasoning_effort: "high", max_tokens: 64, stream: true }) @@ -231,7 +233,7 @@ it.effect("Cohere fits thinking budgets under the output limit", () => model: cohere.model("command-a-reasoning-08-2025"), prompt: "Hi", providerOptions: { thinking: { tokenBudget: 31_999 } }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(prepared.body.thinking).toEqual({ type: "enabled", token_budget: 2048 }) diff --git a/packages/ai/test/provider/compaction.recorded.test.ts b/packages/ai/test/provider/compaction.recorded.test.ts index 3a69a244a0ad..b75f63c0f260 100644 --- a/packages/ai/test/provider/compaction.recorded.test.ts +++ b/packages/ai/test/provider/compaction.recorded.test.ts @@ -28,7 +28,7 @@ for (const provider of [ "compacts and continues with the provider checkpoint", () => Effect.gen(function* () { - const request = ai.request({ model: provider.model, messages: history, generation: { maxTokens: 1024 } }) + const request = ai.request({ model: provider.model, messages: history, maxTokens: 1024 }) const compacted = yield* ai.compact(request) const result = yield* LLMClient.generate({ ...request, @@ -63,7 +63,7 @@ recordedTests({ "The implementation and tests were reviewed. ".repeat(10000), ), ], - generation: { maxTokens: 4096 }, + maxTokens: 4096, providerOptions: { contextManagement: { edits: [ diff --git a/packages/ai/test/provider/conversation-lowering.test.ts b/packages/ai/test/provider/conversation-lowering.test.ts index f4762b9e3c2a..033cde58c5c8 100644 --- a/packages/ai/test/provider/conversation-lowering.test.ts +++ b/packages/ai/test/provider/conversation-lowering.test.ts @@ -12,7 +12,8 @@ it.effect("conversation lowering excludes generation settings and tool definitio model: OpenAI.configure({ apiKey: "test" }).responses("fixture"), system: "Keep the context", messages: [Message.user("hello"), Message.assistant("hi")], - generation: { maxTokens: 100, temperature: 0.5 }, + maxTokens: 100, + temperature: 0.5, providerOptions: { store: false }, tools: [{ name: "unsupported", description: "Generation only", inputSchema: {}, native: { unsupported: {} } }], }), diff --git a/packages/ai/test/provider/digitalocean.recorded.test.ts b/packages/ai/test/provider/digitalocean.recorded.test.ts index 4a429ed06afc..57d540b7b9b8 100644 --- a/packages/ai/test/provider/digitalocean.recorded.test.ts +++ b/packages/ai/test/provider/digitalocean.recorded.test.ts @@ -38,7 +38,7 @@ for (const item of [ system: LARGE_CACHEABLE_SYSTEM, prompt: "Reply exactly: OK", promptCacheKey: `digitalocean-recorded-${item.id}`, - generation: { maxTokens: item.maxTokens }, + maxTokens: item.maxTokens, }) const first = yield* LLMClient.generate(request) const second = yield* LLMClient.generate(request) diff --git a/packages/ai/test/provider/digitalocean.test.ts b/packages/ai/test/provider/digitalocean.test.ts index 3b29fd871ec9..54e95ff8d434 100644 --- a/packages/ai/test/provider/digitalocean.test.ts +++ b/packages/ai/test/provider/digitalocean.test.ts @@ -15,7 +15,7 @@ describe("DigitalOcean", () => { headers: { "X-Test": "fixture" }, body: { temperature: 0 }, }) - expect(model.route.defaults).toMatchObject({ + expect(model.options).toMatchObject({ headers: { "X-Test": "fixture" }, http: { body: { temperature: 0 } }, }) diff --git a/packages/ai/test/provider/explicit-compaction.test.ts b/packages/ai/test/provider/explicit-compaction.test.ts index 7cae31346ed2..ea09f03abd2d 100644 --- a/packages/ai/test/provider/explicit-compaction.test.ts +++ b/packages/ai/test/provider/explicit-compaction.test.ts @@ -61,7 +61,7 @@ testEffect( headers.push(String(request.model.id)) return { "x-deployment": "fixture", "x-override": "route" } }, - defaults: { + options: { headers: { "x-default": "configured", "x-override": "configured" }, providerOptions: { store: false }, http: { body: { instructions: "default instructions" } }, @@ -293,7 +293,7 @@ for (const overlay of [undefined, { service_tier: "priority", prompt_cache_key: include: ["reasoning.encrypted_content"], parallelToolCalls: false, }, - generation: { maxTokens: 100 }, + maxTokens: 100, tools: [{ name: "lookup", description: "Lookup", inputSchema: {} }], http: { body: { diff --git a/packages/ai/test/provider/gemini-cache.recorded.test.ts b/packages/ai/test/provider/gemini-cache.recorded.test.ts index 2230adbd1401..c1a46eb2cc9b 100644 --- a/packages/ai/test/provider/gemini-cache.recorded.test.ts +++ b/packages/ai/test/provider/gemini-cache.recorded.test.ts @@ -20,7 +20,8 @@ const cacheRequest = ai.request({ model, system: LARGE_CACHEABLE_SYSTEM, prompt: "Say hi.", - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, }) const recorded = recordedTests({ diff --git a/packages/ai/test/provider/gemini.test.ts b/packages/ai/test/provider/gemini.test.ts index 9776d57a551c..99d615e32696 100644 --- a/packages/ai/test/provider/gemini.test.ts +++ b/packages/ai/test/provider/gemini.test.ts @@ -39,7 +39,8 @@ const request = ai.request({ model, system: "You are concise.", prompt: "Say hello.", - generation: { maxTokens: 20, temperature: 0 }, + maxTokens: 20, + temperature: 0, }) describe("Gemini route", () => { @@ -100,7 +101,7 @@ describe("Gemini route", () => { const thinkingBudget = (budget: number, maxTokens = 32_000) => compileRequest({ ...request, - generation: { maxTokens }, + maxTokens, providerOptions: { thinkingConfig: { thinkingBudget: budget } }, }).pipe(Effect.map((prepared) => prepared.body.generationConfig?.thinkingConfig?.thinkingBudget)) @@ -117,16 +118,14 @@ describe("Gemini route", () => { ai.request({ model, prompt: "Say hello.", - generation: { - maxTokens: 40, - temperature: 0.2, - topP: 0.8, - topK: 12, - frequencyPenalty: 0.3, - presencePenalty: 0.4, - seed: 42, - stop: ["done"], - }, + maxTokens: 40, + temperature: 0.2, + topP: 0.8, + topK: 12, + frequencyPenalty: 0.3, + presencePenalty: 0.4, + seed: 42, + stop: ["done"], }), ) diff --git a/packages/ai/test/provider/google-interactions.recorded.test.ts b/packages/ai/test/provider/google-interactions.recorded.test.ts index 5fc00755ed81..ea35904a2d30 100644 --- a/packages/ai/test/provider/google-interactions.recorded.test.ts +++ b/packages/ai/test/provider/google-interactions.recorded.test.ts @@ -23,7 +23,7 @@ describe("Google Interactions recorded", () => { ai.request({ model, prompt: "Reply with exactly one word: hello", - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: { thinkingLevel: "low" }, }), ) @@ -47,7 +47,7 @@ describe("Google Interactions recorded", () => { model, prompt: "Find the smallest positive integer that leaves remainder 1 modulo 7, 2 modulo 9, and 3 modulo 11. Explain briefly.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, providerOptions: { thinkingLevel: "high", thinkingSummaries: "auto" }, }), ) @@ -77,7 +77,7 @@ describe("Google Interactions recorded", () => { prompt: "What is the weather in Paris?", tools: [weatherTool], toolChoice: { type: "tool", name: weatherTool.name }, - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto" }, }) const first = yield* LLMClient.generate(request) @@ -96,7 +96,7 @@ describe("Google Interactions recorded", () => { system: request.system, tools: [weatherTool], toolChoice: "none", - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto" }, messages: [ ...request.messages, @@ -124,7 +124,7 @@ describe("Google Interactions recorded", () => { prompt: "What is the weather in Paris?", tools: [weatherTool], toolChoice: "required", - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: { thinkingLevel: "low", store: true }, }) const first = yield* LLMClient.generate(request) @@ -150,7 +150,7 @@ describe("Google Interactions recorded", () => { system: request.system, tools: [weatherTool], toolChoice: "none", - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: { thinkingLevel: "low", previousInteractionId: metadata.interactionId, store: false }, messages: [ Message.tool({ id: call.id, name: call.name, result: { temperature: 22, condition: "sunny" } }), diff --git a/packages/ai/test/provider/groq.recorded.test.ts b/packages/ai/test/provider/groq.recorded.test.ts index 5608e16fa6b9..a4fe615a149c 100644 --- a/packages/ai/test/provider/groq.recorded.test.ts +++ b/packages/ai/test/provider/groq.recorded.test.ts @@ -42,7 +42,7 @@ describe("Groq recorded", () => { }, }).model("openai/gpt-oss-20b"), prompt: "Reply with exactly one word: hello", - generation: { maxTokens: 512 }, + maxTokens: 512, }) const compiled = yield* compileRequest(request) expect(compiled.body).toMatchObject({ @@ -96,7 +96,7 @@ describe("Groq recorded", () => { prompt: `Look up the current weather in ${item.cities.join(" and ")}. Call lookup_weather once for each city in the same response before answering. After receiving all results, report each city's weather in one short sentence.`, tools: [weather], toolChoice: "required", - generation: { maxTokens: 1536 }, + maxTokens: 1536, }) const compiled = yield* compileRequest(request) expect(compiled.body.stream_options).toEqual({ include_usage: true }) @@ -161,7 +161,7 @@ describe("Groq recorded", () => { }).model("qwen/qwen3.6-27b"), prompt: "What is 173 multiplied by 219? Think through the arithmetic, then reply with only the final integer.", - generation: { maxTokens: 2048 }, + maxTokens: 2048, }) const compiled = yield* compileRequest(request) expect(compiled.body).toMatchObject({ reasoning_format: "parsed", reasoning_effort: "default" }) diff --git a/packages/ai/test/provider/groq.test.ts b/packages/ai/test/provider/groq.test.ts index f15f70cd74bd..5343e9803b8d 100644 --- a/packages/ai/test/provider/groq.test.ts +++ b/packages/ai/test/provider/groq.test.ts @@ -12,9 +12,7 @@ it.effect("Groq reuses Chat streaming and defaults to parsed reasoning", () => expect(Groq.protocol.stream).toBe(OpenAIChat.protocol.stream) const model = Groq.configure({ apiKey: "fixture" }).model("llama-3.3-70b-versatile") expect(model.route.endpoint.baseURL).toBe("https://api.groq.com/openai/v1") - const compiled = yield* compileRequest( - ai.request({ model, prompt: "Hello", tools: [weatherTool], generation: { maxTokens: 64 } }), - ) + const compiled = yield* compileRequest(ai.request({ model, prompt: "Hello", tools: [weatherTool], maxTokens: 64 })) expect(compiled.body).toMatchObject({ max_completion_tokens: 64, stream_options: { include_usage: true }, @@ -50,8 +48,8 @@ it.effect("Groq lowers its own options for custom catalog identities and endpoin }), ) expect(model.route.endpoint.baseURL).toBe("https://gateway.example/v1") - expect(model.route.defaults.headers).toEqual({ "x-client": "test" }) - expect(model.route.defaults.http?.body).toEqual({ custom: "value" }) + expect(model.options?.headers).toEqual({ "x-client": "test" }) + expect(model.options?.http?.body).toEqual({ custom: "value" }) expect(compiled.body).toMatchObject({ reasoning_effort: "default", reasoning_format: "parsed", diff --git a/packages/ai/test/provider/meta-capabilities.test.ts b/packages/ai/test/provider/meta-capabilities.test.ts index bdf3ea1630e5..de37f90be589 100644 --- a/packages/ai/test/provider/meta-capabilities.test.ts +++ b/packages/ai/test/provider/meta-capabilities.test.ts @@ -24,7 +24,7 @@ it.effect("Meta selects Messages and lowers native search alongside ordinary fun ToolDefinition.make({ name: "lookup", description: "Lookup", inputSchema: { type: "object" } }), ], providerOptions: { effort: "low" }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }), ) expect(compiled.body).toMatchObject({ diff --git a/packages/ai/test/provider/meta-images.recorded.test.ts b/packages/ai/test/provider/meta-images.recorded.test.ts index 99e26e49d67d..b4c6731d80fe 100644 --- a/packages/ai/test/provider/meta-images.recorded.test.ts +++ b/packages/ai/test/provider/meta-images.recorded.test.ts @@ -81,7 +81,7 @@ recorded.effect.with( size: "1024x1024", }), ], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const compiled = yield* compileRequest(request) expect(compiled.body.tools).toMatchObject([ diff --git a/packages/ai/test/provider/meta-messages.recorded.test.ts b/packages/ai/test/provider/meta-messages.recorded.test.ts index e3a44536d657..39cb7efe5230 100644 --- a/packages/ai/test/provider/meta-messages.recorded.test.ts +++ b/packages/ai/test/provider/meta-messages.recorded.test.ts @@ -24,7 +24,7 @@ for (const mode of ["adaptive", "enabled"] as const) { const request = ai.request({ model, prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: { thinking: mode === "adaptive" @@ -77,7 +77,7 @@ recorded.effect.with( }), ], toolChoice: "auto", - generation: { maxTokens: 1024 }, + maxTokens: 1024, providerOptions: { effort: "low" }, }) const compiled = yield* compileRequest(request) diff --git a/packages/ai/test/provider/meta-search.recorded.test.ts b/packages/ai/test/provider/meta-search.recorded.test.ts index 99c10937078e..9741985dd36b 100644 --- a/packages/ai/test/provider/meta-search.recorded.test.ts +++ b/packages/ai/test/provider/meta-search.recorded.test.ts @@ -26,7 +26,7 @@ for (const api of ["responses", "messages"] as const) { prompt: "Use web search to find NASA's page identifying the first person to walk on the Moon. Answer in one sentence with a source citation.", tools: [Meta.webSearch()], - generation: { maxTokens: 2048 }, + maxTokens: 2048, providerOptions: api === "responses" ? { reasoningEffort: "low", include: ["reasoning.encrypted_content", "web_search_call.results"] } diff --git a/packages/ai/test/provider/meta.recorded.test.ts b/packages/ai/test/provider/meta.recorded.test.ts index 4b474bc2fa48..b27735774b1c 100644 --- a/packages/ai/test/provider/meta.recorded.test.ts +++ b/packages/ai/test/provider/meta.recorded.test.ts @@ -38,7 +38,7 @@ for (const api of ["responses", "chat"] as const) { const request = ai.request({ model: meta[api](modelID), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 1024 }, + maxTokens: 1024, providerOptions: { reasoningEffort: effort, ...(api === "responses" && effort === "high" ? { reasoningSummary: "auto" } : {}), @@ -92,7 +92,7 @@ for (const api of ["responses", "chat"] as const) { tools: [weather], toolChoice: "auto", providerOptions: { reasoningEffort: "low" }, - generation: { maxTokens: 1024 }, + maxTokens: 1024, }) const compiled = yield* compileRequest(request) expect(compiled.body.tool_choice).toBe("auto") diff --git a/packages/ai/test/provider/meta.test.ts b/packages/ai/test/provider/meta.test.ts index 25e3b66ddee2..fb8b118894af 100644 --- a/packages/ai/test/provider/meta.test.ts +++ b/packages/ai/test/provider/meta.test.ts @@ -90,13 +90,13 @@ it.effect("Meta package selectors preserve overrides and Chat token policy on cu reasoningEffort: "future-effort", }) expect(model.route.endpoint.baseURL).toBe("https://gateway.example/v1") - expect(model.route.defaults.headers).toEqual({ "x-client": "test" }) - expect(model.route.defaults.http?.body).toEqual({ custom: "value" }) + expect(model.options?.headers).toEqual({ "x-client": "test" }) + expect(model.options?.http?.body).toEqual({ custom: "value" }) const compiled = yield* compileRequest( ai.request({ model, prompt: "Hello", - generation: { maxTokens: 64 }, + maxTokens: 64, providerOptions: { store: true, include: [] }, }), ) diff --git a/packages/ai/test/provider/minimax.recorded.test.ts b/packages/ai/test/provider/minimax.recorded.test.ts index f64ff23c4002..0bf601de448a 100644 --- a/packages/ai/test/provider/minimax.recorded.test.ts +++ b/packages/ai/test/provider/minimax.recorded.test.ts @@ -86,7 +86,7 @@ describe("MiniMax recorded", () => { const request = ai.request({ model: item.model, prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 1536 }, + maxTokens: 1536, }) const compiled = yield* compileRequest(request) expect(compiled.body).toMatchObject(item.body) @@ -122,7 +122,7 @@ describe("MiniMax recorded", () => { prompt: "Use get_weather to look up the current weather in Paris.", tools: [weather], toolChoice: ToolChoice.named("get_weather"), - generation: { maxTokens: 512 }, + maxTokens: 512, }), ) expect(response.finishReason.normalized).toBe("tool-calls") @@ -174,7 +174,7 @@ describe("MiniMax recorded", () => { "Look up the current weather in Paris using get_weather before answering. After receiving the result, report the weather in one short sentence.", tools: [weather], toolChoice: "auto", - generation: { maxTokens: 1536 }, + maxTokens: 1536, }) const first = yield* LLMClient.generate(request) expect(first.finishReason.normalized).toBe("tool-calls") diff --git a/packages/ai/test/provider/minimax.test.ts b/packages/ai/test/provider/minimax.test.ts index 9c14b56cba74..cb472ce67fd4 100644 --- a/packages/ai/test/provider/minimax.test.ts +++ b/packages/ai/test/provider/minimax.test.ts @@ -85,7 +85,7 @@ describe("MiniMax provider", () => { ai.request({ model: minimax.chat("MiniMax-M3"), prompt: "Hello", - generation: { maxTokens: 128 }, + maxTokens: 128, providerOptions: { thinking: { type: "disabled" }, reasoningSplit: false }, }), ) diff --git a/packages/ai/test/provider/mistral-chat.test.ts b/packages/ai/test/provider/mistral-chat.test.ts index 6efdedf04bae..2bb60059a6cf 100644 --- a/packages/ai/test/provider/mistral-chat.test.ts +++ b/packages/ai/test/provider/mistral-chat.test.ts @@ -63,15 +63,13 @@ describe("Mistral Chat", () => { ], toolChoice: "lookup", promptCacheKey: "session-1", - generation: { - maxTokens: 64, - seed: 7, - temperature: 0.2, - topP: 0.8, - frequencyPenalty: 0.1, - presencePenalty: 0.3, - stop: ["done"], - }, + maxTokens: 64, + seed: 7, + temperature: 0.2, + topP: 0.8, + frequencyPenalty: 0.1, + presencePenalty: 0.3, + stop: ["done"], providerOptions: { safePrompt: true, documentImageLimit: 3, @@ -205,7 +203,7 @@ describe("Mistral Chat", () => { const unsupported = yield* compileRequest( ai.request({ - model: LanguageModel.update(model, { compatibility: { supportsPromptCacheKey: false } }), + model: LanguageModel.update(model, { capabilities: { promptCacheKey: false } }), prompt: "Hello", promptCacheKey: "common-key", providerOptions: { promptCacheKey: "native-key" }, diff --git a/packages/ai/test/provider/mistral.recorded.test.ts b/packages/ai/test/provider/mistral.recorded.test.ts index 32a8d890385e..dce4e374d6ea 100644 --- a/packages/ai/test/provider/mistral.recorded.test.ts +++ b/packages/ai/test/provider/mistral.recorded.test.ts @@ -41,7 +41,8 @@ describe("Mistral recorded", () => { ai.request({ model: configure({ apiKey, providerOptions: { reasoningEffort: "none" } }).model("mistral-small-latest"), prompt: "Reply with exactly one word: hello", - generation: { maxTokens: 40, temperature: 0 }, + maxTokens: 40, + temperature: 0, }), ) @@ -62,7 +63,8 @@ describe("Mistral recorded", () => { const firstRequest = ai.request({ model, prompt: "Calculate 17 multiplied by 23. Think briefly, then reply with only the integer.", - generation: { maxTokens: 512, temperature: 0 }, + maxTokens: 512, + temperature: 0, }) const first = yield* LLMClient.generate(firstRequest) @@ -73,7 +75,8 @@ describe("Mistral recorded", () => { const followUp = { ...firstRequest, messages: [...firstRequest.messages, first.message, Message.user("Reply with exactly: Done.")], - generation: { maxTokens: 256, temperature: 0 }, + maxTokens: 256, + temperature: 0, } const replay = yield* compileRequest(followUp) expect(replay.body.messages).toContainEqual( @@ -105,7 +108,8 @@ describe("Mistral recorded", () => { prompt: "What is the weather?", tools: [weather], toolChoice: weather, - generation: { maxTokens: 160, temperature: 0 }, + maxTokens: 160, + temperature: 0, }) const first = yield* LLMClient.generate(firstRequest) @@ -123,7 +127,8 @@ describe("Mistral recorded", () => { first.message, Message.tool({ id: call.id, name: call.name, result: { condition: "sunny", temperature: "18C" } }), ], - generation: { maxTokens: 160, temperature: 0 }, + maxTokens: 160, + temperature: 0, } const second = yield* LLMClient.generate(followUp) @@ -148,7 +153,8 @@ describe("Mistral hosted GLM recorded", () => { prompt: "What is the weather?", tools: [weather], toolChoice: weather, - generation: { maxTokens: 256, temperature: 0 }, + maxTokens: 256, + temperature: 0, }), ) diff --git a/packages/ai/test/provider/moonshot-capabilities.recorded.test.ts b/packages/ai/test/provider/moonshot-capabilities.recorded.test.ts index 530d826d38a8..01d9c58c525b 100644 --- a/packages/ai/test/provider/moonshot-capabilities.recorded.test.ts +++ b/packages/ai/test/provider/moonshot-capabilities.recorded.test.ts @@ -44,7 +44,7 @@ for (const api of ["chat", "messages", "responses"] as const) { prompt: "Use get_weather to look up the current weather in Paris.", tools: [weather], toolChoice, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) if (api === "responses") { @@ -88,7 +88,7 @@ for (const api of ["chat", "messages", "responses"] as const) { { type: "media", media: Media.bytes(image, "image/png") }, ]), ], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text.toLowerCase()).toContain("jiggling restroom prison") @@ -108,7 +108,7 @@ for (const api of ["chat", "messages", "responses"] as const) { ai.request({ model, prompt: "Return a JSON object containing the capital city of France.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, http: { body: api === "chat" diff --git a/packages/ai/test/provider/moonshot.recorded.test.ts b/packages/ai/test/provider/moonshot.recorded.test.ts index 49fbc84cc034..f14c690c75bb 100644 --- a/packages/ai/test/provider/moonshot.recorded.test.ts +++ b/packages/ai/test/provider/moonshot.recorded.test.ts @@ -24,7 +24,7 @@ for (const api of ["chat", "messages", "responses"] as const) { providerOptions: api === "messages" ? { effort } : { reasoningEffort: effort }, })[api]("kimi-k3"), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const compiled = yield* compileRequest(request) expect(compiled.body.thinking).toBeUndefined() @@ -69,7 +69,7 @@ for (const item of [ ai.request({ model: Moonshot.configure({ apiKey, providerOptions: { thinking: item.thinking } }).chat(item.model), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text.replaceAll(",", "")).toContain("37887") @@ -111,7 +111,7 @@ for (const item of [ prompt: "Use get_weather to look up the current weather in Paris. After receiving the result, report the weather in one short sentence.", tools: [weather], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const first = yield* LLMClient.generate(request) expect(first.finishReason.normalized).toBe("tool-calls") diff --git a/packages/ai/test/provider/moonshot.test.ts b/packages/ai/test/provider/moonshot.test.ts index a7413f7fe61b..41105dac6d2f 100644 --- a/packages/ai/test/provider/moonshot.test.ts +++ b/packages/ai/test/provider/moonshot.test.ts @@ -54,7 +54,7 @@ it.effect("Moonshot preserves default reasoning across model IDs on custom endpo }) for (const id of ["kimi-k2.6", "kimi-k2.7-code", "kimi-k2.7-code-highspeed", "kimi-k3", "future-model"]) { const model = moonshot.chat(id) - const request = ai.request({ model, prompt: "Hello", generation: { maxTokens: 100 } }) + const request = ai.request({ model, prompt: "Hello", maxTokens: 100 }) const compiled = yield* compileRequest(request) expect(compiled.body).toMatchObject({ model: id, max_tokens: 100, stream: true }) expect(compiled.body.max_completion_tokens).toBeUndefined() diff --git a/packages/ai/test/provider/native-providers.test.ts b/packages/ai/test/provider/native-providers.test.ts index cb5a45c607a9..bbe06b031e42 100644 --- a/packages/ai/test/provider/native-providers.test.ts +++ b/packages/ai/test/provider/native-providers.test.ts @@ -83,7 +83,8 @@ describe("native OpenAI-compatible providers", () => { expect(together).toMatchObject({ provider: "togetherai", - compatibility: { maxTokensField: "max_tokens", supportsStrictMode: false }, + compatibility: { maxTokensField: "max_tokens" }, + capabilities: { tools: { strict: false } }, route: { id: "togetherai-chat", protocol: "openai-chat" }, }) expect(together.route.endpoint.baseURL).toBe("https://api.together.xyz/v1") @@ -110,7 +111,7 @@ describe("native OpenAI-compatible providers", () => { expect(selected.route.endpoint.baseURL).toBe(settings.baseURL) const input = { prompt: "Use a tool.", - generation: { maxTokens: 48 }, + maxTokens: 48, tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })], } const native = yield* compileRequest(ai.request({ ...input, model: selected })) @@ -141,7 +142,7 @@ describe("native OpenAI-compatible providers", () => { ai.request({ model: TogetherAI.configure({ apiKey: "fixture", baseURL: "https://gateway.example/v1" }).model("llama"), prompt: "Use a tool.", - generation: { maxTokens: 32 }, + maxTokens: 32, tools: [ ToolDefinition.make({ name: "lookup", description: "Look up data", inputSchema: { type: "object" } }), ], @@ -161,7 +162,7 @@ describe("native OpenAI-compatible providers", () => { const cerebras = yield* compileRequest( ai.request({ model: Cerebras.configure({ apiKey: "fixture", baseURL: "https://gateway.example/v1" }).model("qwen"), - generation: { maxTokens: 48 }, + maxTokens: 48, messages: [ Message.user("Think first."), Message.assistant([ @@ -212,9 +213,9 @@ describe("native OpenAI-compatible providers", () => { }) expect(selected.route.endpoint.baseURL).toBe("https://gateway.example/v1") - expect(selected.route.defaults.headers).toEqual({ "x-application": "opencode" }) - expect(selected.route.defaults.http?.body).toEqual({ service_tier: "priority" }) - expect(selected.route.defaults.providerOptions).toEqual({ reasoningEffort: "high" }) + expect(selected.options?.headers).toEqual({ "x-application": "opencode" }) + expect(selected.options?.http?.body).toEqual({ service_tier: "priority" }) + expect(selected.options?.providerOptions).toEqual({ reasoningEffort: "high" }) } }) diff --git a/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts b/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts index a061536bde02..3f2e7c28c087 100644 --- a/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts +++ b/packages/ai/test/provider/openai-chat-reasoning.recorded.test.ts @@ -60,7 +60,8 @@ for (const item of cases) { model: item.model, system: "Think through the arithmetic, then reply with only the final integer.", prompt: "What is 173 multiplied by 219?", - generation: { maxTokens: 1536, temperature: 0 }, + maxTokens: 1536, + temperature: 0, }), ) diff --git a/packages/ai/test/provider/openai-chat.test.ts b/packages/ai/test/provider/openai-chat.test.ts index 6c07ad4c57b6..18664f77521e 100644 --- a/packages/ai/test/provider/openai-chat.test.ts +++ b/packages/ai/test/provider/openai-chat.test.ts @@ -39,7 +39,8 @@ const request = ai.request({ model, system: "You are concise.", prompt: "Say hello.", - generation: { maxTokens: 20, temperature: 0 }, + maxTokens: 20, + temperature: 0, }) describe("OpenAI Chat route", () => { @@ -66,7 +67,7 @@ describe("OpenAI Chat route", () => { Effect.gen(function* () { const prepared = yield* compileRequest( ai.request({ - model: LanguageModel.update(model, { compatibility: { streamUsage: false } }), + model: LanguageModel.update(model, { capabilities: { streamUsage: false } }), prompt: "Hello", }), ) @@ -88,7 +89,7 @@ describe("OpenAI Chat route", () => { const optedIn = yield* compileRequest( ai.request({ model: LanguageModel.update(compatible.model("compatible-model"), { - compatibility: { supportsStore: true }, + capabilities: { store: true }, }), prompt: "Hello", }), @@ -377,7 +378,7 @@ describe("OpenAI Chat route", () => { ai.request({ model: OpenAIChat.route .with({ endpoint: { baseURL: "https://api.compatible.test/v1" }, auth: Auth.bearer("test") }) - .model({ id: "compatible-model", compatibility: { supportsPromptCacheKey: true } }), + .model({ id: "compatible-model", capabilities: { promptCacheKey: true } }), prompt: "Hello", promptCacheKey: "session_123", }), diff --git a/packages/ai/test/provider/openai-compatible-chat.test.ts b/packages/ai/test/provider/openai-compatible-chat.test.ts index 8752576075e6..bdd589723752 100644 --- a/packages/ai/test/provider/openai-compatible-chat.test.ts +++ b/packages/ai/test/provider/openai-compatible-chat.test.ts @@ -25,7 +25,8 @@ const request = ai.request({ model, system: "You are concise.", prompt: "Say hello.", - generation: { maxTokens: 20, temperature: 0 }, + maxTokens: 20, + temperature: 0, }) const deltaChunk = (delta: object, finishReason: string | null = null) => ({ @@ -186,9 +187,7 @@ describe("OpenAI-compatible Chat route", () => { const compatible = OpenAICompatibleChat.route .with({ provider: "custom", endpoint: { baseURL: "https://api.custom.test/v1" } }) .model({ id: "custom-model", compatibility: { maxTokensField: "max_completion_tokens" } }) - const prepared = yield* compileRequest( - ai.request({ model: compatible, prompt: "Say hello.", generation: { maxTokens: 20 } }), - ) + const prepared = yield* compileRequest(ai.request({ model: compatible, prompt: "Say hello.", maxTokens: 20 })) expect(prepared.body).toMatchObject({ max_completion_tokens: 20 }) expect(prepared.body).not.toHaveProperty("max_tokens") diff --git a/packages/ai/test/provider/openai-compatible-responses.test.ts b/packages/ai/test/provider/openai-compatible-responses.test.ts index ea1b37e5561f..b961e4a024a7 100644 --- a/packages/ai/test/provider/openai-compatible-responses.test.ts +++ b/packages/ai/test/provider/openai-compatible-responses.test.ts @@ -986,7 +986,8 @@ describe("Open Responses-compatible route", () => { ai.request({ model, prompt: "Think.", - generation: { presencePenalty: 0.2, frequencyPenalty: -0.1 }, + presencePenalty: 0.2, + frequencyPenalty: -0.1, tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })], }), ) diff --git a/packages/ai/test/provider/openai-responses-cache.recorded.test.ts b/packages/ai/test/provider/openai-responses-cache.recorded.test.ts index a0f38369393d..915ded54fa55 100644 --- a/packages/ai/test/provider/openai-responses-cache.recorded.test.ts +++ b/packages/ai/test/provider/openai-responses-cache.recorded.test.ts @@ -19,7 +19,8 @@ const cacheRequest = ai.request({ model, system: LARGE_CACHEABLE_SYSTEM, prompt: "Say hi.", - generation: { maxTokens: 16, temperature: 0 }, + maxTokens: 16, + temperature: 0, promptCacheKey: "recorded-cache-test", }) diff --git a/packages/ai/test/provider/openai-responses-websocket.recorded.test.ts b/packages/ai/test/provider/openai-responses-websocket.recorded.test.ts index 5eb77c3d665f..a22598bdfd8c 100644 --- a/packages/ai/test/provider/openai-responses-websocket.recorded.test.ts +++ b/packages/ai/test/provider/openai-responses-websocket.recorded.test.ts @@ -121,7 +121,7 @@ describe("OpenAI Responses WebSocket recorded", () => { system: "Call get_weather once, then reply exactly: Paris is sunny.", prompt: "What is the weather in Paris?", tools: [weatherTool], - generation: { maxTokens: 50 }, + maxTokens: 50, cache: "none", }) const first = yield* LLMClient.generate(request, { webSocket: channel.executor }) @@ -159,7 +159,7 @@ describe("OpenAI Responses WebSocket recorded", () => { model, system: "Follow the user's exact reply instruction.", prompt: "Reply exactly: Alpha.", - generation: { maxTokens: 30 }, + maxTokens: 30, cache: "none", }) const first = yield* LLMClient.generate(request, { webSocket: channel.executor }) @@ -190,7 +190,7 @@ describe("OpenAI Responses WebSocket recorded", () => { model, system: "Follow the user's exact reply instruction.", prompt: "Reply exactly: Ready.", - generation: { maxTokens: 30 }, + maxTokens: 30, cache: "none", }) const first = yield* LLMClient.generate(request, { webSocket: channel.executor }) diff --git a/packages/ai/test/provider/openai-responses.test.ts b/packages/ai/test/provider/openai-responses.test.ts index a139e5cc39ad..f7dcb5af59c5 100644 --- a/packages/ai/test/provider/openai-responses.test.ts +++ b/packages/ai/test/provider/openai-responses.test.ts @@ -102,7 +102,8 @@ const request = ai.request({ model, system: "You are concise.", prompt: "Say hello.", - generation: { maxTokens: 20, temperature: 0 }, + maxTokens: 20, + temperature: 0, }) const configEnv = (env: Record) => Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))) @@ -1458,6 +1459,28 @@ describe("OpenAI Responses route", () => { }), ) + it.effect("keeps the system code when a WebSocket fails to connect", () => + Effect.gen(function* () { + const socket = Object.assign(new EventTarget(), { readyState: globalThis.WebSocket.CONNECTING, close: () => {} }) + const failed = Object.assign(new Event("error"), { + error: Object.assign(new Error("Failed to connect"), { code: "ENOTFOUND" }), + }) + queueMicrotask(() => socket.dispatchEvent(failed)) + const error = yield* WebSocketTransport.fromWebSocket( + // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- waitOpen only listens for events on this branch. + socket as unknown as globalThis.WebSocket, + { url: "wss://api.openai.test/v1/responses", headers: Headers.empty }, + ).pipe(Effect.flip) + + expect(error.reason).toMatchObject({ + _tag: "Transport", + code: "ENOTFOUND", + phase: "connect", + delivery: "not-sent", + }) + }), + ) + it.effect("adds native query params to the Responses URL", () => Effect.gen(function* () { yield* LLMClient.generate({ @@ -2009,7 +2032,8 @@ describe("OpenAI Responses route", () => { model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).model("gpt-5.2"), prompt: "think", promptCacheKey: "session_123", - generation: { presencePenalty: 0.25, frequencyPenalty: -0.25 }, + presencePenalty: 0.25, + frequencyPenalty: -0.25, tools: [ ToolDefinition.make({ name: "read", description: "Read a file", inputSchema: { type: "object" } }), ToolDefinition.make({ name: "grep", description: "Search files", inputSchema: { type: "object" } }), @@ -2205,18 +2229,18 @@ describe("OpenAI Responses route", () => { }), ) - it.effect("omits the prompt cache key when compatibility disables it", () => + it.effect("omits the prompt cache key when capabilities disable it", () => Effect.gen(function* () { const prepared = yield* compileRequest( ai.request({ - model: LanguageModel.update(model, { compatibility: { supportsPromptCacheKey: false } }), + model: LanguageModel.update(model, { capabilities: { promptCacheKey: false } }), prompt: "Hello", promptCacheKey: "request_cache", }), ) expect(prepared.body).not.toHaveProperty("prompt_cache_key") - expect(model.compatibility?.supportsPromptCacheKey).toBeUndefined() + expect(model.capabilities?.promptCacheKey).toBeUndefined() expect( (yield* compileRequest(ai.request({ model, prompt: "Hello", promptCacheKey: "request_cache" }))).body, ).toHaveProperty("prompt_cache_key", "request_cache") diff --git a/packages/ai/test/provider/openrouter.test.ts b/packages/ai/test/provider/openrouter.test.ts index 9376b6583506..b3e9917632ef 100644 --- a/packages/ai/test/provider/openrouter.test.ts +++ b/packages/ai/test/provider/openrouter.test.ts @@ -340,7 +340,7 @@ describe("OpenRouter", () => { model: OpenRouter.configure({ apiKey: "test-key" }).model("qwen/qwen3.8-flash"), cache: "none", prompt: "Hello", - ...(maxTokens === undefined ? {} : { generation: { maxTokens } }), + ...(maxTokens === undefined ? {} : { maxTokens }), providerOptions: { reasoning: value }, }), ).pipe(Effect.map((prepared) => prepared.body.reasoning)) diff --git a/packages/ai/test/provider/pdf.recorded.test.ts b/packages/ai/test/provider/pdf.recorded.test.ts index e6ea4311eb01..00babb15459e 100644 --- a/packages/ai/test/provider/pdf.recorded.test.ts +++ b/packages/ai/test/provider/pdf.recorded.test.ts @@ -129,7 +129,8 @@ describe("PDF recorded", () => { id: `recorded_pdf_${target.id}_user_input`, model: target.model, cache: "none", - generation: { maxTokens: target.maxTokens, temperature: 0 }, + maxTokens: target.maxTokens, + temperature: 0, messages: [ Message.user([ { type: "media", media: Media.base64(PDF, "application/pdf"), filename: target.filename }, @@ -162,7 +163,8 @@ describe("PDF recorded", () => { "Call read_pdf exactly once with path verification.pdf, then reply only with the verification code from its PDF.", prompt: "Use read_pdf with path verification.pdf and return the verification code.", cache: "none", - generation: { maxTokens: target.maxTokens, temperature: 0 }, + maxTokens: target.maxTokens, + temperature: 0, }), tools: [readPdfRuntime], }).pipe(Stream.runCollect), @@ -179,7 +181,8 @@ describe("PDF recorded", () => { model: target.model, system: "Read the PDF returned by the tool and follow the user's response format exactly.", cache: "none", - generation: { maxTokens: target.maxTokens, temperature: 0 }, + maxTokens: target.maxTokens, + temperature: 0, messages: [ Message.user(prompt), Message.assistant([{ type: "tool-call", id: "call_pdf_1", name: readPdf.name, input: {} }]), diff --git a/packages/ai/test/provider/responses-routes.recorded.test.ts b/packages/ai/test/provider/responses-routes.recorded.test.ts index 15af4168ac3f..63a76ff91205 100644 --- a/packages/ai/test/provider/responses-routes.recorded.test.ts +++ b/packages/ai/test/provider/responses-routes.recorded.test.ts @@ -49,7 +49,7 @@ for (const item of [ recorded.effect.with("streams text", { tags: ["text", "usage"] }, () => Effect.gen(function* () { const response = yield* LLMClient.generate( - ai.request({ model: item.model, prompt: "Reply exactly: OK", generation: { maxTokens: 64 } }), + ai.request({ model: item.model, prompt: "Reply exactly: OK", maxTokens: 64 }), ) expect(response.text.trim()).toMatch(/^OK\.?$/) expect(response.events.some(LLMEvent.is.textDelta)).toBe(true) @@ -80,7 +80,7 @@ for (const item of [ prompt: "Use the run tool to execute exactly this code: print(1)", tools: run, toolChoice: "required", - generation: { maxTokens: 256 }, + maxTokens: 256, }), ) expect(response.toolCalls).toMatchObject([{ name: "run", input: { code: expect.stringContaining("print(1)") } }]) diff --git a/packages/ai/test/provider/venice.recorded.test.ts b/packages/ai/test/provider/venice.recorded.test.ts index d7afcad74f71..efa041702d21 100644 --- a/packages/ai/test/provider/venice.recorded.test.ts +++ b/packages/ai/test/provider/venice.recorded.test.ts @@ -45,7 +45,7 @@ for (const item of [ prompt: "Look up conversion rate for code ZEBRA. Then multiply that rate by 17 and add 9. You must use lookup_rate before answering.", tools: [lookup], - generation: { maxTokens: 4096 }, + maxTokens: 4096, providerOptions: "effort" in item ? { reasoningEffort: item.effort } : undefined, }) const first = yield* LLMClient.generate(request) @@ -141,7 +141,7 @@ recorded.effect.with( "Look up private rates for both ZEBRA and MOOSE using two calls to lookup_rate. Then add the rates and multiply by 7. Use parallel calls if possible.", tools: [lookup], providerOptions: { reasoningEffort: "high", parallelToolCalls: true }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const first = yield* LLMClient.generate(request) expect(first.toolCalls).toHaveLength(2) @@ -213,7 +213,7 @@ recorded.effect.with( model: Venice.configure({ apiKey }).chat("qwen3-6-27b"), prompt: "What is 23 multiplied by 17 plus 9? Reply with just the number.", providerOptions: { reasoning: { enabled: false } }, - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text).toContain("400") diff --git a/packages/ai/test/provider/venice.test.ts b/packages/ai/test/provider/venice.test.ts index 30440c75edad..801cbfa45481 100644 --- a/packages/ai/test/provider/venice.test.ts +++ b/packages/ai/test/provider/venice.test.ts @@ -54,7 +54,8 @@ it.effect("Venice lowers typed options, model defaults, and explicit reasoning o "qwen3-6-27b", ), prompt: "Hello", - generation: { maxTokens: 200, topK: 20 }, + maxTokens: 200, + topK: 20, providerOptions: { reasoningEffort: "future-effort", reasoning: { effort: "high", enabled: true, summary: "concise" }, diff --git a/packages/ai/test/provider/vercel-ai-gateway.recorded.test.ts b/packages/ai/test/provider/vercel-ai-gateway.recorded.test.ts index 0e692ad5f492..41d768291081 100644 --- a/packages/ai/test/provider/vercel-ai-gateway.recorded.test.ts +++ b/packages/ai/test/provider/vercel-ai-gateway.recorded.test.ts @@ -88,7 +88,7 @@ recorded.effect( ai.request({ model: VercelAIGateway.configure({ apiKey: "invalid-gateway-key" }).messages("anthropic/claude-sonnet-5.5"), prompt: "Hello", - generation: { maxTokens: 32 }, + maxTokens: 32, }), ).pipe(Effect.flip) expect(error.reason.http?.status).toBe(401) @@ -114,7 +114,7 @@ recorded.effect( { type: "text", text: "Reply with OK only." }, ], prompt: "Confirm.", - generation: { maxTokens: 32 }, + maxTokens: 32, providerOptions: { gateway: { only: ["anthropic"] } }, }) yield* LLMClient.generate(request) diff --git a/packages/ai/test/provider/xai-responses.test.ts b/packages/ai/test/provider/xai-responses.test.ts index 046797444c6f..613bcbc75706 100644 --- a/packages/ai/test/provider/xai-responses.test.ts +++ b/packages/ai/test/provider/xai-responses.test.ts @@ -79,7 +79,9 @@ describe("xAI Responses route", () => { ai.request({ model, prompt: "Hello", - generation: { topK: 20, presencePenalty: 0.5, frequencyPenalty: 0.5 }, + topK: 20, + presencePenalty: 0.5, + frequencyPenalty: 0.5, }), ) diff --git a/packages/ai/test/provider/zai-capabilities.recorded.test.ts b/packages/ai/test/provider/zai-capabilities.recorded.test.ts index 023c2d3facf4..39703db2d44c 100644 --- a/packages/ai/test/provider/zai-capabilities.recorded.test.ts +++ b/packages/ai/test/provider/zai-capabilities.recorded.test.ts @@ -17,7 +17,7 @@ recorded.effect.with( ai.request({ model: ZAI.configure({ apiKey, providerOptions: { thinking: { type: "disabled" } } }).chat("glm-5.3"), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ).pipe(Effect.flip) expect(error.reason._tag).toBe("InvalidRequest") @@ -40,7 +40,7 @@ for (const modelID of ["glm-4.7", "glm-5.2"]) { modelID, ), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text.replaceAll(",", "")).toContain("37887") @@ -64,7 +64,7 @@ for (const effort of ["none", "minimal", "low", "medium", "high", "xhigh", "max" ai.request({ model: ZAI.configure({ apiKey, providerOptions: { reasoningEffort: effort } }).chat("glm-5.2"), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text.replaceAll(",", "")).toContain("37887") @@ -95,7 +95,7 @@ recorded.effect.with( { type: "media", media: Media.bytes(bytes, "image/png") }, ]), ], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.text.toLowerCase()).toContain("jiggling restroom prison") @@ -117,7 +117,7 @@ recorded.effect.with( providerOptions: { reasoningEffort: "low", responseFormat: { type: "json_object" } }, }).chat("glm-5.3"), prompt: 'Return a JSON object with one key "city" set to the capital city of France.', - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(JSON.parse(response.text)).toEqual({ city: "Paris" }) @@ -146,7 +146,7 @@ recorded.effect.with( }, }), ], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }), ) expect(response.toolCalls).toMatchObject([{ name: "get_weather", input: { city: "Paris" } }]) diff --git a/packages/ai/test/provider/zai.recorded.test.ts b/packages/ai/test/provider/zai.recorded.test.ts index 7cab8fd780ca..3a73c00a8c0a 100644 --- a/packages/ai/test/provider/zai.recorded.test.ts +++ b/packages/ai/test/provider/zai.recorded.test.ts @@ -28,7 +28,7 @@ for (const effort of [undefined, "low", "high", "max"] as const) { const request = ai.request({ model: ZAI.configure({ apiKey, providerOptions: { reasoningEffort: effort } }).model("glm-5.3"), prompt: "What is 173 multiplied by 219? Reply with only the final integer.", - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const compiled = yield* compileRequest(request) expect(compiled.body.thinking).toBeUndefined() @@ -56,7 +56,7 @@ recorded.effect.with( prompt: "We have a budget of 38000 dollars for 219 trips costing 173 dollars each. Calculate whether that is affordable. If it is, use get_weather to look up the current weather in Paris. After receiving the result, report the weather in one short sentence.", tools: [weather], - generation: { maxTokens: 4096 }, + maxTokens: 4096, }) const first = yield* LLMClient.generate(request) expect(first.toolCalls).toMatchObject([{ name: "get_weather", input: { city: "Paris" } }]) diff --git a/packages/ai/test/provider/zai.test.ts b/packages/ai/test/provider/zai.test.ts index 427c653ee4b4..e7070dbfc0e6 100644 --- a/packages/ai/test/provider/zai.test.ts +++ b/packages/ai/test/provider/zai.test.ts @@ -80,7 +80,7 @@ it.effect("ZAI Chat retains native thinking fields and scopes tool streaming to ai.request({ model: provider.chat(modelID), prompt: "Hello", - generation: { maxTokens: 123 }, + maxTokens: 123, tools: [tool], providerOptions: { thinking: { type: "enabled", clear_thinking: false } }, }), diff --git a/packages/ai/test/recorded-scenarios.ts b/packages/ai/test/recorded-scenarios.ts index 1ca0ca4a26d3..dc6c99d3e92f 100644 --- a/packages/ai/test/recorded-scenarios.ts +++ b/packages/ai/test/recorded-scenarios.ts @@ -66,10 +66,8 @@ export const weatherToolLoopRequest = (input: { system: input.system ?? "Use the get_weather tool, then answer in one short sentence.", prompt: "What is the weather in Paris?", cache: "none", - generation: - input.temperature === false - ? { maxTokens: input.maxTokens ?? 80 } - : { maxTokens: input.maxTokens ?? 80, temperature: input.temperature ?? 0 }, + maxTokens: input.maxTokens ?? 80, + temperature: input.temperature === false ? undefined : (input.temperature ?? 0), }) export const goldenWeatherToolLoopRequest = (input: { @@ -250,7 +248,7 @@ const runGeneratedConversation = (context: GoldenScenarioContext, steps: Readonl tools: step.tools, toolChoice: step.toolChoice, providerOptions: step.providerOptions, - generation: generation(context, step.maxTokens ?? context.maxTokens ?? 80), + ...generation(context, step.maxTokens ?? context.maxTokens ?? 80), }), ) if (step.text !== undefined) assertAssistantText(response.text, step.text) @@ -317,7 +315,7 @@ const runImageToolResultScenario = (context: GoldenScenarioContext) => model: context.model, system: "Read images carefully. Reply only with the visible text, lowercase, no punctuation.", cache: "none", - generation: generation(context, context.maxTokens ?? 40), + ...generation(context, context.maxTokens ?? 40), messages: [ Message.user("Use the read_screenshot tool, then reply with the words shown."), Message.assistant([{ type: "tool-call", id: "call_screenshot_1", name: screenshotToolName, input: {} }]), diff --git a/packages/ai/test/route.test.ts b/packages/ai/test/route.test.ts index ca3fd1ce7494..e3b92312225b 100644 --- a/packages/ai/test/route.test.ts +++ b/packages/ai/test/route.test.ts @@ -35,7 +35,7 @@ describe("Route.with", () => { path: "/chat/completions", query: { keep: "patch", base: "1", patch: "1" }, }) - expect(route.defaults.headers).toEqual({ + expect(route.options?.headers).toEqual({ "x-base": "base", "x-override": "patch", "x-patch": "patch", @@ -48,7 +48,7 @@ describe("Route.with", () => { expect(route.providerMetadataKey).toBe("azure") expect(overridden.providerMetadataKey).toBe("custom-azure") - expect(overridden.defaults).not.toHaveProperty("providerMetadataKey") + expect(overridden.options).not.toHaveProperty("providerMetadataKey") }) }) diff --git a/packages/ai/test/sanitize.test.ts b/packages/ai/test/sanitize.test.ts index b9418ea2bc26..beb22ecde3f7 100644 --- a/packages/ai/test/sanitize.test.ts +++ b/packages/ai/test/sanitize.test.ts @@ -53,7 +53,7 @@ describe("sanitizeSurrogates", () => { system: "system", tools: [tool], messages: [...messages, Message.user("bad \uD800")], - generation: { maxTokens: 10 }, + maxTokens: 10, providerOptions: { nested: { list: ["a", "b"] } }, }) const sanitized = sanitizeRequest(request) @@ -64,7 +64,7 @@ describe("sanitizeSurrogates", () => { expect(sanitized.messages[2]).not.toBe(request.messages[2]) expect(sanitized.messages[2]).toEqual(Message.user("bad \uFFFD")) expect(sanitized.tools[0]).toBe(request.tools[0]) - expect(sanitized.generation).toBe(request.generation) + expect(sanitized.maxTokens).toBe(10) const input = request const output = sanitizeSurrogates(input) diff --git a/packages/ai/test/tool-runtime.test.ts b/packages/ai/test/tool-runtime.test.ts index 82b21c584c13..5db8b89979c7 100644 --- a/packages/ai/test/tool-runtime.test.ts +++ b/packages/ai/test/tool-runtime.test.ts @@ -1,16 +1,7 @@ import { describe, expect, test } from "bun:test" import { Content } from "@opencode/schema/tool" import { Effect, Schema, Stream } from "effect" -import { - ai, - GenerationOptions, - LLMEvent, - LLMResponse, - toDefinitions, - ToolCallPart, - ToolChoice, - ToolOutput, -} from "../src/effect.js" +import { ai, LLMEvent, LLMResponse, toDefinitions, ToolCallPart, ToolChoice, ToolOutput } from "../src/effect.js" import { Auth, LLMClient } from "../src/route.js" import * as AnthropicMessages from "../src/protocols/anthropic-messages.js" import * as OpenAIChat from "../src/protocols/openai-chat.js" @@ -118,7 +109,7 @@ describe("LLMClient tools", () => { yield* TestToolRuntime.runTools({ request: { ...baseRequest, - generation: GenerationOptions.make({ maxTokens: 50 }), + maxTokens: 50, toolChoice: ToolChoice.make("auto"), }, tools: [get_weather], diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md index 739c03d615bf..412d1898e9c2 100644 --- a/packages/app/AGENTS.md +++ b/packages/app/AGENTS.md @@ -41,7 +41,7 @@ This section is the single source for lifecycle state across `app`, `ui`, `sessi - A result that arrives late can still have side effects. When the user went back but the server already saved the change (a key, a credential), keep the state and emit only the refresh effect. When a timeout cuts a batch short, report the real outcome of the parts that finished and time out only the rest. - Serialize operations that touch the same data through one queue in the machine (`active` plus `pending`), including actions that look independent (steer, remove, reorder, undo). A side path that skips the queue can resurrect what another operation removed. - On an identity change (another session, server, window or credential), move to a new target with a new attempt instead of carrying the previous target's error, controller or result forward. -- On hot paths (scroll, pointer, resize, streaming), keep the machine allocation-free: return the same object when nothing changes, reuse event objects, and keep frozen singleton states. Benchmark with strobe as the Priorities section requires. +- On hot paths (scroll, pointer, resize, streaming), keep the machine allocation-free: return the same object when nothing changes, reuse event objects, and keep frozen singleton states. Benchmark with strobe as the Priorities section requires. Shared or frozen singleton states are safe only in signals and plain variables. Solid store writes (`setStore(path, obj)`, `reconcile`) merge into the object already in the store, so state written into a store never shares an object between two entries or with a module constant: replace it whole (`produce` replacement, or a signal), or build fresh objects with a factory (`createFileTreeState()`), and test through the real store with two entries. - Test the pure transition. Replay the bug's event sequence as a regression that fails on the old logic, then cover stale attempts and every exit (success, failure, timeout, cancel, dispose). Build events the way production builds them (through the real decoder, without fields the wire never carries), or the test passes on routes production never takes. These tests need no DOM, timers or mocks. - Name new driver inputs so they cannot collide with existing ones (`appState`, not a second `state`), and wire Solid reads of machine state into `` and `` with keyed matches or memos so a branch never reads a value another branch already narrowed. diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index 1a5279c6a799..4662fb3105fe 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -549,6 +549,27 @@ story("keeps blank browser tabs when adding tabs and selecting another panel", a await expect(root.getByTestId("browser-closes")).toHaveText("[]") }) +story("a new tab request that opened no blank tab leaves a later blank page's address alone", async ({ page }) => { + const root = page.getByTestId("browser-region-fixture") + const mac = await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform)) + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + const composer = root.getByRole("textbox", { name: "Composer", exact: true }) + await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible() + await root.getByRole("button", { name: "Beta", exact: true }).click() + await root.getByRole("button", { name: "First inventory", exact: true }).click() + await expect(root.getByRole("tab", { name: "Preview", exact: true })).toHaveAttribute("aria-selected", "true") + + // Main answers this request without a new blank tab. + await address.press(`${mac ? "Meta" : "Control"}+t`) + await expect(root.getByTestId("browser-opens")).toHaveText("1") + + // The page the agent blanks later must not take focus from the composer; a dispatched click leaves focus in place. + await composer.focus() + await root.getByRole("button", { name: "Blank page", exact: true }).dispatchEvent("click") + await expect(root.getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true") + await expect(composer).toBeFocused() +}) + story("reopens a closed browser tab with ⌘⇧T after the side panel and a session tab elsewhere", async ({ page }) => { const root = page.getByTestId("browser-region-fixture") const mac = await page.evaluate(() => /Mac|iPhone|iPad|iPod/.test(navigator.platform)) diff --git a/packages/app/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts index 58168ac5c57b..9c6a3376c51c 100644 --- a/packages/app/component-tests/browser-pane.spec.ts +++ b/packages/app/component-tests/browser-pane.spec.ts @@ -113,24 +113,52 @@ story("paints a still of the page in place of the native view while a resize han const visible = await handle.evaluate((element) => { const read = () => document.querySelector('[data-testid="native-Alpha"]')?.getAttribute("data-visible") const box = element.getBoundingClientRect() - const at = { bubbles: true, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 } - element.dispatchEvent(new MouseEvent("mousedown", { ...at, detail: 1 })) - document.dispatchEvent(new MouseEvent("mouseup", at)) + const at = { bubbles: true, pointerId: 1, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 } + element.dispatchEvent(new PointerEvent("pointerdown", { ...at, button: 0 })) + document.dispatchEvent(new PointerEvent("pointerup", at)) const click = read() - element.dispatchEvent(new MouseEvent("mousedown", { ...at, detail: 1 })) + element.dispatchEvent(new PointerEvent("pointerdown", { ...at, button: 0 })) const pressed = read() - document.dispatchEvent(new MouseEvent("mousemove", { ...at, clientX: at.clientX - 40 })) + document.dispatchEvent(new PointerEvent("pointermove", { ...at, clientX: at.clientX - 40 })) return { click, pressed, dragging: read() } }) expect(visible).toEqual({ click: "true", pressed: "true", dragging: "false" }) await expect(still).toBeVisible() - await page.mouse.up() + await handle.evaluate((element) => { + const box = element.getBoundingClientRect() + document.dispatchEvent( + new PointerEvent("pointerup", { bubbles: true, pointerId: 1, clientX: box.x, clientY: box.y }), + ) + }) await expect(native).toHaveAttribute("data-visible", "true") await expect(still).toHaveCount(0) }) +story("shows the native view again when the window loses focus mid-drag", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const handle = root.getByTestId("pane-resize-handle") + const native = root.getByTestId("native-Alpha") + const still = root.locator("#browser-panel img") + + // Alt+Tab mid-drag delivers no pointerup; the page must not stay locked behind a still. + await handle.evaluate((element) => { + const box = element.getBoundingClientRect() + const at = { bubbles: true, pointerId: 1, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 } + element.dispatchEvent(new PointerEvent("pointerdown", { ...at, button: 0 })) + document.dispatchEvent(new PointerEvent("pointermove", { ...at, clientX: at.clientX - 40 })) + }) + await expect(native).toHaveAttribute("data-visible", "false") + await expect(handle).toHaveAttribute("data-dragging", "") + + await handle.evaluate(() => window.dispatchEvent(new FocusEvent("blur"))) + await expect(native).toHaveAttribute("data-visible", "true") + await expect(still).toHaveCount(0) + await expect(handle).not.toHaveAttribute("data-dragging") + expect(await handle.evaluate(() => document.body.style.userSelect)).toBe("") +}) + story("never flies a still of a page the tab has navigated away from", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const motion = root.getByRole("button", { name: "Toggle panel motion", exact: true }) @@ -212,6 +240,33 @@ story("keeps a still of the page under floating content that covers it", async ( await expect(root.getByText("Captures: 1", { exact: true })).toBeVisible() }) +story( + "freezes on the latest capture when floating content closes and reopens before a capture lands", + async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const popover = root.getByRole("button", { name: "Toggle popover", exact: true }) + const still = root.locator("#browser-panel img") + const native = root.getByTestId("native-Alpha") + await page.emulateMedia({ reducedMotion: "reduce" }) + await root.getByRole("button", { name: "Hold capture", exact: true }).click() + await popover.click() + await expect(root.getByText("Captures: 1", { exact: true })).toBeVisible() + await popover.click() + await expect(page.locator("[data-popper-positioner]")).toHaveCount(0) + // The pane measures the overlap on the next animation frame; nothing on screen changes while the capture is held. + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))) + await popover.click() + await expect(root.getByText("Captures: 2", { exact: true })).toBeVisible() + + // Both captures land in order; the first one belongs to the cover that already closed. + await root.getByRole("button", { name: "Release capture", exact: true }).click() + await expect(native).toHaveAttribute("data-visible", "false") + await expect(still).toBeVisible() + // The fixture draws each capture a pixel wider: the second one is 5 pixels wide. + await expect(still).toHaveJSProperty("naturalWidth", 5) + }, +) + story("keeps a still of the page under an open dialog instead of blanking the pane", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const still = root.locator("#browser-panel img") @@ -241,6 +296,26 @@ story("keeps a still of the page under an open dialog instead of blanking the pa await expect(root.getByText("Captures: 1", { exact: true })).toBeVisible() }) +story("hides the native page under a dialog even when its still never arrives", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const native = root.getByTestId("native-Alpha") + const toggle = root.getByRole("button", { name: "Toggle dialog", exact: true }) + await page.clock.install() + await root.getByRole("button", { name: "Hold capture", exact: true }).click() + await toggle.click() + await page.clock.runFor(100) + await expect(native).toHaveAttribute("data-visible", "true") + + // The capture never settles: after its timeout the page hides over the box background instead of the dialog. + await page.clock.runFor(5_000) + await expect(native).toHaveAttribute("data-visible", "false") + await expect(root.locator("#browser-panel img")).toHaveCount(0) + + await toggle.click() + await page.clock.runFor(100) + await expect(native).toHaveAttribute("data-visible", "true") +}) + story("comments on a picked element over a still of the page", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("combobox", { name: "Picked element scenario" }).selectOption("zoomed") @@ -310,6 +385,31 @@ story("cancels the picker and a comment with Escape", async ({ page }) => { await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") }) +story("leaves the picker off and Escape to the app when main never answers", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) + await root.getByRole("button", { name: "Drop picker requests", exact: true }).click() + await picker.click() + await expect(picker).toHaveAttribute("aria-pressed", "false") + + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + await address.click() + await expect(address).toBeFocused() + await address.press("Escape") + await expect(address).not.toBeFocused() +}) + +story("replaces an open page note with the comment for an element picked meanwhile", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.locator('[data-component="browser-address"]').hover() + await root.getByRole("button", { name: "Add page to session", exact: true }).click() + await expect(root.locator('[data-slot="browser-comment-editor"] textarea')).toBeFocused() + + await root.getByRole("button", { name: "Pick element", exact: true }).click() + await expect(root.locator('[data-component="browser-comment"]')).toHaveCount(1) + await expect(root.locator('[data-slot="browser-comment-editor"]')).toContainText("button.primary") +}) + story("cleans up the originating session's picker and comment after a session switch", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const picker = root.getByRole("button", { name: "Select an element to comment on", exact: true }) @@ -541,6 +641,14 @@ story("keeps the submitted URL visible until the browser reports navigation", as await expect(address).toHaveValue("https://example.com/") await expect(root.getByText("Open a page", { exact: true })).toBeHidden() + // Focusing and leaving the field before the browser reports keeps the submitted address. + await address.focus() + await expect(address).toHaveValue("https://example.com/") + await address.press("Escape") + await expect(address).not.toBeFocused() + await expect(address).toHaveValue("https://example.com/") + await expect(root.getByText("Open a page", { exact: true })).toBeHidden() + await root.getByRole("button", { name: "Complete navigation", exact: true }).click() await expect(root.getByTestId("native-Alpha")).toHaveAttribute("data-visible", "true") await expect(address).toHaveValue("https://example.com/") @@ -792,6 +900,19 @@ story("shows the page's cookies in the site information and clears them", async await expect(site).toContainText("0 cookies in use") }) +story("says a failed cookie read failed and reads again on retry", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + await root.getByRole("button", { name: "Fail next site read", exact: true }).click() + await root.getByRole("button", { name: "Site information", exact: true }).click() + const site = page.getByRole("dialog") + await expect(site).toContainText("Request failed") + const retry = site.getByRole("button", { name: "Try again", exact: true }) + await expect(retry).toBeEnabled() + await retry.click() + await expect(site).toContainText("3 cookies in use") + await expect(site.getByRole("button", { name: "Clear", exact: true })).toBeEnabled() +}) + story("zooms the page from the browser options in view and keeps its zoom in the address field", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") const options = root.getByRole("button", { name: "Browser options", exact: true }) diff --git a/packages/app/component-tests/composer.spec.ts b/packages/app/component-tests/composer.spec.ts index d40c18969154..73358c2bb21f 100644 --- a/packages/app/component-tests/composer.spec.ts +++ b/packages/app/component-tests/composer.spec.ts @@ -191,6 +191,30 @@ story( await expect(composer).toHaveCSS("height", `${restoredHeight}px`) await expect(component.getByRole("img", { name: "layout.png", exact: true })).toBeVisible() await expect(component.getByText("Keep the search separate from the draft", { exact: true })).toBeVisible() + + // A click elsewhere cancels the preview too; it used to leave the previewed prompt in place of the draft. + await input.press("Shift+ArrowUp") + await expect(input).toHaveText("Explain the latest changes") + await page.mouse.click(1, 1) + await expect(options).toHaveCount(0) + await expect(input).toBeEmpty() + await expect(component.getByRole("img", { name: "layout.png", exact: true })).toBeVisible() + await expect(component.getByText("Keep the search separate from the draft", { exact: true })).toBeVisible() + + // A click into the draft keeps the previewed prompt to edit. + await input.press("Shift+ArrowUp") + await expect(search).toBeFocused() + await input.click() + await expect(options).toHaveCount(0) + await expect(input).toHaveText("Explain the latest changes") + + // Opening the file picker while browsing keeps the way back to the draft; it used to end browsing. + await input.fill("") + await input.press("ArrowUp") + await expect(input).toHaveText("Explain the latest changes") + await input.press("ControlOrMeta+u") + await input.press("ArrowDown") + await expect(input).toBeEmpty() }, ) diff --git a/packages/app/component-tests/debug-bar.spec.ts b/packages/app/component-tests/debug-bar.spec.ts index 43ad2b90ebd6..7afec7b163c1 100644 --- a/packages/app/component-tests/debug-bar.spec.ts +++ b/packages/app/component-tests/debug-bar.spec.ts @@ -52,6 +52,37 @@ story("the debug bar stays open across a remount until its close button hides it expect(result).toEqual({ opened: true, saved: { visible: false, motion: false }, reopened: false }) }) +story("running memory diagnostics pin the bar without a close button, and its Knobs still open", async ({ page }) => { + const result = await page.evaluate(async (modules) => { + const { mountPlugins, until } = await import(modules.fixture) + const debug = await import(modules.debug) + const definition = { ...debug.default, id: "debug", windowEntry: () => import(modules.renderer) } + const memory = { state: () => ({ on: true, env: false }), set: async () => undefined, on: () => () => {} } + + // The user hid the bar and left the Knobs open before turning diagnostics on. + const host = mountPlugins({ + definitions: [definition], + stored: { "plugin.debug.bar": { visible: false, motion: true } }, + ipc: (token: { readonly id: string }) => (token.id === "debug.memory" ? memory : undefined), + }) + + host.release() + await until(() => host.container.querySelector("aside") !== null) + await until(() => document.querySelector('button[aria-label="Close Knobs"]') !== null) + + const view = { + close: host.container.querySelector('button[aria-label="Hide debug bar"]') !== null, + knobs: document.querySelector('button[aria-label="Close Knobs"]') !== null, + } + + host.unmount() + + return view + }, modules) + + expect(result).toEqual({ close: false, knobs: true }) +}) + story("a feature page's Enabled switch turns that feature on after another feature's page", async ({ page }) => { const result = await page.evaluate( async (modules) => { diff --git a/packages/app/component-tests/file-icon.spec.ts b/packages/app/component-tests/file-icon.spec.ts new file mode 100644 index 000000000000..aae0931cea7f --- /dev/null +++ b/packages/app/component-tests/file-icon.spec.ts @@ -0,0 +1,14 @@ +import { expect, story } from "../../stories/playwright/story" + +story("shows the fallback glyph when an icon chunk fails to load", async ({ mount, page }) => { + await page.route("**/file-types/typescript.svg*", (route) => route.abort()) + const root = await mount("components-file-icon--samples") + + await expect( + root + .locator("div") + .filter({ hasText: /^index\.ts$/ }) + .locator("use"), + ).toHaveAttribute("href", "#file-icon-Document") + await expect(page.locator("#file-icon-sprite > #file-icon-Document")).toHaveCount(1) +}) diff --git a/packages/app/component-tests/focus-ring.spec.ts b/packages/app/component-tests/focus-ring.spec.ts index 4f6cfd3d4e74..f655bd0456dc 100644 --- a/packages/app/component-tests/focus-ring.spec.ts +++ b/packages/app/component-tests/focus-ring.spec.ts @@ -24,6 +24,35 @@ story("keeps the ring on a menu trigger after a keyboard open", async ({ mount, await expect(trigger).toHaveCSS("outline-style", "solid") }) +story("keeps the ring on a menu trigger opened from code after a pointer open", async ({ mount, page }) => { + await mount("ui-menu--programmatic-and-non-modal") + const trigger = page.getByRole("button", { name: "Controlled" }) + + await trigger.click() + await expect(page.getByRole("menuitem", { name: "Rename" })).toBeVisible() + await page.keyboard.press("Escape") + await expect(page.getByRole("menuitem", { name: "Rename" })).toHaveCount(0) + await page.getByRole("button", { name: "Open from code" }).click() + await expect(page.getByRole("menuitem", { name: "Rename" })).toBeVisible() + await page.keyboard.press("Escape") + await expect(trigger).toBeFocused() + await expect(trigger).toHaveCSS("outline-style", "solid") +}) + +story("leaves focus where an outside click put it when a non-modal menu closes", async ({ mount, page }) => { + await mount("ui-menu--programmatic-and-non-modal") + const trigger = page.getByRole("button", { name: "Non-modal" }) + + await trigger.click() + await expect(page.getByRole("menuitem", { name: "Pin" })).toBeVisible() + await page.mouse.click(4, 300) + await expect(page.getByRole("menuitem", { name: "Pin" })).toHaveCount(0) + // The close focus restore has run once the story counts it; the click on empty space left focus on the body. + await expect(page.getByLabel("Non-modal focus restores")).toHaveText("1") + expect(await page.evaluate(() => document.activeElement === document.body)).toBe(true) + await expect(trigger).not.toBeFocused() +}) + story("returns focus to a dialog's trigger without a ring after a pointer open", async ({ mount, page }) => { await mount("ui-dialog--opened-from-button") const trigger = page.getByRole("button", { name: "Choose model" }) diff --git a/packages/app/component-tests/grow.fixture.tsx b/packages/app/component-tests/grow.fixture.tsx new file mode 100644 index 000000000000..88544089c104 --- /dev/null +++ b/packages/app/component-tests/grow.fixture.tsx @@ -0,0 +1,42 @@ +import { createStore } from "solid-js/store" +import { render } from "solid-js/web" +import { Grow } from "../src/session/composer/spring-height" + +const [state, setState] = createStore({ when: false, instant: false, closed: 0, mounts: 0 }) + +const host = document.createElement("div") + +/** One `Grow` with a counted child, and the number of times it reported a close. */ +export function mountGrow() { + host.dataset.testid = "grow-fixture" + document.body.appendChild(host) + render(() => { + function Child() { + setState("mounts", (count) => count + 1) + + return ( +
+ Grown +
+ ) + } + + return ( + <> + {state.closed} + {state.mounts} + setState("closed", (count) => count + 1)}> + + + + ) + }, host) +} + +/** Sets `when` and `instant` together, in one batch. */ +export const setGrow = (patch: { when?: boolean; instant?: boolean }) => setState(patch) + +/** Detaches the fixture the way an inactive session tab detaches its timeline, with every effect still alive. */ +export const detach = () => host.remove() + +export const attach = () => document.body.appendChild(host) diff --git a/packages/app/component-tests/grow.spec.ts b/packages/app/component-tests/grow.spec.ts new file mode 100644 index 000000000000..a4bb083fcade --- /dev/null +++ b/packages/app/component-tests/grow.spec.ts @@ -0,0 +1,74 @@ +import type { Page } from "@playwright/test" +import { expect, sourceURL, story } from "../../stories/playwright/story" + +const fixture = sourceURL(new URL("./grow.fixture.tsx", import.meta.url)) + +story.beforeEach(async ({ mount, page }) => { + // Any story loads the app's styles; the fixture mounts a `Grow` beside it. + await mount("ui-line-comment--editor") + await page.evaluate(async (fixture) => { + const { mountGrow } = await import(fixture) + mountGrow() + }, fixture) +}) + +// What a grow leaves on its wrapper while it moves, and clears when it lands. +const motion = (page: Page) => + page + .getByTestId("grow-child") + .locator("..") + .evaluate((el) => ({ moving: el.hasAttribute("data-moving"), height: el.style.height, opacity: el.style.opacity })) + +const still = { moving: false, height: "", opacity: "" } + +story("keeps its children mounted when it reopens and turns instant in one batch mid-close", async ({ page }) => { + const root = page.getByTestId("grow-fixture") + await page.evaluate(async (fixture) => { + const { setGrow } = await import(fixture) + setGrow({ when: true }) + }, fixture) + await expect(root.getByTestId("grow-child")).toBeVisible() + await expect.poll(() => motion(page)).toEqual(still) + + const closing = await page.evaluate(async (fixture) => { + const { setGrow } = await import(fixture) + setGrow({ when: false }) + + for (let i = 0; i < 3; i++) await new Promise((resolve) => requestAnimationFrame(resolve)) + const moving = !!document.querySelector('[data-testid="grow-fixture"] [data-moving]') + // `instant` is written first, so anything reacting to it alone runs before `when` reopens. + setGrow({ instant: true, when: true }) + + return moving + }, fixture) + + expect(closing).toBe(true) + await expect(root.getByTestId("grow-closed")).toHaveText("0") + await expect(root.getByTestId("grow-mounts")).toHaveText("1") + expect(await motion(page)).toEqual(still) +}) + +story("finishes opening and closing while detached like a cached session tab", async ({ page }) => { + const root = page.getByTestId("grow-fixture") + + const toggleDetached = (when: boolean) => + page.evaluate( + async ({ fixture, when }) => { + const { attach, detach, setGrow } = await import(fixture) + detach() + setGrow({ when }) + + for (let i = 0; i < 3; i++) await new Promise((resolve) => requestAnimationFrame(resolve)) + attach() + }, + { fixture, when }, + ) + + await toggleDetached(true) + await expect(root.getByTestId("grow-child")).toBeVisible() + expect(await motion(page)).toEqual(still) + + await toggleDetached(false) + await expect(root.getByTestId("grow-closed")).toHaveText("1") + await expect(root.getByTestId("grow-child")).toHaveCount(0) +}) diff --git a/packages/app/component-tests/image-preview.spec.ts b/packages/app/component-tests/image-preview.spec.ts index 6be695d24c02..1c5b73f4d32c 100644 --- a/packages/app/component-tests/image-preview.spec.ts +++ b/packages/app/component-tests/image-preview.spec.ts @@ -25,6 +25,79 @@ story("takes the page's clicks as soon as the image preview closes mid-flight", await expect(clickPage(page)).resolves.toBe(true) }) +story("a close mid-flight after the origin is gone fades out without landing at rest", async ({ mount, page }) => { + await mount("components-image-preview--from-message") + await open(page) + const preview = page.locator('[data-component="image-preview"]') + await preview.waitFor({ state: "attached" }) + + // In the page, so the close lands mid-flight however slow the runner: the origin goes the moment the flight starts, + // and Escape follows. Every stage the preview shows from then on is recorded. + const stages = await preview.evaluateHandle((element: HTMLElement) => { + const seen: (string | undefined)[] = [] + let closed = false + + const close = () => { + if (closed || element.dataset.stage === "pending") return + closed = true + document.querySelector('[data-story-image="inline"]')?.remove() + document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })) + } + + new MutationObserver(() => { + if (closed) seen.push(element.dataset.stage) + close() + }).observe(element, { attributes: true, attributeFilter: ["data-stage"] }) + close() + + return seen + }) + + await expect(preview).toHaveCount(0) + const seen = await stages.jsonValue() + expect(seen).toContain("closing") + expect(seen).not.toContain("rest") +}) + +story("a pan whose release never reaches the preview stops following the pointer", async ({ mount, page }) => { + await mount("components-image-preview--from-message") + await open(page) + const body = page.locator('[data-slot="image-preview-body"]') + const image = page.locator('[data-slot="image-preview-image"]') + await expect(page.locator('[data-component="image-preview"]')).toHaveAttribute("data-stage", "rest") + await image.dblclick() + await expect(body).toHaveAttribute("data-zoomed", "") + + const box = await body.boundingBox() + + if (!box) throw new Error("the preview body is not laid out") + const x = box.x + box.width / 2 + const y = box.y + box.height / 2 + + const pointer = await body.evaluateHandle((element: HTMLElement) => { + const seen = { id: -1 } + element.addEventListener("pointerdown", (event) => (seen.id = event.pointerId), { once: true }) + + return seen + }) + + await page.mouse.move(x, y) + await page.mouse.down() + await page.mouse.move(x + 30, y + 10) + await expect(body).toHaveAttribute("data-dragging", "") + + // The pointer loses capture, as when the window loses focus mid-drag, and the button comes up outside the body. + await body.evaluate((element, seen) => element.releasePointerCapture(seen.id), pointer) + await page.mouse.move(x, box.y / 2) + await page.mouse.up() + const transform = await image.evaluate((element) => element.style.transform) + + await page.mouse.move(x, y) + await page.mouse.move(x - 60, y - 30) + await expect(body).not.toHaveAttribute("data-dragging") + expect(await image.evaluate((element) => element.style.transform)).toBe(transform) +}) + async function open(page: Page) { await page.locator('[data-story-image="inline"]').click() } diff --git a/packages/app/component-tests/input-surfaces.spec.ts b/packages/app/component-tests/input-surfaces.spec.ts index fa2fde9473fb..1cce08660c43 100644 --- a/packages/app/component-tests/input-surfaces.spec.ts +++ b/packages/app/component-tests/input-surfaces.spec.ts @@ -125,6 +125,32 @@ story("select fields come in the text input sizes and default to the inline trig await expect(fields.nth(3)).toHaveCSS("box-shadow", "none") }) +story( + "a select previews the highlighted option, reverts it on Escape, and keeps the chosen one", + async ({ mount, page }) => { + const root = await mount("ui-select--highlight-preview") + const trigger = root.locator('[data-component="select-v2"]') + const preview = root.locator('[data-slot="select-preview"]') + + await trigger.click() + await page.getByRole("option", { name: "Cherry", exact: true }).hover() + await expect(preview).toHaveText("Showing Cherry") + await page.keyboard.press("Escape") + await expect(page.getByRole("listbox")).toHaveCount(0) + await expect(preview).toHaveText("Showing Apple") + + await trigger.click() + const banana = page.getByRole("option", { name: "Banana", exact: true }) + await banana.hover() + await expect(preview).toHaveText("Showing Banana") + await banana.click() + await expect(page.getByRole("listbox")).toHaveCount(0) + await expect(trigger).toContainText("Banana") + // Choosing the previewed option must not run its undo afterwards. + await expect(preview).toHaveText("Showing Banana") + }, +) + story("compact checkboxes use the design system control states and focus ring", async ({ mount, page }) => { const root = await mount("ui-checkbox--compact") diff --git a/packages/app/component-tests/line-comment.spec.ts b/packages/app/component-tests/line-comment.spec.ts index d8c204d7a0de..d7fc85e8956e 100644 --- a/packages/app/component-tests/line-comment.spec.ts +++ b/packages/app/component-tests/line-comment.spec.ts @@ -44,6 +44,65 @@ story("autosizes compact comments without native field-sizing", async ({ mount, await expect.poll(() => textarea.evaluate((element) => element.scrollHeight > element.clientHeight)).toBe(true) }) +story("Enter on a list whose refined search still runs waits instead of picking a stale row", async ({ mount }) => { + const component = await mount("ui-line-comment--editor-with-mentions") + const textarea = component.getByRole("textbox") + const items = component.locator('[data-slot="line-comment-v2-mention-item"]') + // From the keyboard, so the pointer does not rest over the list that opens and highlight a row. + const finish = () => component.getByRole("button", { name: "Finish search", exact: true }).press("Enter") + + await textarea.fill("Check @src") + await finish() + await expect(items).toHaveText(["src/app.ts", "src/api.ts", "src/server.ts"]) + + await textarea.pressSequentially("/a") + await textarea.press("Enter") + await expect(textarea).toHaveValue("Check @src/a") + + await finish() + await expect(items).toHaveText(["src/app.ts", "src/api.ts"]) + await textarea.press("Enter") + await expect(textarea).toHaveValue("Check @src/app.ts ") + await expect(items).toHaveCount(0) +}) + +story("Enter sends at once while a search runs with no list on screen", async ({ mount }) => { + const component = await mount("ui-line-comment--editor-with-mentions") + const textarea = component.getByRole("textbox") + + await textarea.fill("Mail a@b.com") + await textarea.press("Enter") + await expect(component.getByRole("status", { name: "Editor result" })).toHaveText("Submitted: Mail a@b.com") +}) + +story("Escape after a bare @ cancels the comment", async ({ mount }) => { + const component = await mount("ui-line-comment--editor-with-mentions") + const textarea = component.getByRole("textbox") + + await textarea.fill("see @") + await textarea.press("Escape") + await expect(component.getByRole("status", { name: "Editor result" })).toHaveText("Cancelled") +}) + +story( + "Escape in a popover's comment field cancels the comment, and on its buttons closes the popover", + async ({ mount, page }) => { + const component = await mount("ui-line-comment--editor-in-popover") + const popover = component.locator('[data-component="popover-content"]') + const textarea = popover.getByRole("textbox") + + await component.getByRole("button", { name: "Open editor", exact: true }).click() + await textarea.fill("Keep this") + await textarea.press("Escape") + await expect(component.getByRole("status", { name: "Editor result" })).toHaveText("Cancelled") + await expect(popover).toBeVisible() + + await popover.getByRole("button", { name: "Cancel", exact: true }).focus() + await page.keyboard.press("Escape") + await expect(popover).toHaveCount(0) + }, +) + story("completes compact optional comments with or without text", async ({ mount }) => { const component = await mount("ui-line-comment--editor", { args: { variant: "compact", allowEmpty: true } }) const action = component.getByRole("button", { name: "Comment", exact: true }) diff --git a/packages/app/component-tests/list.spec.ts b/packages/app/component-tests/list.spec.ts new file mode 100644 index 000000000000..dd8123ab7825 --- /dev/null +++ b/packages/app/component-tests/list.spec.ts @@ -0,0 +1,7 @@ +import { expect, story } from "../../stories/playwright/story" + +story("reports a rejected async load instead of no results", async ({ mount }) => { + const root = await mount("components-list--load-failed") + + await expect(root.locator('[data-slot="list-message"]')).toHaveText("Failed to load results") +}) diff --git a/packages/app/component-tests/new-session-wordmark.spec.ts b/packages/app/component-tests/new-session-wordmark.spec.ts index e068db191d98..751bc31b01e3 100644 --- a/packages/app/component-tests/new-session-wordmark.spec.ts +++ b/packages/app/component-tests/new-session-wordmark.spec.ts @@ -46,6 +46,38 @@ story("shows a static pin board with reduced motion", async ({ mount, page }) => expect(await requestedFrames(page)).toBe(0) }) +story("the lodger pops the pin board out and packs it back into the e", async ({ mount, page }) => { + await page.emulateMedia({ reducedMotion: "no-preference" }) + await mount("app-new-session-wordmark--flat") + const grip = page.locator('[data-slot="wordmark-lodger-grip"]') + const flat = page.locator('[data-slot="wordmark-flat"]') + const board = page.locator("canvas") + await expect(board).toHaveCount(0) + + // Pulling the lodger well past its slip distance pops every pin out into the board. + const hole = (await grip.boundingBox())! + await page.mouse.move(hole.x + hole.width / 2, hole.y + hole.height / 2) + await page.mouse.down() + await page.mouse.move(hole.x + hole.width / 2 + 160, hole.y + hole.height / 2 + 80, { steps: 12 }) + await page.mouse.up() + await expect(flat).toBeHidden() + await expect(board).not.toHaveCount(0) + await expect.poll(() => requestedFrames(page)).toBe(0) + + // Carrying it from its perch back into the "e" reels the pins in and tucks the lodger away. + const lodger = (await page.locator('[data-slot="wordmark-lodger"]').boundingBox())! + const unit = lodger.width / 234 + const perch = (await grip.boundingBox())! + await page.mouse.move(perch.x + perch.width / 2, perch.y + perch.height / 2) + await page.mouse.down() + await page.mouse.move(perch.x + perch.width / 2 - 24 * unit, perch.y + perch.height / 2 - 16 * unit, { steps: 12 }) + await page.mouse.up() + await expect(board).toHaveCount(0) + await expect(flat).toBeVisible() + await expect.poll(() => requestedFrames(page)).toBe(0) + await expect(grip).toBeVisible() +}) + // Reads the on-screen pixel at a grid cell. The board may be drawn with WebGL, whose canvas cannot be read // back once presented, so the pixel comes from a screenshot decoded in the page. async function pinPixel(page: Page, cell = PIN) { diff --git a/packages/app/component-tests/pairing.spec.ts b/packages/app/component-tests/pairing.spec.ts new file mode 100644 index 000000000000..6123a645215f --- /dev/null +++ b/packages/app/component-tests/pairing.spec.ts @@ -0,0 +1,26 @@ +import { expect, story } from "../../stories/playwright/story" + +story("a Keep screen active read that fails offers Try again and keeps the switch enabled", async ({ mount, page }) => { + // The page reads three more times, 1, 2 and 4 seconds apart, before it shows the failure. + await page.clock.install() + const component = await mount("plugins-pairing--screen-setting-fails") + const toggle = component.getByRole("switch", { name: "Keep screen active", exact: true }) + const error = component.getByRole("alert").filter({ hasText: "Could not update the screen activity setting." }) + const retry = component.getByRole("button", { name: "Try again", exact: true }) + + await expect(toggle).toBeDisabled() + await page.clock.runFor(8_000) + await expect(error).toBeVisible() + await expect(toggle).toBeEnabled() + await expect(toggle).not.toBeChecked() + + await retry.click() + await expect(error).toHaveCount(0) + await expect(retry).toHaveCount(0) + await expect(toggle).toBeEnabled() + + await toggle.focus() + await toggle.press("Space") + await expect(toggle).toBeChecked() + await expect(toggle).toBeEnabled() +}) diff --git a/packages/app/component-tests/plugin-host.fixture.tsx b/packages/app/component-tests/plugin-host.fixture.tsx index 1c0e17503a26..e54ccb77587a 100644 --- a/packages/app/component-tests/plugin-host.fixture.tsx +++ b/packages/app/component-tests/plugin-host.fixture.tsx @@ -1,5 +1,5 @@ import type { PluginInfo, SessionMessageInfo } from "@opencode/client/promise" -import { DialogProvider } from "@opencode/ui/context/dialog" +import { DialogProvider, useDialog } from "@opencode/ui/context/dialog" import { Menu } from "@opencode/ui/menu" import { Toast } from "@opencode/ui/toast" import { @@ -23,7 +23,9 @@ import type { BuiltinLayout, BuiltinLocale } from "@opencode/plugin/gui/builtin" import { createComponent, createMemo, + createRoot, createSignal, + ErrorBoundary, getOwner, onCleanup, runWithOwner, @@ -36,7 +38,7 @@ import { render } from "solid-js/web" import { PlatformProvider, type Platform } from "@/runtime/platform/platform" import { Persist, persisted } from "@/runtime/persistence/storage" import { ServerScope } from "@/runtime/server/scope" -import { PluginHostProvider, usePluginHost, type HostApiFactories } from "../src/runtime/plugin/host" +import { PluginHostProvider, usePluginHost, type HostApiFactories, type PluginInput } from "../src/runtime/plugin/host" import { createHostApis } from "../src/runtime/plugin/host-apis" import type { Bridge, Entry } from "@opencode/plugin/gui/host" import { createRegion, RegionContent } from "../src/runtime/plugin/panels" @@ -45,7 +47,7 @@ import type { SessionModel } from "../src/session/model" import { createClosedTabs } from "../src/runtime/plugin/closed-tabs" import { PluginLinks, PluginSlot, PluginThemes } from "../src/runtime/plugin/render" import { Markdown } from "@opencode/session-ui/markdown" -import { ThemeProvider, useTheme } from "@opencode/ui/theme/context" +import { ThemeProvider, useTheme, type ColorScheme } from "@opencode/ui/theme/context" import { persistedHandle } from "../src/runtime/plugin/stores" import { LanguageProvider } from "../src/runtime/i18n/language" import { ExtensionPlugins } from "../src/runtime/plugin/extension-plugins" @@ -80,7 +82,7 @@ type Captured = { apis?: ReturnType } /** A value the fixture's storage holds as JSON. */ type Json = string | number | boolean | null | readonly Json[] | { readonly [key: string]: Json } -export { createComponent, createMemo, createSignal, getOwner, onCleanup, runWithOwner } +export { createComponent, createMemo, createRoot, createSignal, getOwner, onCleanup, runWithOwner, useDialog } const layout: BuiltinLayout = { narrow: () => false, @@ -217,7 +219,7 @@ export function mountPluginHost() { reload: () => hosts[0]?.reload("fixture"), disable: () => setDisabled(new Set(["fixture"])), enable: () => setDisabled(new Set()), - status: () => hosts[0]?.state.status.fixture, + status: () => hosts[0]?.status("fixture"), /** Contributions the host holds for a registry; readable after the host unmounts. */ entries: (registry: string) => hosts[0]?.state.entries[registry]?.length ?? 0, } @@ -237,6 +239,10 @@ export function mountPlugins(input: { plugins?: readonly PluginInfo[] /** The client of an Ipc while main provides it, as a desktop window's bridge reports it. Omitted: the web. */ ipc?: (token: Ipc) => IpcClient | undefined + /** Whether main failed to answer the window's subscribe to an Ipc. */ + ipcFailed?: (token: Ipc) => boolean + /** What a plugin's GUI reads of its server plugin. Omitted: every plugin is a built-in. */ + plugin?: (id: string) => PluginInput | undefined }) { const held = Promise.withResolvers() const saved = { ...input.stored } @@ -299,25 +305,38 @@ export function mountPlugins(input: { ) } + // Errors that escape the host to the boundary above it, which in the app replaces the whole window. + const escaped: string[] = [] + const dispose = render( () => ( - - - - {/* With a bridge, main's plugin manager holds the enable settings, as in a desktop window. */} - - - - - - + { + escaped.push(String(error)) + + return null + }} + > + + + + {/* With a bridge, main's plugin manager holds the enable settings, as in a desktop window. */} + + + + + + + ), container, ) @@ -337,9 +356,11 @@ export function mountPlugins(input: { define: (next: readonly Entry[]) => setDefinitions(next), reload: (id: string) => hosts[0]?.reload(id), ready: () => hosts[0]?.ready() ?? false, - status: (id: string) => hosts[0]?.state.status[id], - failure: (id: string) => hosts[0]?.state.failures[id], + status: (id: string) => hosts[0]?.status(id), + failure: (id: string) => hosts[0]?.failure(id), entries: (registry: string) => hosts[0]?.state.entries[registry]?.length ?? 0, + /** Errors that reached the error boundary above the host. */ + escaped: () => [...escaped], } } @@ -673,7 +694,7 @@ export function mountSessionRegion(input: { leave: () => setRouted(false), /** The session each composer attachment reached, in order. */ attached, - status: (id: string) => hosts[0]?.state.status[id], + status: (id: string) => hosts[0]?.status(id), unmount: () => { dispose() container.remove() @@ -685,7 +706,8 @@ export function mountSessionRegion(input: { * Mounts the real host's theme contributions into the app's theme provider, as the window does. `options` reads the * theme picker's choices as Settings › Appearance lists them; `disable` and `enable` toggle a plugin as * Extensions › Plugins does. With `pending`, the plugin list has not arrived until `load()`. `applied` counts the - * provider's `onThemeApplied` calls, which show a desktop window. + * provider's `onThemeApplied` calls, which show a desktop window. `preview`, `previewScheme`, `commit` and `cancel` + * drive the provider's preview, as the components lab does. */ export function mountThemes(input: { definitions: readonly Entry[]; pending?: true }) { const container = document.createElement("div") @@ -725,10 +747,15 @@ export function mountThemes(input: { definitions: readonly Entry[]; pending?: tr ) return { - status: (id: string) => hosts[0]?.state.status[id], + status: (id: string) => hosts[0]?.status(id), options: () => themes[0]?.ids().map((id) => ({ id, name: themes[0]?.name(id) })) ?? [], select: (id: string) => themes[0]?.setTheme(id), selected: () => themes[0]?.themeId(), + mode: () => themes[0]?.mode(), + preview: (id: string) => themes[0]?.previewTheme(id), + previewScheme: (scheme: ColorScheme) => themes[0]?.previewColorScheme(scheme), + commit: () => themes[0]?.commitPreview(), + cancel: () => themes[0]?.cancelPreview(), applied: () => applied.count, load: () => setLoaded(true), disable: (id: string) => setDisabled(new Set([id])), @@ -790,8 +817,8 @@ export function mountComposerPills(input: { definitions: readonly Entry[] }) { ) return { - status: (id: string) => hosts[0]?.state.status[id], - failure: (id: string) => hosts[0]?.state.failures[id], + status: (id: string) => hosts[0]?.status(id), + failure: (id: string) => hosts[0]?.failure(id), unmount: () => { dispose() container.remove() @@ -864,8 +891,8 @@ export function mountCodeBlocks(input: { definitions: readonly Entry[] }) { return { show: (text: string, streaming = false) => setMessage({ text, streaming }), define: (next: readonly Entry[]) => setDefinitions(next), - status: (id: string) => hosts[0]?.state.status[id], - failure: (id: string) => hosts[0]?.state.failures[id], + status: (id: string) => hosts[0]?.status(id), + failure: (id: string) => hosts[0]?.failure(id), unmount: () => { dispose() container.remove() @@ -930,7 +957,7 @@ export function mountHostApis(input: { definitions: readonly Entry[] }) { /** Mounts the interface. */ attach: () => void captured.apis?.attach(mounted), reload: (id: string) => hosts[0]?.reload(id), - status: (id: string) => hosts[0]?.state.status[id], + status: (id: string) => hosts[0]?.status(id), unmount: () => { dispose() container.remove() diff --git a/packages/app/component-tests/plugin-host.spec.ts b/packages/app/component-tests/plugin-host.spec.ts index 0f397f749636..3a5fb6b5b4f5 100644 --- a/packages/app/component-tests/plugin-host.spec.ts +++ b/packages/app/component-tests/plugin-host.spec.ts @@ -12,7 +12,8 @@ import type { } from "@opencode/plugin/gui" import type { BuiltinPanelTab } from "@opencode/plugin/gui/builtin" import type { Bridge, BridgeMessage, EnableState, Installed } from "@opencode/plugin/gui/host" -import type { mountCodeBlocks } from "./plugin-host.fixture" +import type { JSHandle } from "@playwright/test" +import type { mountCodeBlocks, mountThemes } from "./plugin-host.fixture" import { expect, sourceURL, story } from "../../stories/playwright/story" const fixture = sourceURL(new URL("./plugin-host.fixture.tsx", import.meta.url)) @@ -20,6 +21,9 @@ const fixture = sourceURL(new URL("./plugin-host.fixture.tsx", import.meta.url)) /** What the code block cases drive from the page. */ type CodeBlocksHost = ReturnType +/** What the theme preview case drives from the page. */ +type ThemesHost = ReturnType + /** What the scoped-registration case keeps from inside its plugin. */ type Scope = { owner?: Owner | null; end: () => void; ctx?: Context } @@ -179,6 +183,66 @@ story("a dialog handle closes its own dialog, and a dialog closes with the scope }) }) +story("Escape closes the top dialog while a dialog below it plays its exit animation", async ({ page }) => { + const result = await page.evaluate(async (fixture) => { + const { mountPluginHost, until } = await import(fixture) + const host = mountPluginHost() + const text = (value: string) => () => Object.assign(document.createElement("p"), { textContent: value }) + const shown = () => ["below", "middle", "top"].filter((value) => document.body.textContent?.includes(value)) + const handles: DialogHandle[] = [] + host.load((ctx: Context) => { + handles.push(ctx.dialogs.open(text("below")), ctx.dialogs.open(text("middle")), ctx.dialogs.open(text("top"))) + }, 0) + await until(() => shown().length === 3) + handles[1]?.close() + // In the same tick, so the middle dialog is still playing its exit animation. + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })) + await until(() => shown().length === 1) + const outcome = shown() + host.unmount() + + return outcome + }, fixture) + + expect(result).toEqual(["below"]) +}) + +story("a dialog closes itself while the dialog above it exits, and a double close never reaches below", async ({ + page, +}) => { + const result = await page.evaluate(async (fixture) => { + const { mountPluginHost, until, useDialog } = await import(fixture) + const host = mountPluginHost() + const shown = () => ["base", "middle", "top"].filter((value) => document.body.textContent?.includes(value)) + const own = { close: () => {} } + host.load((ctx: Context) => { + ctx.dialogs.open(() => Object.assign(document.createElement("p"), { textContent: "base" })) + // A Cancel button inside the middle dialog: a plain close() from its own layer. + ctx.dialogs.open(() => { + const dialog = useDialog() + own.close = () => dialog.close() + + return Object.assign(document.createElement("p"), { textContent: "middle" }) + }) + ctx.dialogs.open(() => Object.assign(document.createElement("p"), { textContent: "top" })) + }, 0) + await until(() => shown().length === 3) + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })) + // In the same tick, while the top dialog is still playing its exit animation; twice, as a double click would. + own.close() + own.close() + await until(() => shown().length === 1) + // Past every exit animation, so a close that reached the base dialog would have removed it by now. + await new Promise((resolve) => setTimeout(resolve, 300)) + const outcome = shown() + host.unmount() + + return outcome + }, fixture) + + expect(result).toEqual(["base"]) +}) + story("a dialog pushed in the same tick as a reload never mounts", async ({ page }) => { const shown = await page.evaluate(async (fixture) => { const { mountPluginHost } = await import(fixture) @@ -979,6 +1043,63 @@ story( }, ) +story("a throwing effect or state reader fails only its own plugin; later plugins still activate", async ({ page }) => { + const result = await page.evaluate(async (fixture) => { + const { mountPlugins, until, createMemo, createRoot } = await import(fixture) + const later = Promise.withResolvers() + const thrown = { count: 0 } + + const host = mountPlugins({ + // Creating the broken plugin's instance throws. + plugin: (id: string) => { + if (id === "broken") throw new Error("instance broke") + + return undefined + }, + definitions: [ + { id: "acme", windowEntry: async () => ({ default: () => {} }) }, + { id: "broken", windowEntry: async () => ({ default: () => {} }) }, + { + id: "later", + windowEntry: async () => { + await later.promise + + return { default: () => {} } + }, + }, + ], + }) + + // A reader with no error boundary: its throw reaches the write that woke it, here acme becoming active. + const dispose = createRoot((dispose: () => void) => { + createMemo(() => { + if (host.status("acme") === "active" && thrown.count++ === 0) throw new Error("reader broke") + }) + + return dispose + }) + + await until(() => thrown.count > 0 && host.status("broken") === "failed") + later.resolve() + await until(() => host.status("later") === "active") + + const outcome = { + acme: host.status("acme"), + broken: host.failure("broken")?.error.includes("instance broke"), + later: host.status("later"), + // In the app, an error that reaches the boundary above the host replaces the whole window. + escaped: host.escaped(), + } + + dispose() + host.unmount() + + return outcome + }, fixture) + + expect(result).toEqual({ acme: "active", broken: true, later: "active", escaped: [] }) +}) + story( "a plugin follows another's contract across load, reload and disable, provides only its own, and a failed one stays failed", async ({ page }) => { @@ -1066,6 +1187,7 @@ story( const Other = Ipc.define({ id: "other.ipc", methods: {} }) const [available, setAvailable] = createSignal(false) const [awake, setAwake] = createSignal(false) + const [failed, setFailed] = createSignal(false) const kept: Kept = {} const client = { @@ -1076,6 +1198,7 @@ story( const host = mountPlugins({ ipc: (token: { readonly id: string }) => (token.id === Awake.id && available() ? client : undefined), + ipcFailed: (token: { readonly id: string }) => token.id === Awake.id && failed(), definitions: [{ id: "acme", windowEntry: async () => ({ default: (ctx: Context) => void (kept.ctx = ctx) }) }], }) @@ -1085,6 +1208,16 @@ story( if (!ctx) throw new Error("the plugin never set up") const main = ctx.main(Awake) + // A call that waits rejects once main fails to answer the window's subscribe, instead of waiting forever. + const stuck = main.get() + setFailed(true) + + const unanswered = await stuck.then( + () => false, + (cause: unknown) => String(cause).includes("unavailable: failed"), + ) + + setFailed(false) const waiting = main.get() const before = main.state() setAwake(true) @@ -1111,10 +1244,11 @@ story( host.unmount() - return { before, answered, state, foreign, rejected, same: ctx.main(Awake) === main } + return { unanswered, before, answered, state, foreign, rejected, same: ctx.main(Awake) === main } }, fixture) expect(result).toEqual({ + unanswered: true, before: undefined, answered: true, state: { awake: true }, @@ -1211,6 +1345,8 @@ story("Extensions › Plugins merges the own server's plugins with the desktop G // A bundle main could not read never reaches the window. { id: "garbled", builtin: false, enabled: true, error: "SyntaxError: garbled bundle" }, { id: "flaky", builtin: false, enabled: true }, + // A plugin whose GUI has no window entry runs only in main, so main's error is its only status. + { id: "main-only", builtin: false, enabled: true, error: "Error: main broke" }, ] const listed = (id: string, features: PluginInfo["features"]): PluginInfo => ({ @@ -1262,6 +1398,7 @@ story("Extensions › Plugins merges the own server's plugins with the desktop G { id: "acme", windowEntry: async () => ({ default: () => {} }) }, { id: "notes", windowEntry: async () => ({ default: () => {} }) }, { id: "flaky", windowEntry: fails("flaky broke") }, + { id: "main-only" }, ], }) @@ -1279,6 +1416,7 @@ story("Extensions › Plugins merges the own server's plugins with the desktop G "flaky", "lint-rules", "notes", + "main-only", "garbled", "terminal", ]) @@ -1291,17 +1429,20 @@ story("Extensions › Plugins merges the own server's plugins with the desktop G await expect(plugins.getByText("SyntaxError: garbled bundle", { exact: true })).toBeVisible() await expect(plugins.getByText("Error: flaky broke", { exact: true })).toBeVisible() await expect(plugins.getByText("Error: terminal broke", { exact: true })).toBeVisible() + await expect(plugins.getByText("Error: main broke", { exact: true })).toBeVisible() await expect(plugins.getByRole("button", { name: "Show details" })).toHaveCount(2) const flaky = plugins.locator(".settings-extension-row").filter({ hasText: "flaky" }) await flaky.getByRole("button", { name: "Show details" }).press("Enter") await expect(flaky.locator("pre")).toHaveText(/^Error: flaky broke\s+at /) await expect(flaky.getByRole("button", { name: "Hide details" })).toHaveAttribute("aria-expanded", "true") - await expect(plugins.getByText("Failed", { exact: true })).toHaveCount(2) + // Every plugin settled: none still says it loads. + await expect(plugins.getByText("Failed", { exact: true })).toHaveCount(3) + await expect(plugins.getByText("Loading", { exact: true })).toHaveCount(0) await expect(plugins.getByText("Built-in", { exact: true })).toHaveCount(1) // A built-in always runs, so it has no switch; the switches carry on and off without a status label. - await expect(plugins.getByRole("switch")).toHaveCount(3) + await expect(plugins.getByRole("switch")).toHaveCount(4) await expect(plugins.getByRole("switch", { name: "terminal" })).toHaveCount(0) - await expect(plugins.getByRole("button", { name: "Reload" })).toHaveCount(4) + await expect(plugins.getByRole("button", { name: "Reload" })).toHaveCount(5) await expect(plugins.getByText("Active", { exact: true })).toHaveCount(0) // The fixture mounts below the story, out of the viewport, so the controls are driven from the keyboard. @@ -1602,6 +1743,122 @@ story( }, ) +story("a theme preview survives a system light/dark flip and a plugin theme arriving, and is never saved", async ({ + page, +}) => { + await page.emulateMedia({ colorScheme: "dark" }) + + const host: JSHandle = await page.evaluateHandle(async (fixture) => { + const { mountThemes, Theme } = await import(fixture) + // The frame's own provider saved its scheme; this window follows the system. + localStorage.setItem("opencode-color-scheme", "system") + localStorage.removeItem("opencode-theme-id") + localStorage.removeItem("opencode-theme-css-light") + localStorage.removeItem("opencode-theme-css-dark") + + const variant = { + palette: { + neutral: "#101418", + ink: "#e6edf3", + primary: "#009fff", + success: "#3fb950", + warning: "#d29922", + error: "#f85149", + info: "#a371f7", + }, + } + + const host: ThemesHost = mountThemes({ + definitions: [ + { + id: "acme", + windowEntry: async () => ({ + default: (ctx: Context) => + void ctx.add(Theme, { + $schema: "https://opencode.ai/desktop-theme.json", + name: "Midnight", + id: "midnight", + light: variant, + dark: variant, + }), + }), + }, + ], + }) + + host.previewScheme("light") + + return host + }, fixture) + + const read = () => + host.evaluate((host) => ({ + theme: document.documentElement.dataset.theme, + shown: document.documentElement.dataset.colorScheme, + mode: host.mode(), + scheme: localStorage.getItem("opencode-color-scheme"), + id: localStorage.getItem("opencode-theme-id"), + cached: [localStorage.getItem("opencode-theme-css-light"), localStorage.getItem("opencode-theme-css-dark")].map( + (css) => css !== null, + ), + })) + + // A media change reaches the provider's listener before one added after it. + const flip = async (colorScheme: "light" | "dark") => { + const changed = await page.evaluateHandle(() => ({ + done: new Promise((resolve) => + matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => resolve(), { once: true }), + ), + })) + + await page.emulateMedia({ colorScheme }) + await changed.evaluate((changed) => changed.done) + } + + // The plugin's theme arrives while the preview is up. + await expect.poll(() => host.evaluate((host) => host.status("acme"))).toBe("active") + const previewed = await read() + + await flip("light") + await flip("dark") + const flipped = await read() + + await host.evaluate((host) => host.preview("acme:midnight")) + const midnight = await read() + + await host.evaluate((host) => host.cancel()) + const cancelled = await read() + + await host.evaluate((host) => { + host.preview("acme:midnight") + host.commit() + }) + const committed = await read() + await host.evaluate((host) => host.unmount()) + + expect({ previewed, flipped, midnight, cancelled, committed }).toEqual({ + previewed: { theme: "oc-2", shown: "light", mode: "light", scheme: "system", id: null, cached: [false, false] }, + flipped: { theme: "oc-2", shown: "light", mode: "light", scheme: "system", id: null, cached: [false, false] }, + midnight: { + theme: "acme:midnight", + shown: "light", + mode: "light", + scheme: "system", + id: null, + cached: [false, false], + }, + cancelled: { theme: "oc-2", shown: "dark", mode: "dark", scheme: "system", id: null, cached: [false, false] }, + committed: { + theme: "acme:midnight", + shown: "dark", + mode: "dark", + scheme: "system", + id: "acme:midnight", + cached: [true, true], + }, + }) +}) + story("a selected plugin theme that never returns shows the default theme once plugins settle", async ({ page }) => { const result = await page.evaluate(async (fixture) => { const { mountThemes, until } = await import(fixture) diff --git a/packages/app/component-tests/presence.fixture.tsx b/packages/app/component-tests/presence.fixture.tsx new file mode 100644 index 000000000000..530cb0abc823 --- /dev/null +++ b/packages/app/component-tests/presence.fixture.tsx @@ -0,0 +1,59 @@ +import { Show, createSignal } from "solid-js" +import { createStore } from "solid-js/store" +import { render } from "solid-js/web" +import { ComposerDropzone } from "../src/composer/dropzone" +import { createAnimatedPresence } from "../src/runtime/animated-presence" +import { LanguageProvider } from "../src/runtime/i18n/language" + +type Lane = "bottom" | "row" | "none" + +const [state, setState] = createStore<{ hint?: string; lane: Lane; active: boolean }>({ lane: "bottom", active: false }) + +const host = document.createElement("div") + +/** + * The background hint wired as `MessageTimeline` wires it: two lanes share one ref, and `lane: "none"` unmounts both + * while the ref still holds the removed element. Beside it, a real `ComposerDropzone`. + */ +export function mountPresence() { + host.dataset.testid = "presence-fixture" + document.body.appendChild(host) + render(() => { + const [ref, setRef] = createSignal() + + const presence = createAnimatedPresence( + () => state.hint, + () => ref() ?? null, + () => "ses_fixture", + ) + + const hint = (lane: Lane) => ( + +
+ {presence.value()} +
+
+ ) + + return ( + + {presence.state()} + {hint("bottom")} + {hint("row")} +
+ +
+
+ ) + }, host) +} + +export const setPresence = (patch: { hint?: string; lane?: Lane; active?: boolean }) => setState(patch) diff --git a/packages/app/component-tests/presence.spec.ts b/packages/app/component-tests/presence.spec.ts new file mode 100644 index 000000000000..85b0e90b0965 --- /dev/null +++ b/packages/app/component-tests/presence.spec.ts @@ -0,0 +1,104 @@ +import { expect, sourceURL, story } from "../../stories/playwright/story" + +const fixture = sourceURL(new URL("./presence.fixture.tsx", import.meta.url)) + +story.beforeEach(async ({ mount, page }) => { + // Any story loads the app's styles; the fixture mounts the presences beside it. + await mount("ui-line-comment--editor") + await page.evaluate(async (fixture) => { + const { mountPresence } = await import(fixture) + mountPresence() + }, fixture) +}) + +story("hides an exit whose element was unmounted mid-animation", async ({ page }) => { + const root = page.getByTestId("presence-fixture") + await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + setPresence({ hint: "Move to background" }) + }, fixture) + await expect(root.getByTestId("hint-bottom")).toHaveText("Move to background") + + // The hint starts its exit, then its lane goes away before the animation ends, as when the timeline stops being live. + const hiding = await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + setPresence({ hint: undefined }) + const state = document.querySelector('[data-testid="presence-state"]')?.textContent + setPresence({ lane: "none" }) + + return state + }, fixture) + + expect(hiding).toBe("hiding") + await expect(root.getByTestId("presence-state")).toHaveText("hidden") +}) + +story("hides at once when its element is swapped mid-exit", async ({ page }) => { + const root = page.getByTestId("presence-fixture") + await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + setPresence({ hint: "Move to background" }) + }, fixture) + await expect(root.getByTestId("hint-bottom")).toBeVisible() + + // Moving to the other lane mounts a second element mid-exit; it must not replay the fade from full opacity. + const states = await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + const read = () => document.querySelector('[data-testid="presence-state"]')?.textContent + setPresence({ hint: undefined }) + const hiding = read() + setPresence({ lane: "row" }) + + return [hiding, read()] + }, fixture) + + expect(states).toEqual(["hiding", "hidden"]) + await expect(root.getByTestId("hint-row")).toHaveCount(0) +}) + +story("hides when Reduce Motion turns on mid-exit", async ({ page }) => { + const root = page.getByTestId("presence-fixture") + await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + setPresence({ hint: "Move to background" }) + }, fixture) + await expect(root.getByTestId("hint-bottom")).toBeVisible() + + const states = await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + const read = () => document.querySelector('[data-testid="presence-state"]')?.textContent + setPresence({ hint: undefined }) + const hiding = read() + // What the app does when the setting or the system preference changes. `motion-reduce:animate-none` drops the + // exit animation, and Chromium fires no `animationcancel` for it. + document.documentElement.dataset.motion = "reduce" + await Promise.resolve() + + return [hiding, read()] + }, fixture) + + expect(states).toEqual(["hiding", "hidden"]) + await expect(root.getByTestId("hint-bottom")).toHaveCount(0) +}) + +story("keeps the dropzone mounted while its fade-out transition plays", async ({ page }) => { + const dropzone = page.locator('[data-component="session-dropzone"]') + await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + setPresence({ active: true }) + }, fixture) + await expect(dropzone).toHaveAttribute("data-visible", "true") + // Once the enter animation has finished; hiding from its first frame at opacity 0 has nothing to fade. + await expect(dropzone).toHaveCSS("opacity", "1") + + const leaving = await page.evaluate(async (fixture) => { + const { setPresence } = await import(fixture) + setPresence({ active: false }) + const element = document.querySelector('[data-component="session-dropzone"]') + + return element?.getAttribute("data-visible") + }, fixture) + + expect(leaving).toBe("false") + await expect(dropzone).toHaveCount(0) +}) diff --git a/packages/app/component-tests/session-question-dock.spec.ts b/packages/app/component-tests/session-question-dock.spec.ts index 6f6d469e9d04..ec457e265f30 100644 --- a/packages/app/component-tests/session-question-dock.spec.ts +++ b/packages/app/component-tests/session-question-dock.spec.ts @@ -28,7 +28,9 @@ for (const variant of ["classic", "experimental"] as const) { await page.mouse.down() await page.mouse.move(box!.x + box!.width - 1, box!.y + box!.height / 2, { steps: 12 }) await page.mouse.up() - await expect.poll(() => page.evaluate(() => window.getSelection()?.toString().trim())).toBe(await text.innerText()) + await expect + .poll(() => page.evaluate(() => window.getSelection()?.toString().trim())) + .toBe(await text.innerText()) } for (const slot of ["option-label", "option-description"]) { @@ -1105,6 +1107,44 @@ story.describe("with the new question UI experiment enabled", () => { expect(frames.moving.heights + frames.moving.ghosts).toBeGreaterThan(0) expect(frames.after).toEqual({ animations: 0, heights: 0, ghosts: 0 }) }) + + story("lands the composer's switch to a question at once when the knob turns off", async ({ mount }) => { + const component = await mount("session-composer-docks--empty") + await expect(component.locator('[data-slot="composer-face"]')).toHaveCount(1) + + const frames = await component.evaluate( + async (root, tuning) => { + const { motionTuning } = await import(tuning) + const knob = motionTuning.list().find((item: MotionKnob) => item.id === "question.motion") + const region = root.querySelector('[data-slot="composer-morph"]')! + const frame = () => new Promise((resolve) => requestAnimationFrame(resolve)) + + const sample = () => ({ + moving: region.hasAttribute("data-moving"), + height: !!region.style.height, + faces: region.querySelectorAll('[data-slot="composer-face"]').length, + }) + + // A face that changes within 250ms of mount swaps without a flight. + for (const end = performance.now() + 300; performance.now() < end; ) await frame() + motionTuning + .actions() + .find((action: { id: string }) => action.id === "docks.question") + .run() + await frame() + await frame() + const moving = sample() + motionTuning.set(knob, false) + await frame() + + return { moving, after: sample() } + }, + sourceURL(new URL("../../ui/src/motion-tuning.ts", import.meta.url)), + ) + + expect(frames.moving).toEqual({ moving: true, height: true, faces: 2 }) + expect(frames.after).toEqual({ moving: false, height: false, faces: 1 }) + }) }) story( diff --git a/packages/app/component-tests/ssh-reconnect.spec.ts b/packages/app/component-tests/ssh-reconnect.spec.ts index 7abb39824b61..c2afa5a84e72 100644 --- a/packages/app/component-tests/ssh-reconnect.spec.ts +++ b/packages/app/component-tests/ssh-reconnect.spec.ts @@ -15,6 +15,23 @@ story("settings menu reconnect retains its prompt handler across server updates" await expect(component.getByRole("button", { name: "Authenticate", exact: true })).toHaveCount(0) }) +story("cancelling a sign-in from Home offers it again at once", async ({ mount, page }) => { + const component = await mount("app-dialog-ssh--authentication-required") + const projects = component.getByRole("button", { name: "Projects" }) + const authenticate = page.getByRole("button", { name: "Authenticate", exact: true }) + const dialog = page.getByRole("dialog", { name: "Connect to linuxbook" }) + await projects.click() + await authenticate.click() + await expect(dialog.getByRole("textbox")).toBeVisible() + await dialog.getByRole("button", { name: "Cancel", exact: true }).click() + await expect(dialog).toHaveCount(0) + // The sign-in that waited on the dialog ends with it, instead of showing the server as connecting. + await projects.click() + await expect(authenticate).toBeEnabled() + await authenticate.click() + await expect(dialog.getByRole("textbox")).toBeVisible() +}) + story("cancelling a version mismatch permits reconnecting again", async ({ mount, page }) => { const component = await mount("app-dialog-ssh--incompatible-session") await component.getByRole("button", { name: "Reconnect", exact: true }).click() diff --git a/packages/app/component-tests/terminal.spec.ts b/packages/app/component-tests/terminal.spec.ts index d97e93bdf809..fe8c272b338c 100644 --- a/packages/app/component-tests/terminal.spec.ts +++ b/packages/app/component-tests/terminal.spec.ts @@ -118,6 +118,16 @@ story("does not send the emulator's own answers to terminal queries as input", a expect(server.frames.filter((frame) => frame.type === 1).map((frame) => frame.data)).toEqual(["x"]) }) +story("shows a terminal that has written nothing yet and stays silent", async ({ page, mount }) => { + // An empty checkpoint and no output: nothing ever reaches the emulator. + const server = await serveTerminal(page, { ptyID: "pty_silent", output: "" }) + const root = await mountTerminal(page, mount, "pty_silent") + + await expect.poll(() => server.sockets.length).toBe(1) + await expect(root.locator('[data-component="terminal"]')).toHaveCSS("opacity", "1") + await expect(root.locator("[data-failures]")).toHaveAttribute("data-failures", "0") +}) + story("tells the user a server that predates the input protocol is too old", async ({ page, mount }) => { await serveTerminal(page, { ptyID: "pty_old", output: "old server\r\n", inputProtocol: 0 }) const root = await mountTerminal(page, mount, "pty_old") diff --git a/packages/app/component-tests/timeline-virtualizer.fixture.tsx b/packages/app/component-tests/timeline-virtualizer.fixture.tsx index 460a681d106d..fb6d15e9c403 100644 --- a/packages/app/component-tests/timeline-virtualizer.fixture.tsx +++ b/packages/app/component-tests/timeline-virtualizer.fixture.tsx @@ -99,7 +99,7 @@ export function mountTimelineVirtualizer(input: { }) return ( -
+
@@ -127,6 +127,15 @@ export function mountTimelineVirtualizer(input: { + {/* A tool inside a group of several, which names them all on the group, as a reveal anchors it. */} +
{row().userMessageID}
diff --git a/packages/app/component-tests/timeline-virtualizer.spec.ts b/packages/app/component-tests/timeline-virtualizer.spec.ts index c4e8bbf876ed..af213ad5a296 100644 --- a/packages/app/component-tests/timeline-virtualizer.spec.ts +++ b/packages/app/component-tests/timeline-virtualizer.spec.ts @@ -55,6 +55,25 @@ story("bounds the cheap suffix and reveals only ready measured rows", async ({ p }) }) +story("reveals at the end when Markdown never reports ready", async ({ page }) => { + // A block that never set data-markdown-ready kept every reveal check waiting, and the timeline stayed invisible. + await page.evaluate(async (fixture) => { + const { mountTimelineVirtualizer } = await import(fixture) + mountTimelineVirtualizer({ count: 100, rowHeight: 60, immediate: true }) + }, fixture) + const root = page.getByTestId("timeline-virtualizer-fixture") + const content = root.locator("[data-timeline-virtual-content]") + await expect(content).toHaveCSS("visibility", "hidden") + await expect(content).toHaveCSS("visibility", "visible") + const reveal = await root.evaluate((element) => JSON.parse(element.dataset.firstReveal!)) + expect(reveal.pendingMarkdown).toBeGreaterThan(0) + expect(reveal.rows).toContain(99) + const viewport = root.locator("[data-scrollable]") + await expect + .poll(() => viewport.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop)) + .toBeLessThanOrEqual(1) +}) + story("treats the reachable end as the end under page zoom", async ({ page }) => { // At 110% the browser stops scrolling more than a pixel short of scrollHeight - clientHeight. A mount that waited // for that distance to close stayed blank, or froze the renderer in a microtask loop, and scrolling back down to @@ -128,6 +147,27 @@ story("leaves a reader who scrolled up in place after a scroll to the zoomed end expect(await distance()).toBeGreaterThan(70) }) +story("holds a revealed tool inside a group of several through a later resize", async ({ page }) => { + // The anchor looked only for an element naming the tool alone, so a grouped tool let go on the next resize. + await page.evaluate(async (fixture) => { + const { mountTimelineVirtualizer } = await import(fixture) + mountTimelineVirtualizer({ count: 40, rowHeight: 60, immediate: true }) + }, fixture) + const root = page.getByTestId("timeline-virtualizer-fixture") + const controls = root.getByTestId("timeline-controls") + await root.getByRole("button", { name: "Complete Markdown", exact: true }).click() + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + await expect(controls).toHaveAttribute("data-pinned", "true") + + await root.getByRole("button", { name: "Anchor first row", exact: true }).click() + await expect(root.locator('[data-timeline-part-ids="prt_first,prt_grouped"]')).toBeAttached() + await root.getByRole("button", { name: "Grow last row", exact: true }).click() + + const viewport = root.locator("[data-scrollable]") + await expect.poll(() => viewport.evaluate((element) => element.scrollTop)).toBe(0) + await expect(controls).toHaveAttribute("data-anchored", "true") +}) + for (const input of [ { name: "offset-only", count: 1, rowHeight: 600, reveal: { scrollTop: 0 } }, { name: "zero-height", count: 4, rowHeight: 60, reveal: {} }, diff --git a/packages/app/component-tests/tooltip.spec.ts b/packages/app/component-tests/tooltip.spec.ts index 64e9b879fd67..b55839f0feaf 100644 --- a/packages/app/component-tests/tooltip.spec.ts +++ b/packages/app/component-tests/tooltip.spec.ts @@ -10,3 +10,40 @@ story("opens a neighbouring tooltip without the open delay", async ({ mount, pag await root.getByText("Compact", { exact: true }).hover() await expect(page.getByRole("tooltip", { name: "Compact tooltip" })).toBeVisible() }) + +story("keeps a menu trigger's tooltip hidden when the menu closes under a still pointer", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-menu") + await page.clock.install() + const trigger = root.getByRole("button", { name: "Actions" }) + const tooltip = page.getByRole("tooltip", { name: "More actions" }) + await trigger.hover() + await expect(tooltip).toBeVisible() + await trigger.click() + await expect(page.getByRole("menu")).toBeVisible() + await expect(tooltip).toBeHidden() + await page.keyboard.press("Escape") + await expect(page.getByRole("menu")).toBeHidden() + await expect(trigger).toBeFocused() + // The menu's closing layer hands the still pointer a fresh pointerenter, which would open the tooltip 400 ms later. + await page.clock.runFor(1000) + await expect(tooltip).toBeHidden() + await page.mouse.move(0, 0) + await trigger.hover() + await expect(tooltip).toBeVisible() +}) + +story("opens a menu trigger's tooltip on the next hover after the menu closes", async ({ mount, page }) => { + const root = await mount("ui-tooltip--with-menu") + const trigger = root.getByRole("button", { name: "Actions" }) + const tooltip = page.getByRole("tooltip", { name: "More actions" }) + await trigger.hover() + await expect(tooltip).toBeVisible() + await trigger.click() + await expect(page.getByRole("menu")).toBeVisible() + await page.mouse.move(0, 0) + await page.keyboard.press("Escape") + await expect(page.getByRole("menu")).toBeHidden() + await expect(trigger).toBeFocused() + await trigger.hover() + await expect(tooltip).toBeVisible() +}) diff --git a/packages/app/e2e/regression/btw-sidebar.spec.ts b/packages/app/e2e/regression/btw-sidebar.spec.ts index 0472b77b2bae..9fab34633166 100644 --- a/packages/app/e2e/regression/btw-sidebar.spec.ts +++ b/packages/app/e2e/regression/btw-sidebar.spec.ts @@ -66,7 +66,7 @@ test("keeps separate one-shot /btw answers and restores them after reload", asyn expect(prompts).toEqual([]) }) -test("isolates concurrent side questions and makes an interrupted reload retryable", async ({ page }) => { +test("isolates concurrent side questions and makes interrupted and blank answers retryable", async ({ page }) => { const held = Promise.withResolvers() const attempts: string[] = [] const prompts: unknown[] = [] @@ -83,6 +83,14 @@ test("isolates concurrent side questions and makes an interrupted reload retryab return { text: "Abandoned answer" } } + // A reply with only a tool call or reasoning reaches the panel as blank text. + if (input.prompt.includes("blank question")) { + return { + text: + attempts.filter((item) => item.includes("blank question")).length === 1 ? " \n " : "Recovered answer", + } + } + return { text: input.prompt.includes("fast question") ? "Fast answer" : "Retried answer" } }, }) @@ -114,6 +122,17 @@ test("isolates concurrent side questions and makes an interrupted reload retryab await expect(panel.getByText("Retried answer", { exact: true })).toBeVisible() await expect(panel.getByText("Abandoned answer", { exact: true })).toHaveCount(0) await expect(panel.getByRole("textbox")).toHaveCount(0) + + await editor.fill("/btw blank question") + await editor.press("Enter") + await expect(page.getByRole("tab", { name: "blank question", exact: true })).toHaveAttribute("data-selected", "") + await expect(panel.getByText("Couldn’t answer that question", { exact: true })).toBeVisible() + await expect(panel.getByText("The model replied without any text.", { exact: true })).toBeVisible() + await expect(panel.getByRole("status")).toHaveCount(0) + await panel.getByRole("button", { name: "Retry", exact: true }).click() + await expect(panel.getByText("Recovered answer", { exact: true })).toBeVisible() + await expect(panel.getByText("Couldn’t answer that question", { exact: true })).toHaveCount(0) + expect(attempts.filter((item) => item.includes("blank question"))).toHaveLength(2) expect(prompts).toEqual([]) }) diff --git a/packages/app/e2e/regression/command-palette.spec.ts b/packages/app/e2e/regression/command-palette.spec.ts index 0a7a1bdea5ac..4b21742d6e07 100644 --- a/packages/app/e2e/regression/command-palette.spec.ts +++ b/packages/app/e2e/regression/command-palette.spec.ts @@ -6,7 +6,8 @@ import { openPaletteWorkspace, paletteSession, } from "../utils/command-palette" -import { mockWorkspace } from "../utils/workspace" +import { REMOTE_SERVER, SERVER } from "../utils/app" +import { mockRemoteServer, mockWorkspace } from "../utils/workspace" test.use({ serviceWorkers: "block", permissions: ["clipboard-read", "clipboard-write"] }) @@ -131,6 +132,43 @@ test("titlebar search lists recent sessions and opens the typed match", async ({ await expect(page.getByRole("heading", { name: paletteSession.title, exact: true })).toBeVisible() }) +test("titlebar search shows one server's matches while another server's search fails", async ({ page }) => { + await mockRemoteServer(page, { name: "Remote" }) + const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + // Only typed searches fail, so the remote server still lists its recent sessions. + await page.route(new RegExp(`^${escape(REMOTE_SERVER)}/api/session\\?.*search=[^&]`), (route) => + route.request().method() === "GET" + ? route.fulfill({ + status: 500, + json: { message: "Search failed" }, + headers: { "access-control-allow-origin": "*" }, + }) + : route.fallback(), + ) + await openPaletteWorkspace(page, true) + // The server matches more than titles, so only its answer can list this session. Registered after the local mock so + // this route answers first. + await page.route(new RegExp(`^${escape(SERVER)}/api/session\\?.*search=[^&]`), (route) => + route.fulfill({ + json: { + data: [ + { + ...paletteSession, + id: "ses_palette_found", + location: { directory: paletteSession.directory }, + title: "Matched on the server", + }, + ], + }, + }), + ) + await page.getByRole("banner").getByRole("button", { name: "Search sessions", exact: true }).click() + const dialog = page.getByRole("dialog") + await dialog.getByRole("combobox").fill("needle") + await expect(dialog.getByRole("option")).toHaveText([/Matched on the server/]) + await expect(dialog.getByText("Request failed", { exact: true })).toHaveCount(0) +}) + test("a working session keeps its project avatar in Search sessions and shows its activity ring in place of its age", async ({ page, }) => { diff --git a/packages/app/e2e/regression/composer.spec.ts b/packages/app/e2e/regression/composer.spec.ts index 3c60765b53e2..3f035d4dd843 100644 --- a/packages/app/e2e/regression/composer.spec.ts +++ b/packages/app/e2e/regression/composer.spec.ts @@ -1,5 +1,5 @@ import { expect, test, type Locator, type Page } from "@playwright/test" -import { NO_PROVIDER, SERVER, T0, expectPath, holdRoute, provider, sessionHref } from "../utils/app" +import { NO_PROVIDER, SERVER, T0, expectPath, holdRoute, pageMessagesFrom, provider, sessionHref } from "../utils/app" import { mockWorkspace, openDraft, openSession } from "../utils/workspace" import { mockPluginsActivating, type MockServerConfig } from "../utils/mock-server" @@ -115,6 +115,34 @@ test("a bare @ lists sessions, and a multi-word title matches while file search expect(prompts[1]?.text).toBe("@home now") }) +test("closing the @ menu aborts its session search", async ({ page }) => { + const view = await openSession(page, { + name: "SessionMentionAbort", + findFiles: () => [], + sessions: [{ id: "ses_mention_abort_source", title: "Review the plan" }], + seed: { tabs: ["ses_mention_abort_source"] }, + }) + + const suggestions = page.locator('[data-component="composer-suggestions"]') + const search = await holdRoute(page, /\/api\/session\?.*search=auth(&|$)/) + + try { + await view.editor.pressSequentially("@auth") + const request = await search.arrived + + const failed = page.waitForEvent("requestfailed", { + predicate: (candidate) => candidate === request, + timeout: 10_000, + }) + + await view.editor.press("Escape") + await expect(suggestions).toBeHidden() + expect((await failed).failure()?.errorText).toBe("net::ERR_ABORTED") + } finally { + search.release() + } +}) + test("the free usage limit opens the Go dialog once, leaves a readable notice, and restores the prompt", async ({ page, context, @@ -681,8 +709,15 @@ test("an opened session in another Location names its model from a loaded catalo }), ) + // A click before the catalog loads waits for it, and Escape gives up the wait, so the dialog cannot pop up later. + await control.click() + await expect(control).toHaveAttribute("aria-busy", "true") + await page.keyboard.press("Escape") + await expect(control).not.toHaveAttribute("aria-busy") + // A click before the catalog loads opens the dialog once it does. await control.click() + await expect(control).toHaveAttribute("aria-busy", "true") held.release() await Promise.all(loaded) await expect(page.getByRole("dialog")).toBeVisible() @@ -883,7 +918,11 @@ test("keeps a line added at the end of a scrolling prompt clear of the bottom fa const viewport = element.closest('[data-component="composer-scroll"]')! const range = document.createRange() range.selectNodeContents(element) - const line = Array.from(range.getClientRects()).reduce((last, rect) => (rect.bottom > last.bottom ? rect : last)) + + const line = Array.from(range.getClientRects()).reduce((last, rect) => + rect.bottom > last.bottom ? rect : last, + ) + const fade = parseFloat(getComputedStyle(viewport).getPropertyValue("--composer-fade-bottom")) return Math.max(0, Math.round(line.bottom - (viewport.getBoundingClientRect().bottom - fade))) @@ -952,6 +991,53 @@ test.describe("touch keyboard", () => { .poll(() => prompts.map((body) => body.text)) .toEqual(["first line\nsecond line", "from the iPad keyboard"]) }) + + test("the / and @ keys toggle their lists, and Backspace or typing in the editor closes them", async ({ page }) => { + const view = await openSession(page, { name: "ComposerTouchSlash" }) + const suggestions = page.locator('[data-component="composer-suggestions"]') + const slash = page.locator('[data-slot="composer-touch-bar"] [data-action="composer-commands"]') + + await slash.tap() + await expect(suggestions).toBeVisible() + await expect(view.editor).toHaveText("/") + await slash.tap() + await expect(suggestions).toBeHidden() + await expect(view.editor).toBeEmpty() + + await slash.tap() + await expect(suggestions).toBeVisible() + await page.keyboard.press("Backspace") + await expect(suggestions).toBeHidden() + + // With a draft, / opens the searchable menu instead. Backspace backs out of it and keeps the draft, from the editor + // as well: iOS keeps the keyboard there rather than moving it to the menu's search. + await view.editor.fill("keep me") + await slash.tap() + await expect(suggestions).toBeVisible() + await view.editor.press("Backspace") + await expect(suggestions).toBeHidden() + await expect(view.editor).toHaveText("keep me") + + await slash.tap() + await expect(suggestions).toBeVisible() + // Focusing the editor programmatically leaves the caret wherever the browser puts it, so move it to the end first. + await expect(suggestions.getByRole("textbox", { name: "Commands", exact: true })).toBeFocused() + await view.editor.focus() + await page.keyboard.press("End") + await page.keyboard.type(" now") + await expect(suggestions).toBeHidden() + await expect(view.editor).toHaveText("keep me now") + + // @ toggles the same way, taking back only the @ it typed. + const at = page.locator('[data-slot="composer-touch-bar"] [data-action="composer-context"]') + await view.editor.pressSequentially(" ") + await at.tap() + await expect(suggestions).toBeVisible() + await expect(view.editor).toHaveText("keep me now @") + await at.tap() + await expect(suggestions).toBeHidden() + await expect(view.editor).toHaveText("keep me now ") + }) }) test("a key-up never moves the caret back after later navigation", async ({ page }) => { @@ -1091,6 +1177,33 @@ test("shows the dropzone and attaches a dropped file", async ({ page }) => { await expect(page.locator('[data-component="composer-attachments"]')).toContainText("dropzone.txt") }) +test("an attachment pasted mid-sentence leaves the text and the caret where they were", async ({ page }) => { + const { editor } = await openDraft(page, { + name: "ComposerDraft", + provider: NO_PROVIDER, + onFileWrite: () => undefined, + }) + + await editor.click() + await page.keyboard.type("Hello world") + await editor.press("Home") + + for (let count = 0; count < "Hello".length; count++) await editor.press("ArrowRight") + + const text = await editor.evaluateHandle((element) => element.firstChild) + + await editor.evaluate((element) => { + const data = new DataTransfer() + data.items.add(new File(["Attachment fixture"], "notes.txt", { type: "text/plain" })) + element.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true })) + }) + await expect(page.locator('[data-component="composer-attachments"]')).toContainText("notes.txt") + // A rewrite of the editor would replace this node, even when it put the caret back in the same place. + expect(await editor.evaluate((element, node) => element.firstChild === node, text)).toBe(true) + await page.keyboard.type(",") + await expect(editor).toHaveText("Hello, world") +}) + test("keeps one dropzone while a file drag crosses the composer, and none for a text drag", async ({ page }) => { const editor = await draft(page) await page.keyboard.type("worktree off the latest dev") @@ -1258,6 +1371,13 @@ test("/reload reloads the server's configuration once and reports it", async ({ await expect(page.locator('[data-suggestion-id="config.reload"]')).toHaveAttribute("data-active", "") await editor.press("Enter") await expect(page.getByText("Reloading configuration…", { exact: true })).toBeVisible() + // A second /reload while the first runs joins it: no second request and no second toast. + await expect(editor).toBeEmpty() + await editor.fill("/reload") + await expect(page.locator('[data-suggestion-id="config.reload"]')).toHaveAttribute("data-active", "") + await editor.press("Enter") + await expect(editor).toBeEmpty() + await expect(page.getByText("Reloading configuration…", { exact: true })).toHaveCount(1) reloaded.resolve() await expect(page.getByText("Configuration reloaded", { exact: true })).toBeVisible() await expect(page.getByText("Reloading configuration…", { exact: true })).toBeHidden() @@ -1265,6 +1385,62 @@ test("/reload reloads the server's configuration once and reports it", async ({ expect(reloads).toBe(1) }) +test("/fork forks once while its request is pending, can retry a failure, and restores the prompt", async ({ + page, +}) => { + const source = { id: "ses_fork_source", title: "Fork source" } + const forks: string[] = [] + const answers = [Promise.withResolvers(), Promise.withResolvers()] + + const { editor } = await openSession(page, { + name: "ComposerFork", + provider: NO_PROVIDER, + sessions: [source], + pageMessages: pageMessagesFrom({ + [source.id]: [ + { id: "msg_fork_first", type: "user", text: "First prompt", time: { created: T0 } }, + { id: "msg_fork_second", type: "user", text: "Second prompt", time: { created: T0 + 1 } }, + ], + }), + onFork: async ({ body }) => { + forks.push(String(body.before)) + await answers[forks.length - 1]?.promise + + if (forks.length === 1) return { status: 500, body: { message: "Fork failed" } } + }, + }) + + await editor.fill("/fork") + await expect(page.locator('[data-suggestion-id="session.fork"]')).toHaveAttribute("data-active", "") + await editor.press("Enter") + + const dialog = page.getByRole("dialog", { name: "Fork from message", exact: true }) + const search = dialog.getByRole("searchbox") + const newest = dialog.getByRole("option", { name: /Second prompt/ }) + await expect(search).toBeFocused() + + // Enter forks from the newest prompt; a second Enter while the fork runs sends nothing. + await search.press("Enter") + await expect(newest).toHaveAttribute("aria-busy", "true") + await expect(dialog.getByRole("option", { name: /First prompt/ })).toBeDisabled() + await search.press("Enter") + answers[0].resolve() + + await expect(page.getByText("Request failed", { exact: true })).toBeVisible() + await expect(newest).toBeEnabled() + await expect(newest).not.toHaveAttribute("aria-busy") + expect(forks).toEqual(["msg_fork_second"]) + + await search.press("Enter") + await expect(newest).toHaveAttribute("aria-busy", "true") + answers[1].resolve() + + await expectPath(page, sessionHref(`${source.id}_fork`)) + await expect(dialog).toBeHidden() + await expect(editor).toHaveText("Second prompt") + expect(forks).toEqual(["msg_fork_second", "msg_fork_second"]) +}) + const followUp = "Add follow-up, / for commands, @ for context…" test("the shell shortcut toggles modes and keeps explicit bindings", async ({ page }) => { @@ -1333,6 +1509,33 @@ for (const row of [ }) } +test("a sent shell command returns the composer to prompt mode, and ! enters shell mode again", async ({ page }) => { + const { editor } = await openSession(page, { + name: "ShellSend", + sessions: [{ id: "ses_shell_send", title: "Shell send" }], + }) + + const scroll = page.locator('[data-component="composer-scroll"]') + await expect(scroll).toHaveText("Ask anything, / for commands, @ for context…") + await editor.pressSequentially("!") + await expect(scroll).toHaveText("Enter shell command… git status") + await editor.pressSequentially("git status") + + const sent = page.waitForRequest( + (request) => request.method() === "POST" && new URL(request.url()).pathname.endsWith("/ses_shell_send/shell"), + ) + + await editor.press("Enter") + expect((await sent).postDataJSON()).toMatchObject({ command: "git status" }) + await expect(editor).toBeEmpty() + await expect(scroll).toHaveText("Ask anything, / for commands, @ for context…") + await expect(page.getByRole("button", { name: /^Exit/ })).toHaveCount(0) + + // The editor reads the draft's mode, so it agrees with the draft the send reset. + await editor.pressSequentially("!") + await expect(scroll).toHaveText("Enter shell command… git status") +}) + test("marks a Console provider with its workspace only when it is also connected directly", async ({ page }) => { const model = (id: string, name: string) => ({ [id]: { id, name, limit: { context: 200_000 } } }) diff --git a/packages/app/e2e/regression/directory-picker.spec.ts b/packages/app/e2e/regression/directory-picker.spec.ts index 7d61a2eb0baf..dae4f41cf46e 100644 --- a/packages/app/e2e/regression/directory-picker.spec.ts +++ b/packages/app/e2e/regression/directory-picker.spec.ts @@ -1,8 +1,74 @@ -import { expect, test } from "@playwright/test" +import { expect, test, type Page } from "@playwright/test" +import { holdRoute } from "../utils/app" +import type { MockServerConfig } from "../utils/mock-server" import { fileNode, openSettings } from "../utils/workspace" test.use({ viewport: { width: 1440, height: 900 } }) +const directory = "C:/OpenCode/Picker" + +// Opens the folder picker from Settings > Projects once its root has listed. +async function openPicker(page: Page, input: Pick) { + await openSettings(page, { name: "Picker", seed: { tabs: [] }, ...input }) + await page.getByTestId("settings-screen").getByRole("tab", { name: "Projects", exact: true }).click() + await page.getByRole("button", { name: "Add project", exact: true }).click() + const picker = page.getByRole("dialog", { name: "Open project", exact: true }) + await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled() + + return picker +} + +test("Tab and Enter while suggestions load act on the typed folder, not the previous suggestions", async ({ page }) => { + const picker = await openPicker(page, { + fileList: (path) => + path === directory ? ["alpha", "beta"].map((name) => fileNode(directory, name, "directory")) : [], + findFiles: (input) => ["alpha", "beta"].filter((name) => input.query.length >= 3 && name.startsWith(input.query)), + }) + + const input = picker.getByRole("combobox") + + await input.fill("alp") + await expect(picker.getByRole("option")).toHaveText(["C:\\OpenCode\\Picker\\alpha/"]) + + const search = await holdRoute(page, /\/api\/fs\/find\?(.*&)?query=beta(&|$)/) + await input.fill("beta") + await search.arrived + await expect(picker.getByRole("option")).toHaveCount(0) + + await input.press("Tab") + await expect(input).toHaveValue("beta") + + await input.press("Enter") + await expect(input).toHaveValue("C:\\OpenCode\\Picker\\beta\\") + await expect(picker.locator(".directory-picker-selection-text")).toHaveText("C:\\…\\Picker\\beta") + search.release() +}) + +test("a folder that cannot be listed leaves the root readable and retries when expanded", async ({ page }) => { + let failures = 0 + + const picker = await openPicker(page, { + fileList: (path) => { + if (path === `${directory}/locked`) { + failures += 1 + + return Promise.reject(new Error("Permission denied")) + } + + return path === directory ? ["locked", "open"].map((name) => fileNode(directory, name, "directory")) : [] + }, + }) + + // The root preloads its folders, so the locked one fails once before the user touches it. + await expect.poll(() => failures).toBe(1) + await picker.getByRole("treeitem", { name: "locked", exact: true }).click() + await expect.poll(() => failures).toBe(2) + + await expect(picker.getByText("Unable to read this folder")).toHaveCount(0) + await expect(picker.getByRole("treeitem", { name: "open", exact: true })).toBeVisible() + await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled() +}) + test("the folder picker's tree scrolls with the mouse wheel inside the modal", async ({ page }) => { const directory = "/projects/big" let listing = false diff --git a/packages/app/e2e/regression/home.spec.ts b/packages/app/e2e/regression/home.spec.ts index 4c41157822a9..85734ab509f0 100644 --- a/packages/app/e2e/regression/home.spec.ts +++ b/packages/app/e2e/regression/home.spec.ts @@ -1,7 +1,18 @@ import type { OpenCodeEvent } from "@opencode/client/promise" import { expect, test, type Page } from "@playwright/test" -import { expectPath, holdRoute, NO_PROVIDER, project, REMOTE_SERVER, seed, sessionHref, T0 } from "../utils/app" -import { mockOpenCodeServer } from "../utils/mock-server" +import { + expectPath, + holdRoute, + NO_PROVIDER, + project, + REMOTE_SERVER, + seed, + SERVER, + session, + sessionHref, + T0, +} from "../utils/app" +import { mockOpenCodeServer, mockServers } from "../utils/mock-server" import { fixture, mockStressTimeline } from "../utils/session-fixture" import { mockRemoteServer, mockWorkspace, newSessionLocation } from "../utils/workspace" import { APP_READY_TIMEOUT, expectAppVisible } from "../utils/waits" @@ -30,7 +41,10 @@ test("Home keeps the session list in every interface mode", async ({ page }) => await page.keyboard.press("Control+,") const settings = page.getByTestId("settings-screen") const option = settings.getByRole("radio", { name: mode, exact: true }) - await settings.getByRole("group", { name: "Interface layout", exact: true }).getByText(mode, { exact: true }).click() + await settings + .getByRole("group", { name: "Interface layout", exact: true }) + .getByText(mode, { exact: true }) + .click() await expect(option).toBeChecked() await settings.getByRole("button", { name: "Back to app", exact: true }).click() await expect(page).toHaveURL("/") @@ -124,13 +138,100 @@ test("the session context menu renames, exports, and deletes a Home session", as await expect(dialog).toContainText('Delete session "Renamed from Home"?') await expect(dialog.getByRole("button", { name: "Cancel", exact: true })).toBeFocused() - const removed = page.waitForRequest( - (request) => request.method() === "DELETE" && new URL(request.url()).pathname.endsWith(`/${fixture.targetID}`), - ) + const removed = await holdRoute(page, (url) => url.pathname.endsWith(`/session/${fixture.targetID}`), { + method: "DELETE", + }) - await dialog.getByRole("button", { name: "Delete session" }).click() - await removed + // A double click claims one delete: the dialog stays open, with both buttons disabled, until the server answers. + await dialog.getByRole("button", { name: "Delete session" }).dblclick() + await removed.arrived + await expect(dialog.getByRole("button", { name: "Delete session" })).toBeDisabled() + await expect(dialog.getByRole("button", { name: "Cancel", exact: true })).toBeDisabled() + removed.release() + await expect(dialog).toBeHidden() await expect(renamedRow).toBeHidden() + expect(removed.requests).toHaveLength(1) +}) + +test("a failed session list says so and loads again on Try again, instead of showing the empty state", async ({ + page, +}) => { + const earlier = { id: "ses_home_failed_load", title: "Listed after retry" } + await mockWorkspace(page, { name: "HomeLoad", sessions: [earlier], seed: { tabs: [] } }) + const list = /\/api\/session\?/ + await page.route(list, (route) => + route.request().method() === "GET" + ? route.fulfill({ + status: 500, + json: { message: "Index unavailable" }, + headers: { "access-control-allow-origin": "*" }, + }) + : route.fallback(), + ) + await page.goto("/") + + const alert = page.getByRole("alert").filter({ hasText: "Couldn't load sessions" }) + await expect(alert).toBeVisible({ timeout: APP_READY_TIMEOUT }) + await expect(page.getByText("Nothing here yet")).toHaveCount(0) + await expect(page.locator('[data-component="home-session-skeleton"]')).toHaveCount(0) + + await page.unroute(list) + await alert.getByRole("button", { name: "Try again", exact: true }).click() + await expect(row(page, earlier.title)).toBeVisible() + await expect(alert).toHaveCount(0) +}) + +test("tabbing out of session search closes its results, and tabbing back reopens them", async ({ page }) => { + const earlier = { id: "ses_home_search_tab", title: "Finished earlier" } + await mockWorkspace(page, { name: "HomeSearch", sessions: [earlier] }) + await page.goto("/") + const search = page.getByRole("textbox", { name: /Search sessions/ }) + const panel = page.locator('[data-component="home-session-search-panel"]') + await expect(row(page, earlier.title)).toBeVisible() + + await search.click() + await page.keyboard.type("Finished") + await expect(panel.getByRole("option")).toHaveCount(1) + await expect(panel.getByRole("option")).toContainText(earlier.title) + + // The clear button is part of the search; the next stop is outside it. + await page.keyboard.press("Tab") + await expect(search).not.toBeFocused() + await expect(panel).toBeVisible() + await page.keyboard.press("Tab") + await expect(panel).toHaveCount(0) + await expect(search).toHaveValue("Finished") + + await page.keyboard.press("Shift+Tab") + await page.keyboard.press("Shift+Tab") + await expect(search).toBeFocused() + await expect(panel.getByRole("option")).toContainText(earlier.title) +}) + +test("Escape cancels an inline rename whose save does not answer", async ({ page }) => { + const target = { id: "ses_home_rename_hang", title: "Rename me" } + await mockWorkspace(page, { name: "HomeRename", sessions: [target] }) + const save = await holdRoute(page, /\/api\/session\/ses_home_rename_hang$/, { method: "PATCH" }) + await page.goto("/") + const session = row(page, target.title) + await expect(session).toBeVisible() + + await session.click({ button: "right" }) + await page.getByRole("menuitem", { name: "Rename" }).click() + const title = page.locator('[data-component="home-session-rename"]') + await expect(title).toBeFocused() + await title.fill("Never saved") + await title.press("Enter") + await save.arrived + + // The input keeps focus while the save is pending, so Escape reaches it. + await expect(title).toBeFocused() + await expect(title).toHaveAttribute("aria-busy", "true") + await page.keyboard.press("Escape") + await expect(title).toHaveCount(0) + await expect(session).toBeFocused() + await expect(session).toContainText(target.title) + save.release() }) test("the Home shortcut focuses session search, and the Home button leaves focus alone", async ({ page }) => { @@ -256,6 +357,90 @@ test("Home migrates the directories an older build listed to the server's curren .toMatchObject({ usedProjectIDs: { local: ["proj_api", "proj_web"] }, projects: {} }) }) +test("selecting a Home project lists its worktrees once, however often the project updates", async ({ page }) => { + const listed = [entry("alpha", 2), entry("beta", 1)] + const view = await homeProjects(page, listed) + await seed(page, { usedProjects: { local: ["proj_alpha", "proj_beta"] } }) + const lists: string[] = [] + page.on("request", (request) => { + const url = new URL(request.url()) + + if (request.method() === "GET" && url.pathname === "/api/worktree") lists.push(url.searchParams.get("projectID")!) + }) + await page.goto("/") + await expect(view.rows).toHaveText(["alpha", "beta"]) + const alpha = page.locator('[data-component="home-project-row"]').filter({ hasText: "alpha" }) + + const refreshed = page.waitForRequest( + (request) => request.method() === "POST" && new URL(request.url()).pathname === "/api/worktree/refresh", + ) + + await alpha.click() + await expect(alpha).toHaveAttribute("data-selected", "") + await refreshed + + // Each update replaces the selected project's object in the store. + const renamed: OpenCodeEvent = { + id: "evt_home_worktrees", + created: T0, + type: "project.updated", + data: { ...listed[0]!, name: "alpha renamed" }, + } + + await view.server.push([renamed]) + await expect(view.rows).toHaveText(["alpha renamed", "beta"]) + + const beta = page.waitForRequest((request) => new URL(request.url()).searchParams.get("projectID") === "proj_beta") + await page.locator('[data-component="home-project-row"]').filter({ hasText: "beta" }).click() + await beta + expect(lists).toEqual(["proj_alpha", "proj_beta"]) +}) + +test("Home keeps a restored remote selection while the desktop server list loads", async ({ page }) => { + const local = session({ id: "ses_home_local", directory: "/repo", title: "Local session" }) + const remote = session({ id: "ses_home_remote", directory: "/remote/project", title: "Remote session" }) + const selection = { server: REMOTE_SERVER, directory: "/remote/project" } + + await mockServers(page, { + [SERVER]: { + directory: "/repo", + project: project({ id: "proj_local", directory: "/repo" }), + provider: NO_PROVIDER, + sessions: [local], + pageMessages: () => ({ items: [] }), + }, + [REMOTE_SERVER]: { + directory: selection.directory, + project: project({ id: "proj_remote", directory: selection.directory, name: "remote-project" }), + provider: NO_PROVIDER, + sessions: [remote], + pageMessages: () => ({ items: [] }), + }, + }) + await seed(page, { + servers: [{ url: REMOTE_SERVER, name: "Remote" }], + usedProjects: { [REMOTE_SERVER]: ["proj_remote"] }, + storage: { "opencode.global.dat:layout": { home: { selection } } }, + }) + // Desktop storage is asynchronous; the stored servers load after the layout here. + await page.goto( + `/e2e/utils/settings-wsl.html?${new URLSearchParams({ server: SERVER, mode: "stopped", storage: "async", hold: "^server$", path: "/" })}`, + ) + + // Until then Home shows this computer's sessions, not filtered by the remote server's directory. + await expect(row(page, local.title)).toBeVisible() + await page.getByRole("button", { name: "Load held storage", exact: true }).click() + + await expect(row(page, remote.title)).toBeVisible() + await expect( + page.locator('[data-component="home-project-row"]').filter({ hasText: "remote-project" }), + ).toHaveAttribute("data-selected", "") + await expect(row(page, local.title)).toHaveCount(0) + expect( + await page.evaluate(() => JSON.parse(localStorage.getItem("opencode.global.dat:layout") ?? "{}").home.selection), + ).toEqual(selection) +}) + test("Home shows loaded sessions before the location request resolves", async ({ page }) => { const location = await holdRoute(page, (url) => url.pathname === "/api/location") await openHome(page) diff --git a/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts b/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts index cb8ef2fc0473..227abf793915 100644 --- a/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts +++ b/packages/app/e2e/regression/mcp-workspace-toggle.spec.ts @@ -20,7 +20,16 @@ type Surface = "popover" | "dialog" | "settings" // Extensions page opened (Ctrl+,) from the session. async function open( page: Page, - input: { surface: Surface } & Pick, + input: { surface: Surface } & Pick< + MockServerConfig, + | "mcp" + | "onMcpAction" + | "integrations" + | "onIntegrationOAuth" + | "onIntegrationOAuthStatus" + | "onIntegrationOAuthComplete" + | "mcpResourceFailures" + >, ) { const requests: { path: string; directory: string }[] = [] page.on("request", (request) => { @@ -41,6 +50,9 @@ async function open( onMcpAction: input.onMcpAction, integrations: input.integrations, onIntegrationOAuth: input.onIntegrationOAuth, + onIntegrationOAuthStatus: input.onIntegrationOAuthStatus, + onIntegrationOAuthComplete: input.onIntegrationOAuthComplete, + mcpResourceFailures: input.mcpResourceFailures, }) await page.goto(sessionHref(sessionID)) @@ -147,12 +159,29 @@ for (const surface of ["popover", "dialog"] as const) { test("the MCP popover shows a failed server and reconnects it from its details", async ({ page }) => { const error = "Streamable HTTP error: Error POSTing to endpoint: 404 Not Found" + const again = "Streamable HTTP error: Error POSTing to endpoint: 503 Service Unavailable" + const retries = { connecting: false, failing: true } const view = await open(page, { surface: "popover", mcp: (target) => [ - { name: "figma-desktop", status: target !== workspace ? { status: "connected" } : { status: "failed", error } }, + { + name: "figma-desktop", + status: + target !== workspace + ? { status: "connected" } + : retries.connecting + ? { status: "pending" } + : { status: "failed", error }, + }, ], + // The first retry fails again with another error, reported by the refreshed status; the second connects. + onMcpAction: (input) => { + if (input.action !== "connect" || !retries.failing) return + retries.failing = false + + return { status: "failed", error: again } + }, }) const row = view.panel.locator(".session-mcp-row").filter({ hasText: "figma-desktop" }) @@ -164,14 +193,153 @@ test("the MCP popover shows a failed server and reconnects it from its details", const details = page.getByRole("dialog", { name: "figma-desktop", exact: true }) await expect(details).toHaveAccessibleDescription("Connection failed") await expect(details.getByText(error, { exact: true })).toBeVisible() - await details.getByRole("button", { name: "Try again", exact: true }).click() + const retry = details.getByRole("button", { name: "Try again", exact: true }) + const connect = await holdRoute(page, /\/api\/experimental\/mcp\/figma-desktop\/connect(?:\?|$)/, { method: "POST" }) + await retry.click() + await connect.arrived + // The server reports that it is connecting; the details stay open while the retry runs, and take no second retry. + retries.connecting = true + + const listed = page.waitForResponse((response) => { + const url = new URL(response.url()) + + return ( + response.request().method() === "GET" && + url.pathname === "/api/mcp" && + url.searchParams.get("location[directory]") === workspace + ) + }) + + await view.push([ + { + id: "evt_mcp_connecting", + created: 1, + type: "mcp.status.changed", + location: { directory: workspace }, + data: { server: "figma-desktop" }, + }, + ]) + await listed + await expect(details.getByText(error, { exact: true })).toBeVisible() + await expect(retry).toBeDisabled() + await expect(details.getByRole("button", { name: "Disable", exact: true })).toBeDisabled() + connect.release() + // A retry that fails again shows its new error in place. + await expect(details.getByText(again, { exact: true })).toBeVisible() + await expect(retry).toBeEnabled() + + const reconnect = await holdRoute(page, /\/api\/experimental\/mcp\/figma-desktop\/connect(?:\?|$)/, { + method: "POST", + }) + + await retry.click() + await reconnect.arrived + await page.keyboard.press("Escape") await expect(details).toBeHidden() + + // The details closed and opened again still show the retry the dialog started, and take no second connect. + if (await view.panel.isVisible()) await page.getByRole("button", { name: "Session details", exact: true }).click() + await expect(view.panel).toBeHidden() + await view.show() + await expect(view.toggle).toBeDisabled() + reconnect.release() + await expect(view.toggle).toHaveAccessibleDescription("Connected") + await expect(view.toggle).toBeEnabled() expect(view.requests.filter((request) => request.path.endsWith("/connect"))).toEqual([ { path: "/api/experimental/mcp/figma-desktop/connect", directory: workspace }, + { path: "/api/experimental/mcp/figma-desktop/connect", directory: workspace }, ]) +}) - if (!(await view.panel.isVisible())) await view.show() - await expect(view.toggle).toHaveAccessibleDescription("Connected") +test("the MCP dialog keeps a retrying server's error open, and its other servers stay free", async ({ page }) => { + const error = "Streamable HTTP error: Error POSTing to endpoint: 404 Not Found" + const again = "Streamable HTTP error: Error POSTing to endpoint: 503 Service Unavailable" + const retries = { connecting: false, failing: true } + + const view = await open(page, { + surface: "dialog", + mcp: (target) => [ + { + name: "figma-desktop", + status: + target !== workspace + ? { status: "connected" } + : retries.connecting + ? { status: "pending" } + : { status: "failed", error }, + }, + { name: "zeta-mcp", status: { status: "disabled" } }, + ], + // The first retry fails again with another error, reported by the refreshed status; the second connects. + onMcpAction: (input) => { + if (input.server !== "figma-desktop" || input.action !== "connect" || !retries.failing) return + retries.failing = false + + return { status: "failed", error: again } + }, + }) + + const details = page.getByRole("dialog", { name: "figma-desktop", exact: true }) + const retry = details.getByRole("button", { name: "Try again", exact: true }) + const figma = view.panel.getByRole("switch", { name: "figma-desktop", exact: true }) + const zeta = view.panel.getByRole("switch", { name: "zeta-mcp", exact: true }) + await view.panel.getByRole("button", { name: "View error for figma-desktop", exact: true }).click() + await expect(details.getByText(error, { exact: true })).toBeVisible() + + const connect = await holdRoute(page, /\/api\/experimental\/mcp\/figma-desktop\/connect(?:\?|$)/, { method: "POST" }) + await retry.click() + await connect.arrived + // The server reports that it is connecting; the error stays open while the retry runs, and takes no second retry. + retries.connecting = true + + const listed = page.waitForResponse((response) => { + const url = new URL(response.url()) + + return ( + response.request().method() === "GET" && + url.pathname === "/api/mcp" && + url.searchParams.get("location[directory]") === workspace + ) + }) + + await view.push([ + { + id: "evt_mcp_dialog_connecting", + created: 1, + type: "mcp.status.changed", + location: { directory: workspace }, + data: { server: "figma-desktop" }, + }, + ]) + await listed + await expect(details.getByText(error, { exact: true })).toBeVisible() + await expect(retry).toBeDisabled() + await expect(details.getByRole("button", { name: "Disable", exact: true })).toBeDisabled() + connect.release() + // A retry that fails again shows its new error in place. + await expect(details.getByText(again, { exact: true })).toBeVisible() + await expect(retry).toBeEnabled() + + const reconnect = await holdRoute(page, /\/api\/experimental\/mcp\/figma-desktop\/connect(?:\?|$)/, { + method: "POST", + }) + + await retry.click() + await reconnect.arrived + await details.getByRole("button", { name: "Navigate back", exact: true }).click() + await expect(details).toBeHidden() + + // While figma-desktop connects, only its own row waits; another server still toggles. + await expect(figma).toBeDisabled() + await expect(zeta).toBeEnabled() + view.requests.length = 0 + await view.panel.getByRole("option").filter({ hasText: "zeta-mcp" }).locator('[data-slot="switch-control"]').click() + await expect(zeta).toBeChecked() + expect(view.requests).toContainEqual({ path: "/api/experimental/mcp/zeta-mcp/connect", directory: workspace }) + await expect(figma).toBeDisabled() + reconnect.release() + await expect(figma).toHaveAccessibleDescription("Connected") + await expect(figma).toBeEnabled() }) for (const surface of ["dialog"] as const) { @@ -392,6 +560,74 @@ for (const surface of ["popover", "dialog"] as const) { }) } +for (const surface of ["popover", "dialog"] as const) { + test(`a pasted MCP sign-in from the ${surface} submits once and recovers from a failed refresh`, async ({ + page, + context, + }) => { + const state = { signedIn: false, recovered: false } + const pasted: unknown[] = [] + await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" })) + + const view = await open(page, { + surface, + mcp: () => [ + { + name: "figma-desktop", + integrationID: "figma-oauth", + status: state.signedIn ? { status: "connected" } : { status: "needs_auth", error: "Sign in required" }, + }, + ], + integrations: [{ id: "figma-oauth", name: "Figma", methods: [{ id: "oauth", type: "oauth" }], connections: [] }], + onIntegrationOAuth: () => ({ url: "https://auth.example.test/authorize", paste: true }), + onIntegrationOAuthStatus: () => (state.signedIn ? "complete" : "pending"), + // The server accepts the pasted URL and finishes the sign-in. + onIntegrationOAuthComplete: (input) => { + pasted.push(input.body) + state.signedIn = true + }, + // The MCP lists fail to reload after the sign-in until the user retries. + mcpResourceFailures: () => state.signedIn && !state.recovered, + }) + + const complete = await holdRoute( + page, + /\/api\/integration\/figma-oauth\/connect\/oauth\/[^/?]+\/complete(?:\?|$)/, + { + method: "POST", + }, + ) + + await view.panel.getByRole("button", { name: "Sign in to figma-desktop", exact: true }).click() + const dialog = page.getByRole("dialog", { name: "Sign in to figma-desktop", exact: true }) + const redirect = dialog.getByRole("textbox", { name: "Redirect URL", exact: true }) + + // The details popover closes behind the dialog and returns focus to its trigger; type once that settled. + if (surface === "popover") await expect(view.panel).toBeHidden() + + await redirect.fill("http://127.0.0.1:19876/callback?code=abc") + + // A second Enter while the paste is in flight does not send it again. + await redirect.press("Enter") + await expect(redirect).toHaveAttribute("readonly", "") + await redirect.press("Enter") + await complete.arrived + complete.release() + + // The sign-in succeeded but the lists did not reload: the dialog offers a retry instead of waiting forever. + const retry = dialog.getByRole("button", { name: "Try again", exact: true }) + await expect(retry).toBeVisible() + await expect(dialog.getByText("Waiting for authorization…", { exact: true })).toHaveCount(0) + await expect(redirect).toHaveCount(0) + + state.recovered = true + await retry.click() + await expect(dialog).toHaveCount(0) + expect(pasted).toEqual([expect.objectContaining({ code: "http://127.0.0.1:19876/callback?code=abc" })]) + expect(complete.requests).toHaveLength(1) + }) +} + for (const surface of ["popover", "dialog"] as const) { test(`long MCP names keep their status and controls visible in the ${surface}`, async ({ page }) => { const names = ["connected", "disabled", "failed", "needs_auth"].map( diff --git a/packages/app/e2e/regression/mobile-model-pickers.spec.ts b/packages/app/e2e/regression/mobile-model-pickers.spec.ts index af63687b0693..1ccb5fb69309 100644 --- a/packages/app/e2e/regression/mobile-model-pickers.spec.ts +++ b/packages/app/e2e/regression/mobile-model-pickers.spec.ts @@ -212,6 +212,41 @@ test("desktop model button shows only the choose-model hint, not the model detai await expect(tooltip.getByText("Input & Output", { exact: true })).toHaveCount(0) }) +test("model dialog flyout waits after the arrow keys and cools down after it closes", async ({ page }) => { + const { model, dialog } = await openDesktopPicker(page, "ltr") + const flyout = dialog.locator('[data-slot="model-dialog-flyout"]') + const search = dialog.getByRole("combobox", { name: "Search models", exact: true }) + const rowA = dialog.locator('[data-option-key="opencode:mobile-a"]') + const rowB = dialog.locator('[data-option-key="opencode:mobile-b"]') + await model.click() + await expect(search).toBeFocused() + // See "tab preview opens cold" in tabs.spec.ts: pause at a fixed offset from an explicit install time. + const start = Date.now() + await page.clock.install({ time: start }) + await page.clock.pauseAt(start + 10_000) + + // The arrow keys take over before the hover's open delay ends, so its flyout never opens. + await rowA.hover() + await search.press("ArrowDown") + await page.clock.runFor(200) + await expect(rowB).toHaveAttribute("data-active", "") + await expect(flyout).toHaveCount(0) + + await rowB.hover() + await page.clock.runFor(200) + await expect(flyout.getByRole("menuitemradio", { name: "max", exact: true })).toBeVisible() + + // Once the flyout has been closed for a moment, the next row waits for the open delay again. + await page.mouse.move(5, 5) + await expect(flyout).toHaveCount(0) + await page.clock.runFor(400) + await rowA.hover() + await expect(rowA).toHaveAttribute("data-active", "") + await expect(flyout).toHaveCount(0) + await page.clock.runFor(200) + await expect(flyout.getByRole("menuitemradio", { name: "balanced", exact: true })).toBeVisible() +}) + test("model dialog shows a summary and only the default variant for models without variants", async ({ page }) => { const { model, dialog } = await openDesktopPicker(page, "ltr") const flyout = dialog.locator('[data-slot="model-dialog-flyout"]') diff --git a/packages/app/e2e/regression/multi-server.spec.ts b/packages/app/e2e/regression/multi-server.spec.ts index 4809eb2ac5a0..e42837e00402 100644 --- a/packages/app/e2e/regression/multi-server.spec.ts +++ b/packages/app/e2e/regression/multi-server.spec.ts @@ -1,5 +1,15 @@ import { expect, test, type Page } from "@playwright/test" -import { REMOTE_SERVER, SERVER, expectPath, project, seed, session, sessionHref, type TabSeed } from "../utils/app" +import { + REMOTE_SERVER, + SERVER, + expectPath, + holdRoute, + project, + seed, + session, + sessionHref, + type TabSeed, +} from "../utils/app" import { mockServers, type MockServerConfig } from "../utils/mock-server" import { expectSessionTitle } from "../utils/waits" @@ -151,7 +161,9 @@ test("a remote session whose server signed the app out asks to sign in again, th }) await seed(page, { storage: { - "opencode.global.dat:server": { list: [{ type: "http", http: { url: REMOTE_SERVER, password: "old-password" } }] }, + "opencode.global.dat:server": { + list: [{ type: "http", http: { url: REMOTE_SERVER, password: "old-password" } }], + }, }, }) await page.goto(sessionHref(sessionB.id, REMOTE_SERVER)) @@ -160,6 +172,14 @@ test("a remote session whose server signed the app out asks to sign in again, th await expect(signedOut).toBeVisible() await page.getByRole("button", { name: "Sign in again", exact: true }).click() const editor = page.getByRole("dialog", { name: "Edit server" }) + + // An empty address explains itself instead of closing the dialog. + await editor.getByRole("button", { name: "Use password", exact: true }).click() + await editor.getByLabel("Server address", { exact: true }).fill("") + await editor.getByRole("button", { name: "Save", exact: true }).click() + await expect(editor.getByRole("alert")).toHaveText("Enter a valid HTTP or HTTPS server address.") + await editor.getByRole("button", { name: "Use pairing link", exact: true }).click() + await editor.getByLabel("Pairing link", { exact: true }).fill(`${REMOTE_SERVER}/auth/connect/one-time-code`) await editor.getByRole("button", { name: "Save", exact: true }).click() @@ -168,6 +188,80 @@ test("a remote session whose server signed the app out asks to sign in again, th await expect(signedOut).toHaveCount(0) }) +// The session route waits this long for an uncached session before it calls the server unreachable. +const RESOLUTION_TIMEOUT_MS = 30_000 + +// How often the app checks each server's health. +const SERVER_HEALTH_POLL_MS = 10_000 + +test("a session its server never answers for says the server is unreachable, then opens", async ({ page }) => { + const late = session({ id: "ses_server_a_late", directory: directoryA, title: "Late session" }) + const sessions = [sessionA] + await setup(page, { tabs: [], a: { sessions } }) + const metadata = await holdRoute(page, new RegExp(`/api/session/${late.id}(\\?|$)`), { method: "GET" }) + await page.clock.install() + await page.goto(sessionHref(late.id)) + await metadata.arrived + const unreachable = page.getByText("Can't reach this server", { exact: true }) + await expect(unreachable).toHaveCount(0) + + await page.clock.fastForward(RESOLUTION_TIMEOUT_MS) + await expect(unreachable).toBeVisible() + await expect(page.getByRole("button", { name: "Close Tab", exact: true })).toBeVisible() + + // The request that hung still fills the cache when it answers. + sessions.push(late) + metadata.release() + await expectSessionTitle(page, late.title) + await expect(unreachable).toHaveCount(0) +}) + +// The inbox shows what it has once this long passes, even while a server still has not answered. +const INBOX_SETTLE_TIMEOUT_MS = 10_000 + +test("one server that never answers the inbox index does not hide the other server's sessions", async ({ page }) => { + await setup(page, { tabs: [] }) + await seed(page, { settings: { appearance: { tabLayout: "inbox" } } }) + + const index = await holdRoute(page, new RegExp(`^${REMOTE_SERVER}/api/session\\?(.*&)?order=desc`), { + method: "GET", + }) + + await page.clock.install() + await page.goto("/") + await index.arrived + + const inbox = page.locator('[data-slot="sidebar-inbox"]') + const row = inbox.locator('[data-slot="sidebar-inbox-item"]').filter({ hasText: sessionA.title }) + await expect(inbox).toHaveAttribute("aria-busy", "true") + await expect(row).toHaveCount(0) + + await page.clock.fastForward(INBOX_SETTLE_TIMEOUT_MS) + await expect(inbox).toHaveAttribute("aria-busy", "false") + await expect(row).toBeVisible() +}) + +test("an open session stays visible while its server stops answering", async ({ page }) => { + const late = session({ id: "ses_server_a_late", directory: directoryA, title: "Late session" }) + await setup(page, { tabs: [sessionA.id, late.id], a: { sessions: [sessionA] } }) + await holdRoute(page, new RegExp(`/api/session/${late.id}(\\?|$)`), { method: "GET" }) + await page.clock.install() + await page.goto(sessionHref(sessionA.id)) + await expectSessionTitle(page, sessionA.title) + + await page.route(`${SERVER}/api/info`, (route) => route.fulfill({ status: 503, body: "" })) + await page.clock.fastForward(SERVER_HEALTH_POLL_MS) + const unreachable = page.getByText("Can't reach this server", { exact: true }) + + // An uncached session on the same server proves the app now considers the server down. + await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(late.id)}"])`).click() + await expect(unreachable).toBeVisible() + + await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(sessionA.id)}"])`).click() + await expectSessionTitle(page, sessionA.title) + await expect(unreachable).toHaveCount(0) +}) + test("auto-accept responds for an unfocused server session and its child", async ({ page }) => { const view = await setup(page, { tabs: [sessionA.id, { session: sessionB.id, server: REMOTE_SERVER }] }) await page.goto(sessionHref(sessionA.id)) diff --git a/packages/app/e2e/regression/new-session.spec.ts b/packages/app/e2e/regression/new-session.spec.ts index 3d2a8cc820fd..4a975d008b75 100644 --- a/packages/app/e2e/regression/new-session.spec.ts +++ b/packages/app/e2e/regression/new-session.spec.ts @@ -1,5 +1,6 @@ import { expect, test, type Locator, type Page } from "@playwright/test" -import type { OpenCodeEvent, WorktreeDirectory } from "@opencode/client/promise" +import type { OpenCodeEvent, SessionMessageInfo, WorktreeDirectory } from "@opencode/client/promise" +import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { draftHref, expectPath, NO_PROVIDER, project, provider, seed, sessionHref, T0 } from "../utils/app" import { mockOpenCodeServer } from "../utils/mock-server" import { @@ -91,6 +92,35 @@ test("the location shortcuts choose worktrees from every state and keep cycling" await expect(view.editor).toBeFocused() }) +test("Local shows and targets the main checkout when the draft opened in a worktree", async ({ page }) => { + const root = "C:/OpenCode/LocalFromWorktree" + + const worktree = `${root}/.worktrees/quiet-river` + + const created: unknown[] = [] + + const view = await openDraft(page, { + name: "LocalFromWorktree", + project: { sandboxes: [worktree] }, + worktrees: () => [{ directory: root }, { directory: worktree, strategy: "git" }], + vcs: (directory) => + directory === worktree + ? { current: "worktree-branch", default: "dev" } + : { current: "checkout-branch", default: "dev" }, + onSessionCreate: (body) => void created.push(body.location), + seed: { tabs: [{ draft: "draft_localfromworktree", directory: worktree }] }, + }) + + const screen = page.locator('[data-component="new-session"]') + + await expect(newSessionWorktree(page)).toHaveText("Local") + await expect(screen.getByText("checkout-branch", { exact: true })).toBeVisible() + await expect(screen.getByText("worktree-branch", { exact: true })).toHaveCount(0) + await view.editor.fill("Run in the main checkout") + await submit(page).click() + await expect.poll(() => created).toEqual([{ directory: root }]) +}) + for (const binding of ["custom", "none"]) { test(`the picker tooltips reflect ${binding} shortcuts`, async ({ page }) => { const view = await openDraft(page, { @@ -698,6 +728,46 @@ test("a pending worktree session shows immediately, keeps its draft, and hands o await expect(label).toHaveText("Generated session title") }) +test("a variant picked on a worktree draft stays with the session it starts, even while another tab is open", async ({ + page, +}) => { + const mock = await openWorktreeDraft(page, { + ...pendingDraft, + provider: provider({ id: "pending-model", name: "Pending Model", variants: { balanced: {}, high: {} } }), + }) + + const composer = page.locator('[data-component="composer"]') + const variant = composer.getByRole("button", { name: "Choose model variant", exact: true }) + + // The Default variant control shows only while the pointer is over the composer. + await composer.hover() + await variant.click() + await page.getByRole("menuitemradio", { name: "high", exact: true }).click() + await expect(variant).toHaveText("high") + const pending = await submitPending(page, mock) + + // The session starts while another tab shows, so nothing shows the worktree when its selection is handed over. + await tabLink(page, otherID).click() + await expectPath(page, sessionHref(otherID)) + mock.worktree.resolve({ status: 200, json: { directory: workspace } }) + await expect.poll(() => mock.prompts.map((prompt) => prompt.sessionID)).toEqual([pending.sessionID]) + expect(mock.creates).toEqual([ + expect.objectContaining({ + id: pending.sessionID, + location: { directory: workspace }, + model: expect.objectContaining({ id: "pending-model", variant: "high" }), + }), + ]) + + await tabLink(page, pending.sessionID).click() + await expect(page).toHaveURL(pending.url) + await expect(pending.message.locator('[data-slot="user-message-text"]')).toHaveText(text) + await expect(variant).toHaveText("high") + await page.reload() + await expect(composer.locator('[data-action="composer-model"]')).toHaveText("Pending Model") + await expect(variant).toHaveText("high") +}) + test("a pending worktree session keeps Session as its mobile title until the generated title arrives", async ({ page, }) => { @@ -790,6 +860,45 @@ test("the title and message stay stable through worktree creation", async ({ pag await expect.poll(() => mock.calls).toEqual(["worktree", "session", "prompt"]) }) +test("the created session's composer keeps focus and a caret placed mid-draft", async ({ page }) => { + const mock = await openWorktreeDraft(page, pendingDraft) + const pending = await submitPending(page, mock) + await draftFollowUp(page) + // The start of the second line: not where focusing the editor alone would put the caret. + await editor(page).press("ControlOrMeta+End") + await editor(page).press("Home") + mock.worktree.resolve({ status: 200, json: { directory: workspace } }) + + await expect(page.locator("[data-session-title]").getByRole("heading", { level: 1 })).toHaveText( + "Created workspace session", + ) + await expect(pending.shimmer).toHaveCount(0) + await expect(editor(page)).toHaveText(followUp) + await expect(editor(page)).toBeFocused() + // Types into whatever holds focus, without focusing the editor again. + await page.keyboard.type("Also: ") + await expect(editor(page)).toHaveText(followUp.replace("\n", "\nAlso: ")) +}) + +test("a user who leaves the pending composer keeps focus there once the session is created", async ({ page }) => { + const mock = await openWorktreeDraft(page, pendingDraft) + const pending = await submitPending(page, mock) + await draftFollowUp(page) + await pending.shimmer.click() + await expect(editor(page)).not.toBeFocused() + mock.worktree.resolve({ status: 200, json: { directory: workspace } }) + + await expect(page.locator("[data-session-title]").getByRole("heading", { level: 1 })).toHaveText( + "Created workspace session", + ) + await expect(pending.shimmer).toHaveCount(0) + await expect(editor(page)).toHaveText(followUp) + await expect(submit(page)).toBeEnabled() + await expect(editor(page)).not.toBeFocused() + await expect.poll(() => mock.calls).toEqual(["worktree", "session", "prompt"]) + await expect(editor(page)).not.toBeFocused() +}) + for (const row of [ { failure: "worktree", followUp: true, calls: ["worktree"] }, { failure: "session", followUp: true, calls: ["worktree", "session"] }, @@ -891,6 +1000,102 @@ test("keeps the draft on the main checkout when session creation fails, then ret await expect(page.locator('[data-component="user-message"] [data-slot="user-message-text"]')).toHaveText(text) }) +// Before, a create whose response stalled left the pending tab on "Starting session" with the prompt locked. +test("a stalled session create returns to the draft, and the Session it creates later is deleted unused", async ({ + page, +}) => { + const held = Promise.withResolvers() + const creates: string[] = [] + const prompts: string[] = [] + await page.clock.install() + + const view = await openDraft(page, { + ...pendingDraft, + onPrompt: (prompt) => void prompts.push(prompt.sessionID), + onSessionCreate: async (body, attempt) => { + creates.push(String(body.id)) + + if (attempt === 1) await held.promise + }, + }) + + await view.editor.fill(text) + await submit(page).click() + await expect.poll(() => creates.length).toBe(1) + const stalled = creates[0]! + await expectPath(page, sessionHref(stalled)) + await expect(page.locator('[data-component="session-preparing"]').getByRole("status")).toContainText( + "Starting session", + ) + + // The create phase's time limit, below the request queue's 60 s wait for response headers. + await page.clock.fastForward(30_000) + + await expectPath(page, draftHref(draftID)) + await expect(page.getByText("Failed to create session", { exact: true })).toBeVisible() + await expect( + page.getByText("The server took too long to respond. Send again to retry.", { exact: true }), + ).toBeVisible() + await expect(view.editor).toHaveText(text) + await expect(submit(page)).toBeEnabled() + await expect(tabLink(page, stalled)).toHaveCount(0) + + const removed = page.waitForRequest( + (request) => request.method() === "DELETE" && new URL(request.url()).pathname === `/api/session/${stalled}`, + ) + + held.resolve() + await removed + + await submit(page).click() + + await expect.poll(() => creates.length).toBe(2) + await expect.poll(() => prompts).toEqual([creates[1]]) + await expectPath(page, sessionHref(creates[1]!)) + await expect(page.locator('[data-component="user-message"] [data-slot="user-message-text"]')).toHaveText(text) +}) + +test("a new session's first prompt stays once its missed admission echo resyncs the session", async ({ page }) => { + const messages: SessionMessageInfo[] = [] + const created: string[] = [] + + // The mock admits the prompt without its session.inbox.enqueued echo. + const view = await openDraft(page, { + ...pendingDraft, + pageMessages: () => ({ items: messages }), + onSessionCreate: (body) => void created.push(String(body.id)), + seed: { settings: { general: { timelineDetail: timelinePresets[0].value } } }, + }) + + await view.editor.fill(text) + await submit(page).click() + await expect.poll(() => created).toHaveLength(1) + const sessionID = created[0]! + await expectPath(page, sessionHref(sessionID)) + const prompt = page.locator('[data-component="user-message"] [data-slot="user-message-text"]') + await expect(prompt).toHaveText([text]) + + // Another client switches the agent. Only its own notice shows: the admitted prompt no longer projects one. + messages.push({ + id: "msg_first_agent_plan", + type: "agent-switched", + agent: "plan", + previous: "build", + time: { created: T0 }, + }) + await view.push([ + { + id: "evt_first_agent_plan", + type: "session.agent.selected", + created: T0, + durable: { aggregateID: sessionID, seq: 1, version: 1 }, + data: { sessionID, agent: "plan" }, + }, + ]) + await expect(page.locator('[data-slot="session-timeline-notice"]')).toHaveText([/^Agent changed\s*Build → Plan$/]) + await expect(prompt).toHaveText([text]) +}) + test("restores the draft after closing and revisiting a pending session that fails", async ({ page }) => { const mock = await openWorktreeDraft(page, pendingDraft) const pending = await submitPending(page, mock) @@ -1116,6 +1321,17 @@ test("the location dialog separates added projects from server projects and tags await search.fill("no-worktree-matches") await expect(options).toHaveCount(0) await expect(dialog.getByRole("separator")).toHaveCount(0) + // Open project from the worktree step returns to that step with its search, not to the projects. + const open = (await page.evaluate(() => navigator.platform.includes("Mac"))) ? "Meta+o" : "Control+o" + await search.fill("open") + await page.keyboard.press(open) + await expect(back).toHaveText("Servers") + await expect(search).toHaveValue("") + await page.keyboard.press("Escape") + await expect(back).toHaveText("Run session in") + await expect(search).toHaveValue("open") + await expect(options.locator(".command-palette-title")).toHaveText(["opencode", "New worktree", "opencode-beta"]) + await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") await search.fill("") await expect(options.nth(0)).toHaveAttribute("aria-selected", "true") await page.keyboard.press("Backspace") @@ -1127,7 +1343,7 @@ test("the location dialog separates added projects from server projects and tags await expect(rows.nth(0)).toHaveAttribute("aria-selected", "true") await page.keyboard.press("ArrowUp") await expect(options.nth(3)).toHaveAttribute("aria-selected", "true") - await page.keyboard.press((await page.evaluate(() => navigator.platform.includes("Mac"))) ? "Meta+o" : "Control+o") + await page.keyboard.press(open) await expect(back).toHaveText("Servers") // The server the app runs beside shows its hostname and "This computer" instead of its address. await expect(options).toHaveText(["hailmaryThis computer", "apollo"]) diff --git a/packages/app/e2e/regression/review.spec.ts b/packages/app/e2e/regression/review.spec.ts index 94456f7393c1..90ff4ddc3e35 100644 --- a/packages/app/e2e/regression/review.spec.ts +++ b/packages/app/e2e/regression/review.spec.ts @@ -151,6 +151,38 @@ test("a rejected Git init releases its session's button without showing an error await expect(init).toBeEnabled() }) +test("a created Git repository whose project refresh fails still refreshes the session without an error", async ({ + page, +}) => { + await openSession(page, { + name: "ReviewInitRefresh", + project: { vcs: undefined }, + onVcsInit: () => undefined, + sessions: [{ id: "ses_init_refresh", title: "Initialize Refresh" }], + seed: { + panes: { ses_init_refresh: { review: true } }, + storage: reviewTabs("C:/OpenCode/ReviewInitRefresh", "ses_init_refresh"), + }, + }) + const panel = page.locator("#review-panel") + const init = panel.getByRole("button", { name: "Create Git repository", exact: true }) + await expect(init).toBeEnabled() + + // The repository is created; the project list refresh after it fails. + await page.route(/\/api\/project(\?|$)/, (route) => + route.fulfill({ status: 500, headers: { "access-control-allow-origin": "*" }, json: {} }), + ) + const created = page.waitForResponse((item) => new URL(item.url()).pathname === "/api/vcs/init") + const project = page.waitForResponse((item) => new URL(item.url()).pathname === "/api/project") + const session = page.waitForResponse((item) => new URL(item.url()).pathname === "/api/session/ses_init_refresh") + await init.click() + expect((await created).status()).toBe(204) + expect((await project).status()).toBe(500) + expect((await session).status()).toBe(200) + await expect(panel.getByRole("button", { name: "Creating Git repository…", exact: true })).toHaveCount(0) + await expect(page.getByText("Request failed", { exact: true })).toHaveCount(0) +}) + test("opens file picker launchers when randomUUID is unavailable on insecure HTTP origins", async ({ page }) => { await page.addInitScript(() => { Object.defineProperty(globalThis, "isSecureContext", { configurable: true, value: false }) @@ -672,6 +704,64 @@ test("file tree expands Windows paths and scrolls long names in both directions" await expect(panel.getByText("contents:frontend/app.ts", { exact: true })).toBeVisible() }) +test("the file tree follows a folder the review closes and lists a recreated folder's files", async ({ page }) => { + const directory = "C:/OpenCode/TreeFollow" + const disk = { src: true } + + const workspace = await openSession(page, { + name: "TreeFollow", + vcsDiff: [fileDiff("src/a.ts")], + fileList: (path) => { + if (!disk.src) return path ? [] : [fileNode(directory, "README.md")] + + if (path === "src") return [fileNode(directory, "src/a.ts")] + + return path ? [] : [fileNode(directory, "src", "directory"), fileNode(directory, "README.md")] + }, + fileContent: (path) => ({ type: "text", content: `contents:${path}` }), + seed: { + panes: { ses_treefollow: { review: true } }, + storage: { "opencode.global.dat:review-panel-v2": { sidebarOpened: true } }, + }, + }) + + const panel = page.locator("#review-panel") + const tab = (name: string) => panel.getByRole("tab", { name, exact: true }) + // Only the selected tab's tree is visible; the file browser stays mounted, hidden, behind the review. + const folder = panel.getByRole("treeitem", { name: "src" }) + const file = panel.getByRole("treeitem", { name: "a.ts" }) + + await openReviewLauncher(panel) + await expect(file).toBeVisible() + await openFileLauncher(panel) + await expect(tab("Open file")).toHaveAttribute("aria-selected", "true") + await folder.click() + await expect(folder).toHaveAttribute("aria-expanded", "true") + await expect(file).toBeVisible() + + // The review shares the workspace's folders: closing one there closes it in the file browser too. + await panel.locator("#session-side-panel-review-tab").click() + await expect(folder).toHaveAttribute("aria-expanded", "true") + await folder.click() + await expect(folder).toHaveAttribute("aria-expanded", "false") + await tab("Open file").click() + await expect(folder).toHaveAttribute("aria-expanded", "false") + await expect(file).toHaveCount(0) + + // A deleted folder takes its files with it, so they show again once it is recreated and opened. + await folder.click() + await expect(file).toBeVisible() + disk.src = false + await workspace.push([filesystemEvent(directory, "src", "unlink")]) + await expect(folder).toHaveCount(0) + disk.src = true + await workspace.push([filesystemEvent(directory, "src", "add")]) + await expect(folder).toHaveAttribute("aria-expanded", "false") + await folder.click() + await expect(folder).toHaveAttribute("aria-expanded", "true") + await expect(file).toBeVisible() +}) + test("rereads a file each time an artifact link opens it", async ({ page }) => { // Enough lines to scroll the code view, ending in the draft's name. const draft = (name: string) => [...Array.from({ length: 200 }, (_, index) => `item ${index + 1}`), name].join("\n") @@ -739,7 +829,7 @@ test("rereads a file each time an artifact link opens it", async ({ page }) => { await expect(panel.getByText("second draft", { exact: true })).toHaveCount(0) // A restored file tab whose file was deleted shows its inline not-found state without a toast; clicking a broken link - // when no tab is open for it shows the toast. + // when no tab is open for it shows one toast. await page.route("**/api/fs/read/shopping.txt*", (route) => route.fulfill({ status: 404, @@ -755,6 +845,13 @@ test("rereads a file each time an artifact link opens it", async ({ page }) => { await expect(panel.getByText("File not found: shopping.txt", { exact: true })).toBeVisible() await expect(page.getByText("Failed to load file", { exact: true })).toHaveCount(0) + // Behind another tab, the deleted file's tab is what its link selects: the click never does nothing. + await page.getByRole("button", { name: "Toggle session context" }).click() + await expect(missingTab).toHaveAttribute("aria-selected", "false") + await link.click() + await expect(missingTab).toHaveAttribute("aria-selected", "true") + await expect(page.getByText("Failed to load file", { exact: true })).toHaveCount(0) + await missingTab.locator("..").getByRole("button", { name: "Close tab" }).click() await expect(missingTab).toHaveCount(0) await link.click() @@ -762,6 +859,61 @@ test("rereads a file each time an artifact link opens it", async ({ page }) => { await expect(missingTab).toHaveCount(0) }) +// A change reported while a file's read is in flight used to join that read, so the tab kept the bytes from before the +// change until the next change. +test("a file changed during its read shows the change", async ({ page }) => { + const reads: string[] = [] + const arrived = Promise.withResolvers() + const held = Promise.withResolvers() + + const messages = [ + { id: "msg_prompt", type: "user", text: "Update the lists", time: { created: 1 } }, + { + id: "msg_reply", + type: "assistant", + agent: "build", + model: { id: "test", providerID: "opencode" }, + content: [{ type: "text", text: "Updated [notes.txt](notes.txt) and [shopping.txt](shopping.txt)." }], + time: { created: 2, completed: 3 }, + }, + ] satisfies SessionMessageInfo[] + + const workspace = await openSession(page, { + name: "FileReadRace", + fileList: () => [], + fileContent: async (path) => { + reads.push(path) + + if (path !== "shopping.txt") return `contents:${path}` + + if (reads.filter((item) => item === path).length > 1) return "after change" + arrived.resolve() + await held.promise + + return "before change" + }, + pageMessages: () => ({ items: messages }), + }) + + const panel = page.locator("#review-panel") + await page.getByRole("link", { name: "notes.txt", exact: true }).click() + await expect(panel.getByText("contents:notes.txt", { exact: true })).toBeVisible() + + await page.getByRole("link", { name: "shopping.txt", exact: true }).click() + await arrived.promise + // Events arrive in order, so the reread of notes.txt shows that the change to shopping.txt was handled before it. + await workspace.push([ + filesystemEvent(workspace.directory, "shopping.txt", "change"), + filesystemEvent(workspace.directory, "notes.txt", "change"), + ]) + await expect.poll(() => reads.filter((item) => item === "notes.txt").length).toBe(2) + held.resolve() + + await expect(panel.getByRole("tab", { name: "shopping.txt" })).toHaveAttribute("aria-selected", "true") + await expect(panel.getByText("after change", { exact: true })).toBeVisible() + await expect(panel.getByText("before change", { exact: true })).toHaveCount(0) +}) + test("artifact actions copy and download content, switch source, and follow the selected file's capabilities", async ({ page, context, @@ -769,6 +921,30 @@ test("artifact actions copy and download content, switch source, and follow the await context.grantPermissions(["clipboard-read", "clipboard-write"]) const source = '' const table = 'name,role\n"Jensen, Oliver",Researcher\nIsabella,Support' + const broken = ' getComputedStyle(element, "::after").borderTopStyle)).toBe("solid") @@ -876,6 +1086,16 @@ test("artifact actions copy and download content, switch source, and follow the const bar = (await toolbar.boundingBox())! expect(surface.y - bar.y - bar.height).toBe(1) await expect(panel.getByRole("group", { name: "Preview controls", exact: true })).toHaveCount(0) + await copy.click() + // Chromium writes CRLF to the Windows clipboard. + await expect + .poll(() => page.evaluate(() => navigator.clipboard.readText()).then((text) => text.replace(/\r\n/g, "\n"))) + .toBe(notes) + await page.getByRole("button", { name: "Dismiss", exact: true }).click() + await sourceAction.click() + await expect(paper).toHaveCount(0) + await expect(panel.locator('diffs-container [data-line="1"]')).toHaveText("---") + await expect(panel.locator('diffs-container [data-line="2"]')).toContainText("description: Release checklist") await page.getByRole("link", { name: "Binary", exact: true }).click() await expect(panel.getByText(/Binary file/)).toBeVisible() @@ -886,6 +1106,13 @@ test("artifact actions copy and download content, switch source, and follow the await expect(page.getByRole("menuitem", { name: "Download", exact: true })).toHaveCount(0) await page.getByRole("menuitem", { name: "Copy path", exact: true }).click() await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(`${workspace.directory}/sample.bin`) + + // A text SVG that fails to decode shows the binary placeholder but can still show its source. + await page.getByRole("link", { name: "Broken", exact: true }).click() + await expect(toolbar.getByText("broken.svg", { exact: true })).toBeVisible() + await expect(panel.getByText("Couldn't load this file.", { exact: true })).toBeVisible() + await toolbar.getByRole("button", { name: "View source", exact: true }).click() + await expect(panel.locator("diffs-container")).toContainText(broken) }) test("Markdown and DOCX sheets stay aligned when switching at wide and narrow preview widths", async ({ page }) => { @@ -980,7 +1207,9 @@ test("Markdown and DOCX sheets stay aligned when switching at wide and narrow pr await expect(markdown.getByRole("heading", { name: "Document spacing", exact: true })).toBeVisible() await expect.poll(() => edges(markdown)).toEqual(reference) await expect.poll(() => toolbar.boundingBox()).toEqual(header) - expect(await canvas!.evaluate((element) => element.isConnected && Number(element.getAttribute("width")) > 0)).toBe(true) + expect(await canvas!.evaluate((element) => element.isConnected && Number(element.getAttribute("width")) > 0)).toBe( + true, + ) await panel.getByRole("tab", { name: "other.docx", exact: true }).click() await expect(word).toHaveAttribute("data-e2e-probe", "other-warm") await panel.getByRole("tab", { name: "notes.md", exact: true }).click() @@ -1133,6 +1362,28 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy await expect(stage).toHaveAttribute("data-zoom", "actual") expect((await image.boundingBox())!.x).toBeCloseTo(scrolled.x + 30, 1) expect((await image.boundingBox())!.y).toBeCloseTo(scrolled.y + 20, 1) + // A pan whose release the image never heard ends on the next move without the button, and pans nothing. + const touched = (await image.boundingBox())! + await page.mouse.down() + await expect(image).toHaveCSS("cursor", "grabbing") + await image.evaluate( + (element, point) => + element.dispatchEvent( + new PointerEvent("pointermove", { + bubbles: true, + pointerId: 1, + pointerType: "mouse", + isPrimary: true, + buttons: 0, + clientX: point.x, + clientY: point.y, + }), + ), + { x: anchor.x - 100, y: anchor.y - 100 }, + ) + await expect(image).toHaveCSS("cursor", "grab") + expect(await image.boundingBox()).toEqual(touched) + await page.mouse.up() // Keyboard-accessible fit restores the exact original geometry. await fit.focus() await page.keyboard.press("Enter") @@ -1657,6 +1908,139 @@ test("desktop review waits for the session's stored mode before it loads changes expect(working).toEqual([]) }) +// A failed request used to settle like an empty one, so the review claimed the working tree was clean. +test("a failed diff request offers a retry instead of a clean working tree", async ({ page }) => { + await openSession(page, { name: "ReviewDiffFailure", vcsDiff: [fileDiff("src/alpha.ts")] }) + const changes = { failing: true } + await page.route(/\/api\/vcs\/diff\?/, (route) => { + if (!changes.failing || new URL(route.request().url()).searchParams.get("untracked") !== "folders") + return route.fallback() + + return route.fulfill({ status: 500, headers: { "access-control-allow-origin": "*" }, json: {} }) + }) + const panel = page.locator("#review-panel") + const failure = panel.getByRole("alert") + + await page.getByRole("button", { name: "Toggle review", exact: true }).click() + await openReviewLauncher(panel) + await expect(failure.getByText("Couldn't load changes", { exact: true })).toBeVisible() + await expect(panel.locator('[data-slot="session-review-v2-empty-changes"]')).toHaveCount(0) + changes.failing = false + await failure.getByRole("button", { name: "Try again", exact: true }).click() + await expect(panel.locator('[data-slot="session-review-v2-file-name"]')).toHaveText("alpha.ts") + await expect(failure).toHaveCount(0) +}) + +// A large file's full patch that failed to load used to leave its preview blank, with no reason and no way to load it. +test("a large file whose full diff fails to load says so, and loads on Try again", async ({ page }) => { + // The listing leaves the patch out, as the server does for a large file; the bounded request carries it. + await openSession(page, { + name: "ReviewDetailFailure", + vcsDiff: (input) => [fileDiff("big.ts", { loaded: input.context === "3" })], + }) + const full = { failing: true } + await page.route(/\/api\/vcs\/diff\?.*context=3/, (route) => { + if (!full.failing) return route.fallback() + + return route.fulfill({ status: 500, headers: { "access-control-allow-origin": "*" }, json: {} }) + }) + const panel = page.locator("#review-panel") + const preview = panel.locator('[data-slot="session-review-v2-diff-scroll"]') + const failure = preview.getByRole("alert") + + await page.getByRole("button", { name: "Toggle review", exact: true }).click() + await openReviewLauncher(panel) + await expect(panel.locator('[data-slot="session-review-v2-file-name"]')).toHaveText("big.ts") + // The request runs three times, a second and then two apart, before the preview gives up. + await expect(failure.getByText("Couldn't load changes", { exact: true })).toBeVisible() + full.failing = false + await failure.getByRole("button", { name: "Try again", exact: true }).click() + await expect(preview.locator("diffs-container")).toContainText("export const value = 'after'") + await expect(failure).toHaveCount(0) +}) + +// A failed search used to read "No results found", as if the workspace had no such file. +test("a failed file search offers a retry instead of no results", async ({ page }) => { + const directory = "C:/OpenCode/ReviewSearchFailure" + await openSession(page, { + name: "ReviewSearchFailure", + fileList: () => [fileNode(directory, "README.md")], + findFiles: (input) => (input.query === "nested" ? [fileNode(directory, "src/nested.ts")] : []), + seed: { panes: { ses_reviewsearchfailure: { review: true } } }, + }) + const search = { failing: true } + await page.route(/\/api\/fs\/find\?/, (route) => { + if (!search.failing) return route.fallback() + + return route.fulfill({ status: 500, headers: { "access-control-allow-origin": "*" }, json: {} }) + }) + const panel = page.locator("#review-panel") + const filter = panel.getByRole("combobox", { name: "Filter files" }) + const failure = panel.getByRole("alert") + + await openFileLauncher(panel) + await filter.fill("nested") + await expect(failure.getByText("Couldn't search files", { exact: true })).toBeVisible() + await expect(panel.getByText("No results found", { exact: true })).toHaveCount(0) + await page.screenshot({ path: test.info().outputPath("file-search-failed.png"), animations: "disabled" }) + search.failing = false + await failure.getByRole("button", { name: "Try again", exact: true }).click() + await expect(panel.getByRole("option", { name: /nested\.ts/ })).toBeVisible() + await expect(failure).toHaveCount(0) +}) + +// An untracked folder whose listing failed used to look empty, and opening it again never asked the server again. +test("an untracked folder that cannot load says so, and loads once it is opened again", async ({ page }) => { + const workspace = await openSession(page, { + name: "ReviewFolderFailure", + vcsDiff: (input) => + input.directory.endsWith("/untracked") + ? [fileDiff("untracked/notes.ts", { status: "added" })] + : [fileDiff("src/alpha.ts"), fileDiff("untracked/", { status: "added" })], + }) + + const listing = { failing: true, failures: 0 } + + await page.route(/\/api\/vcs\/diff\?/, (route) => { + const directory = new URL(route.request().url()).searchParams.get("location[directory]") + + if (!listing.failing || directory !== `${workspace.directory}/untracked`) return route.fallback() + listing.failures += 1 + + return route.fulfill({ status: 500, headers: { "access-control-allow-origin": "*" }, json: {} }) + }) + const panel = page.locator("#review-panel") + const folder = panel.getByRole("treeitem", { name: "untracked" }) + const notes = panel.getByRole("treeitem", { name: "notes.ts" }) + + await page.getByRole("button", { name: "Toggle review", exact: true }).click() + await openReviewLauncher(panel) + await expect(panel.getByRole("treeitem", { name: "alpha.ts" })).toBeVisible() + // Retries back off over 1, 2 and 4 seconds; the installed clock follows real time until a fast-forward skips it. + await page.clock.install() + await folder.click() + await expect(folder).toHaveAttribute("aria-expanded", "true") + + for (const failures of [1, 2, 3]) { + await expect.poll(() => listing.failures).toBe(failures) + await page.clock.fastForward(1_000 * 2 ** (failures - 1)) + } + + await expect.poll(() => listing.failures).toBe(4) + await expect(folder).toContainText("Couldn't load changes") + await expect(notes).toHaveCount(0) + + listing.failing = false + await folder.click() + await expect(folder).toHaveAttribute("aria-expanded", "false") + await expect(folder).not.toContainText("Couldn't load changes") + await folder.click() + await expect(folder).toHaveAttribute("aria-expanded", "true") + await expect(notes).toBeVisible() + await expect(folder).toContainText("1") + expect(listing.failures).toBe(4) +}) + test("a chosen mode the session stops offering shows as Git, and comes back when it is offered again", async ({ page, }) => { @@ -1746,8 +2130,9 @@ test("Review from a new tab keeps the file browser and preview open", async ({ p await openFileLauncher(panel) await expect(tab("Open file")).toHaveAttribute("aria-selected", "true") + // The empty panel's own New tab stays beside the one the file browser replaced, so the added one is the last. await panel.getByRole("button", { name: "Add tab", exact: true }).click() - await expect(tab("New tab")).toHaveAttribute("aria-selected", "true") + await expect(tab("New tab").last()).toHaveAttribute("aria-selected", "true") await panel.getByRole("button", { name: /^Review/ }).click() await expect(tab("Review")).toHaveAttribute("aria-selected", "true") await expect(tab("Open file")).toHaveAttribute("aria-selected", "false") @@ -1762,7 +2147,7 @@ test("Review from a new tab keeps the file browser and preview open", async ({ p // Choosing Review also leaves a single-click file preview open beside it. await panel.getByRole("button", { name: "Add tab", exact: true }).click() - await expect(tab("New tab")).toHaveAttribute("aria-selected", "true") + await expect(tab("New tab").last()).toHaveAttribute("aria-selected", "true") await panel.getByRole("button", { name: /^Review/ }).click() await expect(panel.locator("#session-side-panel-review-tab")).toHaveAttribute("aria-selected", "true") await expect(tab("README.md")).toHaveCount(1) diff --git a/packages/app/e2e/regression/session-header.spec.ts b/packages/app/e2e/regression/session-header.spec.ts index 09e55d4859c5..a46def6643bb 100644 --- a/packages/app/e2e/regression/session-header.spec.ts +++ b/packages/app/e2e/regression/session-header.spec.ts @@ -290,6 +290,20 @@ test.describe("location", () => { await header.screenshot({ path: test.info().outputPath(`location-${state.width}.png`) }) } + // Find takes room from the title, so the usage details give way, and come back once Find closes. + const search = header.locator('[data-component="timeline-search-bar"] input') + await row.evaluate((element) => (element.style.inlineSize = "680px")) + await expect(usage).toBeVisible() + await page.keyboard.press("ControlOrMeta+f") + await expect(search).toBeFocused() + await expect(usageMenu).toBeVisible() + await header.screenshot({ path: test.info().outputPath("location-find-open.png") }) + await search.press("Escape") + await expect(search).toHaveCount(0) + await expect(project).toBeVisible() + await expect(usage).toBeVisible() + await header.screenshot({ path: test.info().outputPath("location-find-closed.png") }) + await row.evaluate((element) => element.style.removeProperty("inline-size")) await review.click() await expect(review).toHaveAttribute("aria-expanded", "true") @@ -495,6 +509,40 @@ test.describe("location", () => { }) } + test("an app launch that never answers releases the Open in controls", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }) + await page.clock.install() + + const mock = await mockWorkspace(page, { + ...workspace, + seed: { + storage: { ...reviewTabs(worktree, "ses_location"), "opencode.global.dat:plugin.file.app": { app: "vscode" } }, + }, + }) + + // An editor that does not detach keeps its launch running until the user closes it. + await page.goto( + `/e2e/utils/windows-menu.html?${new URLSearchParams({ + server: mock.server, + path: sessionHref("ses_location", "sidecar"), + os: "macos", + openApps: "1", + holdOpen: "1", + })}`, + ) + await expectSessionTitle(page, "Location session") + await page.getByRole("button", { name: "Toggle review", exact: true }).click() + await expect(page.getByRole("complementary", { name: "Review and files", exact: true })).toBeFocused() + const open = page.getByRole("button", { name: "Open in VS Code", exact: true }) + await open.click() + await expect(page.getByLabel("Opened paths")).toContainText("Visual Studio Code") + await expect(open).toBeDisabled() + + await page.clock.fastForward(10_000) + await expect(open).toBeEnabled() + await expect(page.getByText("Request failed", { exact: true })).toHaveCount(0) + }) + test.describe("touch", () => { test.use({ hasTouch: true }) @@ -715,6 +763,46 @@ test.describe("revert", () => { await expect(prompt).toHaveText("Unsent draft") }) + test("a second /undo before the staged event rewinds one prompt further, and /redo retires the toast", async ({ + page, + }) => { + const staged: { sessionID: string; messageID: string }[] = [] + const { session, editor } = await openSession(page, { ...workspace, onRevertStage: (input) => staged.push(input) }) + const prompt = page.getByRole("textbox", { name: "Prompt" }) + const undoToast = page.getByRole("button", { name: "Undo", exact: true }) + + const slash = async (command: string) => { + await editor.press("ControlOrMeta+a") + await editor.press("Backspace") + await editor.pressSequentially(`/${command}`) + await expect( + page.locator('[data-component="composer-suggestions"] [data-suggestion-id][data-active]'), + ).toContainText(`/${command}`) + await editor.press("Enter") + } + + // The mock server never sends session.revert.staged, so each step must build on the last request's result. + await slash("undo") + await expect(prompt).toHaveText("Second prompt") + await expect(undoToast).toBeVisible() + await slash("undo") + await expect(prompt).toHaveText("First prompt") + expect(staged).toEqual([ + { sessionID: session.id, messageID: "msg_second" }, + { sessionID: session.id, messageID: "msg_first" }, + ]) + + const cleared = page.waitForResponse( + (response) => + response.request().method() === "DELETE" && + new URL(response.url()).pathname === `/api/session/${session.id}/revert`, + ) + + await slash("redo") + expect((await cleared).ok()).toBe(true) + await expect(undoToast).toHaveCount(0) + }) + test("Undo after switching tabs restages the earlier revert in the Session it came from", async ({ page }) => { const staged: { sessionID: string; messageID: string }[] = [] const cleared: string[] = [] diff --git a/packages/app/e2e/regression/session-location-sync.spec.ts b/packages/app/e2e/regression/session-location-sync.spec.ts index d189c92dca9b..daf37da3403b 100644 --- a/packages/app/e2e/regression/session-location-sync.spec.ts +++ b/packages/app/e2e/regression/session-location-sync.spec.ts @@ -115,9 +115,26 @@ test("replaces the composer when the location is not found and recovers by movin // A typed not-found answer is final; retrying cannot succeed until the folder changes. expect(requests).toBe(1) - await transport.waitForConnection() + const connection = await transport.waitForConnection() await page.getByRole("button", { name: "Choose worktree", exact: true }).click() - await page.getByRole("menuitem", { name: "existing-worktree", exact: true }).click() + const worktree = page.getByRole("menuitem", { name: "existing-worktree", exact: true }) + await expect(worktree).toBeVisible() + + // Reconnecting checks the folder again without remounting the missing view, so the open menu survives. + const rechecked = page.waitForResponse( + (response) => + new URL(response.url()).searchParams.get("location[directory]") === directory && response.status() === 404, + ) + + await transport.close() + await transport.waitForConnection({ after: connection.id }) + await rechecked + expect(requests).toBe(2) + await expect(worktree).toBeVisible() + // The open menu hides the page from role locators. + await expect(page.getByText("Session location unavailable", { exact: true })).toBeVisible() + + await worktree.click() await expect.poll(() => moves).toEqual([{ directory: destination }]) session.directory = destination diff --git a/packages/app/e2e/regression/session-queue.spec.ts b/packages/app/e2e/regression/session-queue.spec.ts index 9fede2d25617..f9cc211908d3 100644 --- a/packages/app/e2e/regression/session-queue.spec.ts +++ b/packages/app/e2e/regression/session-queue.spec.ts @@ -3,9 +3,11 @@ import type { OpenCodeEvent, SessionInboxInfo, SessionMessageInfo, ShellInfo } f import { PromptInput } from "@opencode/schema/prompt-input" import { SessionInbox } from "@opencode/schema/session-inbox" import { SessionMessage } from "@opencode/schema/session-message" +import { timelinePresets } from "@opencode/session-ui/timeline/detail" import { Schema } from "effect" -import { holdRoute, provider } from "../utils/app" +import { holdRoute, provider, seed, SERVER } from "../utils/app" import type { MockServerConfig } from "../utils/mock-server" +import { installSseTransport } from "../utils/sse-transport" import { openSession } from "../utils/workspace" const sessionID = "ses_session_queue_regression" @@ -168,6 +170,7 @@ async function openQueue( revert?: string, status: "idle" | "running" = "running", model = { id: "queue-model", name: "Queue Model" }, + config: Pick = {}, ) { const options: Parameters[1] = { name: "SessionQueueRegression", @@ -189,6 +192,7 @@ async function openQueue( onBackground: mock.onBackground, shellCommands: () => mock.shells, events: mock.events, + ...config, } if (followUpBehavior) options.seed = { settings: { general: { followUpBehavior } } } @@ -337,6 +341,98 @@ test("a steer shows as pending in the timeline as the composer clears, before th await expect(prompt.locator('[data-component="user-message"]')).toHaveAttribute("data-pending", "true") }) +test("a prompt sent while the session's agents and models load shows as pending at once and sends once they load", async ({ + page, +}) => { + const mock = createQueueMock( + [], + [{ id: "msg_queue_delivered", type: "user", text: "First prompt", time: { created: 1 } }], + ) + + // The Location's agents load only once released, so the composer has no agent or model to send with yet. + const agents = Promise.withResolvers() + + const view = await openQueue(page, mock, "steer", undefined, "idle", undefined, { + beforeAgentsResponse: () => agents.promise, + }) + + const prompt = page.locator('[data-timeline-virtual-content] [data-timeline-row="UserMessage"]', { + hasText: "read the deploy logs", + }) + + await expect(userRow(page, "msg_queue_delivered")).toContainText("First prompt") + await view.input.fill("read the deploy logs") + await view.input.press("Enter") + await expect(prompt.locator('[data-component="user-message"]')).toHaveAttribute("data-pending", "true") + await expect(view.input).toHaveText("") + expect(mock.prompts).toEqual([]) + + agents.resolve() + await expect.poll(() => mock.prompts.map((item) => item.text)).toEqual(["read the deploy logs"]) + await expect(prompt).toHaveCount(1) +}) + +for (const row of [ + { case: "a missed admission echo", reconnect: false }, + { case: "an event stream reconnect", reconnect: true }, +]) { + test(`a steer stops projecting its selection after ${row.case}`, async ({ page }) => { + const transport = await installSseTransport(page, { server: SERVER }) + + const mock = createQueueMock( + [], + [{ id: "msg_queue_delivered", type: "user", text: "First prompt", time: { created: 1 } }], + ) + + const admit = mock.onPrompt + + // The server admits the steer, but its session.inbox.enqueued echo never reaches the client. + mock.onPrompt = (input) => { + admit(input) + mock.events() + } + + await seed(page, { settings: { general: { timelineDetail: timelinePresets[0].value } } }) + const view = await openQueue(page, mock, "steer") + const connection = await transport.waitForConnection() + const commit = await holdRoute(page, new RegExp(`/api/session/${sessionID}/prompt(\\?|$)`), { method: "POST" }) + + const prompt = page.locator('[data-timeline-virtual-content] [data-timeline-row="UserMessage"]', { + hasText: "use the staging database", + }) + + await expect(userRow(page, "msg_queue_delivered")).toContainText("First prompt") + await view.input.fill("use the staging database") + await view.input.press("Enter") + await commit.arrived + await expect(prompt).toBeVisible() + + if (row.reconnect) await transport.disconnect() + commit.release() + await expect.poll(() => mock.prompts.map((item) => item.text)).toEqual(["use the staging database"]) + + if (row.reconnect) await transport.waitForConnection({ after: connection.id }) + // Another client switches the agent. Only its own notice shows: the admitted steer no longer projects one. + mock.messages.push({ + id: "msg_queue_agent_plan", + type: "agent-switched", + agent: "plan", + previous: "build", + time: { created: Date.now() }, + }) + await transport.send({ + id: "evt_queue_agent_plan", + type: "session.agent.selected", + created: Date.now(), + durable: { aggregateID: sessionID, seq: 100, version: 1 }, + data: { sessionID, agent: "plan" }, + }) + const notices = page.locator('[data-slot="session-timeline-notice"]') + await expect(notices).toHaveText([/^Agent changed\s*Build → Plan$/]) + await expect(prompt).toHaveCount(1) + }) +} + test("a steer into an idle session leaves the finished turn finished until delivery", async ({ page }) => { const mock = createQueueMock( [], diff --git a/packages/app/e2e/regression/session-request-docks.spec.ts b/packages/app/e2e/regression/session-request-docks.spec.ts index 618aad4f08ff..ae1d0277e4dd 100644 --- a/packages/app/e2e/regression/session-request-docks.spec.ts +++ b/packages/app/e2e/regression/session-request-docks.spec.ts @@ -171,6 +171,80 @@ test("replies with predefined choices and the edited custom multiselect answer", expect(cancellations).toEqual([]) }) +test("keeps a choice when a custom answer with its value is turned off, and replies once", async ({ page }) => { + const form = { + id: "frm_question_once", + sessionID, + title: "Questions", + metadata: { kind: "question" }, + fields: [ + { + key: "q0", + type: "multiselect", + title: "Include", + description: "Which supporting surfaces should remain visible?", + options: [ + { value: "files", label: "Changed files" }, + { value: "terminal", label: "Terminal" }, + ], + custom: true, + }, + ], + } + + const replies: unknown[] = [] + const transport = await installSseTransport(page, { server: SERVER, retry: 20 }) + await mockServer(page, { forms: () => (replies.length > 0 ? [] : [form]) }) + page.on("request", (request) => { + if ( + request.method() === "POST" && + new URL(request.url()).pathname === `/api/session/${sessionID}/form/frm_question_once/reply` + ) + replies.push(request.postDataJSON()) + }) + await page.goto(sessionHref(sessionID)) + await transport.waitForConnection() + await expectSessionTitle(page, title) + + const question = page.locator('[data-component="dock-prompt"][data-kind="question"]') + const files = question.getByRole("checkbox", { name: "Changed files", exact: true }) + const custom = question.getByRole("checkbox", { name: "Type your own answer…", exact: true }) + const input = question.getByRole("textbox", { name: "Type your own answer…", exact: true }) + const submit = question.getByRole("button", { name: "Submit", exact: true }) + const dismiss = question.getByRole("button", { name: "Dismiss", exact: true }) + + await files.click() + await input.fill("files") + await expect(custom).toBeChecked() + await custom.click() + await expect(custom).not.toBeChecked() + await expect(files).toBeChecked() + + const reply = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/session/${sessionID}/form/frm_question_once/reply`, + ) + + await submit.click() + expect((await reply).request().postDataJSON()).toEqual({ answer: { q0: ["files"] } }) + + // The server has the answer but has not announced the form settled yet, so nothing can send it again. + await expect(submit).toBeDisabled() + await expect(dismiss).toBeDisabled() + await expect(files).toHaveAttribute("aria-disabled", "true") + + await transport.send({ + id: "evt_form_replied_once", + created: 1700000003000, + type: "form.replied", + location: { directory }, + data: { sessionID, id: "frm_question_once", answer: { q0: ["files"] } }, + }) + await expect(question).toHaveCount(0) + expect(replies).toEqual([{ answer: { q0: ["files"] } }]) +}) + test("shows a pending permission dock", async ({ page }) => { const replies: { sessionID: string; permissionID: string; body: unknown }[] = [] await mockServer(page, { @@ -210,6 +284,178 @@ test("shows a pending permission dock", async ({ page }) => { await expect(page.locator('[data-component="composer"]')).toBeVisible() }) +test("sends one permission reply and closes the dock when it lands, before permission.replied", async ({ page }) => { + await mockServer(page, { + sessionPermissions: { + [sessionID]: [ + { + id: "permission-request", + sessionID, + permission: "shell", + patterns: ["git status"], + metadata: {}, + always: [], + }, + ], + }, + }) + const replies: unknown[] = [] + const released = Promise.withResolvers() + // Answers without the `permission.replied` event the server also publishes, so only the reply can close the dock. + await page.route(/\/api\/session\/ses_request_docks\/permission\/permission-request\/reply/, async (route) => { + if (route.request().method() !== "POST") return route.fallback() + replies.push(route.request().postDataJSON()) + await released.promise + await route.fulfill({ status: 204 }) + }) + + await page.goto(sessionHref(sessionID)) + await expectSessionTitle(page, title) + + const permission = page.locator('[data-component="dock-prompt"][data-kind="permission"]') + const actions = permission.locator('[data-slot="permission-footer-actions"]') + await permission.getByRole("button", { name: "Allow once" }).dblclick() + await expect.poll(() => replies.length).toBe(1) + + for (const name of ["Deny", "Allow always", "Allow once"]) + await expect(actions.getByRole("button", { name, exact: true })).toBeDisabled() + + released.resolve() + await expect(permission).toHaveCount(0) + await expect(page.locator('[data-component="composer"]')).toBeVisible() + await expect(page.getByText("Request failed", { exact: true })).toHaveCount(0) + expect(replies).toEqual([{ decision: "once" }]) +}) + +test("shows an auto-accepted permission in the dock once its replies stop answering", async ({ page }) => { + const permissionID = "permission-hung" + const attempts = { count: 0 } + await page.clock.install() + await mockWorkspace(page, { + name: "RequestDocks", + directory, + sessions: [{ id: sessionID, title }], + sessionPermissions: { + [sessionID]: [ + { id: permissionID, sessionID, action: "shell", resources: ["git status"], metadata: {}, save: [] }, + ], + }, + seed: { settings: { permissions: { autoApprove: true } } }, + }) + // Every reply reaches the server and never answers. + await page.route(new RegExp(`/api/session/${sessionID}/permission/${permissionID}/reply(\\?|$)`), (route) => { + if (route.request().method() !== "POST") return route.fallback() + attempts.count++ + }) + + await page.goto(sessionHref(sessionID)) + await expectSessionTitle(page, title) + const permission = page.locator('[data-component="dock-prompt"][data-kind="permission"]') + + // Each reply times out, then the next one starts after its retry delay. + await expect.poll(() => attempts.count).toBe(1) + await page.clock.fastForward(15_000) + await page.clock.fastForward(1_000) + await expect.poll(() => attempts.count).toBe(2) + await page.clock.fastForward(15_000) + await page.clock.fastForward(2_000) + await expect.poll(() => attempts.count).toBe(3) + await expect(permission).toHaveCount(0) + + await page.clock.fastForward(15_000) + await expect(permission.getByText("git status")).toBeVisible() + expect(attempts.count).toBe(3) +}) + +test("keeps a typed MCP elicitation answer across a session switch and submits it once", async ({ page }) => { + const other = { id: "ses_request_docks_other", title: "Other request session" } + + const form = { + id: "frm_mcp_draft", + sessionID, + title: "Deploy", + metadata: { kind: "mcp-elicitation", server: "release" }, + fields: [{ key: "env", type: "string", title: "Environment" }], + } + + const replies: unknown[] = [] + await mockWorkspace(page, { + name: "RequestDocks", + directory, + sessions: [{ id: sessionID, title }, other], + forms: () => (replies.length > 0 ? [] : [form]), + onFormReply: (reply) => replies.push(reply.body), + seed: { tabs: [sessionID, other.id] }, + }) + + await page.goto(sessionHref(sessionID)) + await expectSessionTitle(page, title) + const dock = page.locator('[data-component="session-elicitation-dock"]') + const input = dock.getByRole("textbox", { name: "Environment", exact: true }) + await input.fill("staging") + + await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(other.id)}"])`).click() + await expectSessionTitle(page, other.title) + await expect(dock).toHaveCount(0) + await page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(sessionID)}"])`).click() + await expectSessionTitle(page, title) + await expect(input).toHaveValue("staging") + + await dock.getByRole("button", { name: "Submit", exact: true }).dblclick() + await expect(dock).toHaveCount(0) + await expect(page.locator('[data-component="composer"]')).toBeVisible() + expect(replies).toEqual([{ answer: { env: "staging" } }]) +}) + +test("gives a Location elicitation's hung reply back after 30 s and closes it on form.replied", async ({ page }) => { + const form = { + id: "frm_mcp_global", + sessionID: "global", + title: "Deploy", + metadata: { kind: "mcp-elicitation", server: "release" }, + fields: [{ key: "env", type: "string", title: "Environment" }], + } + + const replies: { body: unknown; directory: string | undefined }[] = [] + const transport = await installSseTransport(page, { server: SERVER, retry: 20 }) + await page.clock.install() + await mockServer(page, { forms: [form] }) + // The server takes the reply and never answers it. + await page.route(/\/api\/session\/global\/form\/frm_mcp_global\/reply(\?|$)/, (route) => { + if (route.request().method() !== "POST") return route.fallback() + replies.push({ body: route.request().postDataJSON(), directory: route.request().headers()["x-opencode-directory"] }) + }) + + await page.goto(sessionHref(sessionID)) + await transport.waitForConnection() + await expectSessionTitle(page, title) + const dock = page.locator('[data-component="session-elicitation-dock"]') + const input = dock.getByRole("textbox", { name: "Environment", exact: true }) + const submit = dock.getByRole("button", { name: "Submit", exact: true }) + await input.fill("prod") + + await submit.dblclick() + await expect.poll(() => replies.length).toBe(1) + await expect(submit).toBeDisabled() + expect(replies).toEqual([{ body: { answer: { env: "prod" } }, directory: encodeURIComponent(directory) }]) + + await page.clock.fastForward(30_000) + await expect(submit).toBeEnabled() + await expect(input).toHaveValue("prod") + await expect(page.getByText("Request failed", { exact: true })).toBeVisible() + + await transport.send({ + id: "evt_form_replied_global", + created: 1700000004000, + type: "form.replied", + location: { directory }, + data: { sessionID: "global", id: "frm_mcp_global", answer: { env: "prod" } }, + }) + await expect(dock).toHaveCount(0) + await expect(page.locator('[data-component="composer"]')).toBeVisible() + expect(replies).toHaveLength(1) +}) + test("names the MCP tool, the hook's message and the full input in the permission dock", async ({ page }) => { const body = "x".repeat(3000) await mockServer(page, { diff --git a/packages/app/e2e/regression/session-summary.spec.ts b/packages/app/e2e/regression/session-summary.spec.ts index 39e08332fc7a..a9752cc91ffc 100644 --- a/packages/app/e2e/regression/session-summary.spec.ts +++ b/packages/app/e2e/regression/session-summary.spec.ts @@ -150,6 +150,31 @@ test("the project menu loads changes on demand and opens review", async ({ page await expect(page.locator("#review-panel")).toBeVisible() }) +// A failed load used to read "No changes", a clean working tree the server never reported. +test("the project menu shows a failed changes load and loads again in place", async ({ page }) => { + await openSession(page, { + name: "ProjectChangesFailure", + vcsDiff: [fileDiff("README.md", { additions: 7, deletions: 3 })], + }) + const changes = { failing: true } + await page.route(/\/api\/vcs\/diff\?/, (route) => { + if (!changes.failing) return route.fallback() + + return route.fulfill({ status: 500, headers: cors, json: {} }) + }) + await page.locator('[data-slot="session-location-trigger"]').click() + const menu = page.locator('[data-slot="session-location-card"]') + const failed = menu.getByRole("menuitem", { name: /^Couldn't load changes.*Retry$/ }) + await expect(failed).toBeVisible() + await expect(menu.getByRole("menuitem", { name: "No changes", exact: true })).toHaveCount(0) + await page.screenshot({ path: test.info().outputPath("project-menu-changes-failed.png"), animations: "disabled" }) + + changes.failing = false + await failed.click() + await expect(menu).toBeVisible() + await expect(menu.getByRole("menuitem", { name: /1 Changed file/ })).toContainText("+7") +}) + test("a session in a worktree subfolder names its worktree and lists cached worktrees at once", async ({ page }) => { const root = "C:/OpenCode/SmokeWorktrees" await mockStressTimeline(page, { @@ -261,6 +286,115 @@ test("the details follow the routed session when it moves to another worktree", await expect(location("feature")).toHaveCount(0) }) +test("a new worktree that does not receive the session offers Retry and Delete worktree after the menu closes", async ({ + page, +}) => { + const created = "C:/OpenCode/worktrees/quiet-river" + const creates: unknown[] = [] + const removes: unknown[] = [] + const moves: unknown[] = [] + const answers = ["fail", "ok", "fail"] + + const view = await openSession(page, { + name: "WorktreeRecovery", + onWorktreeCreate: (input) => { + creates.push(input) + + return { status: 200, body: { directory: created } } + }, + onWorktreeRemove: (input) => void removes.push(input), + }) + + await page.route(`**/api/session/${view.session.id}/move`, (route) => { + if (route.request().method() !== "POST") return route.fallback() + moves.push(route.request().postDataJSON()) + + if (answers.shift() === "fail") + return route.fulfill({ status: 400, headers: cors, json: { message: "Session is locked" } }) + + return route.fulfill({ status: 204, headers: cors }) + }) + const dialog = page.getByRole("dialog", { name: "Session not moved", exact: true }) + const retry = dialog.getByRole("button", { name: "Retry", exact: true }) + + // The location menu closes as the item is picked; the move and its recovery outlive it. + await moveToNewWorktree(page) + await expect(dialog).toContainText("The new worktree quiet-river is ready") + await expect(page.locator('[data-slot="session-location-card"]')).toBeHidden() + await expect(retry).toBeFocused() + expect(moves).toEqual([{ directory: created }]) + await page.screenshot({ path: test.info().outputPath("worktree-recovery.png"), animations: "disabled" }) + + // Retry moves into the worktree already created, without creating another. + await retry.click() + await expect(dialog).toBeHidden() + expect(moves).toEqual([{ directory: created }, { directory: created }]) + expect(creates).toHaveLength(1) + + await moveToNewWorktree(page) + await expect(dialog).toBeVisible() + await dialog.getByRole("button", { name: "Delete worktree", exact: true }).click() + await expect(dialog).toBeHidden() + expect(creates).toHaveLength(2) + expect(removes).toEqual([expect.objectContaining({ directory: created, force: true })]) +}) + +test("a session that starts running while its new worktree is created stays put until Retry", async ({ page }) => { + const created = "C:/OpenCode/worktrees/calm-lake" + const moves: unknown[] = [] + + const view = await openSession(page, { + name: "WorktreeRunning", + onWorktreeCreate: () => ({ status: 200, body: { directory: created } }), + }) + + await page.route(`**/api/session/${view.session.id}/move`, (route) => { + if (route.request().method() !== "POST") return route.fallback() + moves.push(route.request().postDataJSON()) + + return route.fulfill({ status: 204, headers: cors }) + }) + const create = await holdRoute(page, /\/api\/worktree(?:\?|$)/, { method: "POST" }) + const dialog = page.getByRole("dialog", { name: "Session not moved", exact: true }) + const retry = dialog.getByRole("button", { name: "Retry", exact: true }) + const composer = page.locator('[data-component="session-composer-dock"]') + + await moveToNewWorktree(page) + await create.arrived + await view.push([ + { + id: "evt_worktree_running", + created: 1700000002000, + type: "session.execution.started", + durable: { aggregateID: view.session.id, seq: 1, version: 1 }, + data: { sessionID: view.session.id }, + }, + ]) + await expect(composer.getByRole("button", { name: "Stop", exact: true })).toBeEnabled() + create.release() + + // The run keeps its checkout: nothing moves, and Retry waits for the run to end. + await expect(dialog).toContainText("The session is running. Try again once it finishes.") + await expect(retry).toBeDisabled() + await expect(dialog.getByRole("button", { name: "Keep worktree", exact: true })).toBeFocused() + expect(moves).toEqual([]) + await page.screenshot({ path: test.info().outputPath("worktree-running.png"), animations: "disabled" }) + + await view.push([ + { + id: "evt_worktree_idle", + created: 1700000003000, + type: "session.execution.succeeded", + durable: { aggregateID: view.session.id, seq: 2, version: 1 }, + data: { sessionID: view.session.id }, + }, + ]) + await expect(retry).toBeEnabled() + await retry.click() + await expect(dialog).toBeHidden() + expect(moves).toEqual([{ directory: created }]) +}) + for (const direction of ["ltr", "rtl"] as const) { test(`summary overlays the view and submenus follow ${direction}`, async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }) @@ -447,6 +581,26 @@ test("summary catalogs load, refresh while cached, and tell errors from empty", await expectRefreshKeeps(page, service.name, service.path, service.item) } + // A refresh that fails keeps the list it had, with its footer and its row's count. + state.fail = true + + const failed = page.waitForResponse( + (response) => new URL(response.url()).pathname === "/api/plugin" && response.status() === 500, + ) + + await page.keyboard.press("Escape") + await expect(menu("Skills")).toBeHidden() + await open("Plugins") + await failed + await expect(menu("Plugins")).toHaveAttribute("aria-busy", "false") + await expect(menu("Plugins").getByText("supermemory", { exact: true })).toBeVisible() + await expect(menu("Plugins").getByText("Configuration file")).toBeVisible() + await expect(menu("Plugins").getByRole("alert")).toHaveCount(0) + await expect( + summary.getByRole("button", { name: "Plugins", exact: true }).locator(".session-service-count"), + ).toHaveText("2") + state.fail = false + state.extra = true await expectRefreshKeeps(page, "Plugins", "/api/plugin", "supermemory") await expect(menu("Plugins").getByText("daytona", { exact: true })).toBeVisible() @@ -563,6 +717,8 @@ test("MCP rows toggle once per action and keep sign-in, errors, and management a if (pending) { await pending.arrived await expect(connected).toBeDisabled() + // Each row toggles its own server: the others stay free meanwhile. + await expect(disabled).toBeEnabled() pending.release() } @@ -865,6 +1021,21 @@ test("long MCP lists stay in the viewport in a real RTL locale", async ({ page } await expect(menu).toBeHidden() }) +// Picks New worktree from the location menu of a session in its project's root checkout. +async function moveToNewWorktree(page: Page) { + const location = page.locator('[data-slot="session-location-card"]').getByRole("menuitem", { + name: "Local repository", + exact: true, + }) + + await page.locator('[data-slot="session-location-trigger"]').click() + await location.click() + await page + .getByRole("menu", { name: "Local repository", exact: true }) + .getByRole("menuitem", { name: "New worktree", exact: true }) + .click() +} + // Moves the pointer straight across from a submenu's trigger into the open submenu, so it never crosses sibling items. async function enter(page: Page, trigger: Locator, menu: Locator) { await expect(menu).toBeVisible() diff --git a/packages/app/e2e/regression/session-websearch-dock.spec.ts b/packages/app/e2e/regression/session-websearch-dock.spec.ts new file mode 100644 index 000000000000..30719b45bff4 --- /dev/null +++ b/packages/app/e2e/regression/session-websearch-dock.spec.ts @@ -0,0 +1,122 @@ +import { expect, test, type Page } from "@playwright/test" +import { sessionHref } from "../utils/app" +import { expectSessionTitle } from "../utils/waits" +import { mockWorkspace, type WorkspaceInput } from "../utils/workspace" + +const directory = "C:/OpenCode/WebSearchDock" + +const sessionID = "ses_websearch_dock" + +const title = "Web search dock regression" + +const providers = [ + { id: "exa", name: "Exa" }, + { id: "parallel", name: "Parallel" }, +] + +const consent = { + id: "frm_websearch_consent", + sessionID, + title: "Web Search", + metadata: { kind: "websearch.provider" }, + fields: [ + { + key: "choice", + type: "string", + required: true, + custom: false, + options: [ + { value: "allow", label: "Allow search via Exa, Parallel" }, + { value: "choose", label: "Choose another provider" }, + { value: "disable", label: "Disable web search" }, + ], + }, + ], +} + +const provider = { + id: "frm_websearch_provider", + sessionID, + title: "Choose a web search provider", + metadata: { kind: "websearch.provider" }, + fields: [ + { + key: "provider", + type: "string", + required: true, + custom: false, + options: providers.map((item) => ({ value: item.id, label: item.name })), + }, + ], +} + +type Reply = { sessionID: string; formID: string; body: unknown } + +// The forms the mock server lists now. +type Listed = { forms: unknown[] } + +test("sends one consent reply for a double-click and keeps the answered form closed", async ({ page }) => { + const replies: Reply[] = [] + // The mock keeps listing the consent form after the reply, so the form sync that follows it lists the answered form. + await mockServer(page, { forms: [consent], onFormReply: (reply) => replies.push(reply) }) + await page.goto(sessionHref(sessionID)) + await expectSessionTitle(page, title) + + const dock = page.locator('[data-component="session-websearch-dock"]') + const enable = dock.getByRole("button", { name: "Enable", exact: true }) + await expect(enable).toBeEnabled() + await expect(page.locator('[data-component="composer"]')).toHaveCount(0) + + const resynced = page.waitForResponse( + (response) => + replies.length > 0 && + response.request().method() === "GET" && + new URL(response.url()).pathname === `/api/session/${sessionID}/form`, + ) + + await enable.dblclick() + await resynced + + await expect(dock).toHaveCount(0) + await expect(page.locator('[data-component="composer"]')).toBeVisible() + expect(replies).toEqual([{ sessionID, formID: consent.id, body: { answer: { choice: "allow" } } }]) +}) + +test("answers the provider form a form sync delivers when its form.created event is missed", async ({ page }) => { + const replies: Reply[] = [] + const state: Listed = { forms: [consent] } + await mockServer(page, { + forms: () => state.forms, + // No form.created event is pushed: the provider form reaches the app only through the form sync after the reply. + onFormReply: (reply) => { + replies.push(reply) + state.forms = reply.formID === consent.id ? [provider] : [] + }, + }) + await page.goto(sessionHref(sessionID)) + await expectSessionTitle(page, title) + + const dock = page.locator('[data-component="session-websearch-dock"]') + await expect(dock.getByRole("button", { name: "Enable", exact: true })).toBeEnabled() + await dock.locator('[data-component="select-v2"]').click() + await page.getByRole("listbox").getByRole("option", { name: "Parallel", exact: true }).click() + await expect(dock.locator('[data-component="select-v2"]')).toHaveText("Parallel") + await dock.getByRole("button", { name: "Enable", exact: true }).click() + + await expect(dock).toHaveCount(0) + await expect(page.locator('[data-component="composer"]')).toBeVisible() + expect(replies).toEqual([ + { sessionID, formID: consent.id, body: { answer: { choice: "choose" } } }, + { sessionID, formID: provider.id, body: { answer: { provider: "parallel" } } }, + ]) +}) + +function mockServer(page: Page, requests: Pick) { + return mockWorkspace(page, { + name: "WebSearchDock", + directory, + sessions: [{ id: sessionID, title }], + websearchProviders: providers, + ...requests, + }) +} diff --git a/packages/app/e2e/regression/settings-search.spec.ts b/packages/app/e2e/regression/settings-search.spec.ts index 0f882095ef45..333abd9affb7 100644 --- a/packages/app/e2e/regression/settings-search.spec.ts +++ b/packages/app/e2e/regression/settings-search.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "@playwright/test" import en from "../../src/runtime/i18n/en" import { clientSettings } from "../../src/settings/search-catalog" -import { NO_PROVIDER, REMOTE_SERVER, project, type SeedInput } from "../utils/app" +import { NO_PROVIDER, REMOTE_SERVER, holdRoute, project, type SeedInput } from "../utils/app" import { mockOpenCodeServer } from "../utils/mock-server" import { openSettings } from "../utils/workspace" @@ -393,6 +393,83 @@ test("project results keep the query, selection, and scroll position on return", await expect.poll(() => view.viewport.evaluate((list) => list.scrollTop)).toBe(scroll) }) +test("a page reached through an opened result keeps its own way back", async ({ page }) => { + const view = await open(page) + await view.search.fill("Projects") + await view.results.getByRole("option", { name: "Projects, This computer", exact: true }).click() + await expect(view.settings.getByRole("heading", { name: "Projects", exact: true })).toBeVisible() + await view.settings.getByRole("button", { name: "OpenCode", exact: true }).click() + await expect(view.settings.getByRole("heading", { name: "OpenCode", exact: true })).toBeVisible() + await expect(view.settings.getByRole("button", { name: "Back to projects", exact: true })).toBeVisible() + // Escape leaves the project for its own parent, not for the page the search started on. + await page.keyboard.press("Escape") + await expect(view.settings.getByRole("heading", { name: "Projects", exact: true })).toBeVisible() + await expect(view.search).toHaveValue("Projects") + + // A Command Palette jump reveals its setting without a way back to a search. + const key = await page.evaluate(() => + /Mac|iPhone|iPad|iPod/.test(navigator.platform) ? "Meta+Shift+P" : "Control+Shift+P", + ) + + await page.keyboard.press(key) + const palette = page.getByRole("dialog") + await palette.getByRole("combobox").fill("OpenCode name") + await palette.getByRole("option", { name: /^Project name/ }).click() + await expect(view.settings.getByRole("textbox", { name: "Project name", exact: true })).toHaveValue("OpenCode") + await expect(view.settings.locator('[data-search-target="row"]')).toContainText("Project name") + await expect(view.settings.getByRole("button", { name: "Back to projects", exact: true })).toBeVisible() +}) + +test("project edits queued behind a save reach their project in order across jumps away and back", async ({ page }) => { + const view = await open(page, { count: 2 }) + await view.search.fill("OpenCode 00 name") + await view.results.getByRole("option").click() + const name = view.settings.getByRole("textbox", { name: "Project name", exact: true }) + await expect(name).toHaveValue("OpenCode 00") + const hold = await holdRoute(page, /\/api\/project\/proj_search_\d+(\?|$)/, { method: "PATCH" }) + + await name.fill("Renamed") + await name.blur() + await hold.arrived + const startup = view.settings.getByRole("textbox", { name: "Worktree startup script", exact: true }) + await startup.fill("bun dev") + await startup.blur() + + const key = await page.evaluate(() => + /Mac|iPhone|iPad|iPod/.test(navigator.platform) ? "Meta+Shift+P" : "Control+Shift+P", + ) + + const jump = async (query: string, value: string) => { + await page.keyboard.press(key) + const palette = page.getByRole("dialog") + await palette.getByRole("combobox").fill(query) + await palette.getByRole("option", { name: /^Project name/ }).click() + await expect(name).toHaveValue(value) + } + + const sent = (projectID: string) => + hold.requests + .filter((request) => new URL(request.url()).pathname === `/api/project/${projectID}`) + .map((request) => request.postDataJSON()) + + await jump("OpenCode 01 name", "OpenCode 01") + + // Another project's save does not wait behind the first project's held one. + await name.fill("Bravo") + await name.blur() + await expect.poll(() => sent("proj_search_1")).toEqual([{ name: "Bravo" }]) + + // Back on the first project before its queued edit went out, a new save must not overtake it. + await jump("OpenCode 00 name", "OpenCode 00") + await startup.fill("bun start") + await startup.blur() + hold.release() + + await expect + .poll(() => sent("proj_search_0")) + .toEqual([{ name: "Renamed" }, { commands: { start: "bun dev" } }, { commands: { start: "bun start" } }]) +}) + test("IME confirmation does not activate a search result", async ({ page }) => { const view = await open(page) await view.search.fill("font") diff --git a/packages/app/e2e/regression/settings-wsl.spec.ts b/packages/app/e2e/regression/settings-wsl.spec.ts index 849ca540ba74..5f87de494d56 100644 --- a/packages/app/e2e/regression/settings-wsl.spec.ts +++ b/packages/app/e2e/regression/settings-wsl.spec.ts @@ -1,6 +1,6 @@ import { base64Encode } from "@opencode/util/encode" import { expect, test } from "@playwright/test" -import { NO_PROVIDER, REMOTE_SERVER, SERVER, project, provider, session } from "../utils/app" +import { NO_PROVIDER, REMOTE_SERVER, SERVER, holdRoute, project, provider, session } from "../utils/app" import { mockOpenCodeServer, mockServers } from "../utils/mock-server" import { expectSessionTitle } from "../utils/waits" @@ -250,3 +250,43 @@ test("an open session moves to the controller a new SSH sign-in creates", async await editor.press("Enter") await expect.poll(() => prompts).toEqual(["after sign-in"]) }) + +test("a session being created on an SSH host that turns out incompatible says so", async ({ page }) => { + const directory = "/home/box/project" + const box = session({ id: "ses_ssh_incompatible", directory, title: "SSH incompatible session" }) + + const config = { + directory, + project: project({ id: "proj_ssh_incompatible", directory }), + provider: provider(), + sessions: [box], + pageMessages: () => ({ items: [] }), + } + + await mockServers(page, { [SERVER]: { ...config, sessions: [] }, [REMOTE_SERVER]: config }) + const path = `/server/${base64Encode("ssh:box")}/session/${box.id}` + await page.goto( + `/e2e/utils/settings-wsl.html?${new URLSearchParams({ server: SERVER, mode: "ready", ssh: REMOTE_SERVER, path })}`, + ) + await expectSessionTitle(page, box.title) + await page.getByRole("button", { name: "New session", exact: true }).click() + + // The create request stays in flight, so the new session stays in preparation. + await holdRoute(page, new RegExp(`^${REMOTE_SERVER.replace(/[.]/g, "\\.")}/api/session(\\?|$)`), { method: "POST" }) + const editor = page.locator('[data-component="composer-editor"]') + const send = page.getByRole("button", { name: "Send", exact: true }) + await expect(page.locator('[data-component="new-session"]')).toBeVisible() + await expect(editor).toBeEditable() + await editor.fill("start on the box") + await expect(editor).toHaveText("start on the box") + await expect(send).toBeEnabled() + await send.click() + const preparing = page.locator('[data-component="session-preparing"]') + await expect(preparing).toBeVisible() + + // The SSH plugin covers a host that is not ready; the route stays mounted beneath its cover. + await page.getByRole("button", { name: "Report incompatible SSH server" }).click() + await expect(page.getByRole("heading", { name: "SSH connection inactive", exact: true })).toBeVisible() + await expect(page.getByText("This server version isn't supported", { exact: true })).toBeAttached() + await expect(preparing).toHaveCount(0) +}) diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index babf27ad342a..c4260f2ce98c 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -96,6 +96,43 @@ test("a settings page survives refresh", async ({ page }) => { await expect(page).toHaveURL("/settings?tab=appearance") }) +// The Arabic dictionary chunks: built (`_assets/ar-.js`) and dev (`.../i18n/ar.ts`), for the app and the UI. +const arabic = /\/(?:_assets\/ar-[\w-]+\.js|i18n\/ar\.ts)(?:\?|$)/ + +async function pickArabic(page: Page) { + const { settings } = await open(page) + await settings.locator('[data-action="settings-language"]').click() + await page.getByRole("listbox").getByRole("option", { name: "العربية", exact: true }).click() + + return settings +} + +test("a language switch keeps settings on screen and flips direction only with the new strings", async ({ page }) => { + const chunks = await holdRoute(page, arabic) + const html = page.locator("html") + const settings = await pickArabic(page) + await chunks.arrived + + await expect(settings.getByText("Language", { exact: true })).toBeVisible() + await expect(html).toHaveAttribute("dir", "ltr") + await expect(html).toHaveAttribute("lang", "en") + + chunks.release() + await expect(settings.getByText("اللغة", { exact: true })).toBeVisible() + await expect(html).toHaveAttribute("dir", "rtl") + await expect(html).toHaveAttribute("lang", "ar") +}) + +test("a language whose chunk fails to load keeps English and says so", async ({ page }) => { + await page.route(arabic, (route) => route.abort("failed")) + const settings = await pickArabic(page) + + await expect(page.getByText("Failed to load العربية", { exact: true })).toBeVisible() + await expect(settings.getByText("Language", { exact: true })).toBeVisible() + await expect(page.locator("html")).toHaveAttribute("dir", "ltr") + await expect(settings.locator('[data-action="settings-language"]')).toContainText("English") +}) + test("Questions settings default independently of old Permissions settings and survive reload", async ({ page }) => { const { settings } = await open(page, { seed: { @@ -468,6 +505,42 @@ test("several servers share one selected server across per-server pages", async await expect(settings.getByRole("button", { name: "Edit server", exact: true })).toBeVisible() }) +for (const server of [ + { name: "Signed-out box", url: REMOTE_SERVER, password: "secret" }, + // Nothing answers on this server. + { name: "Offline box", url: "http://127.0.0.1:4099" }, +]) { + test(`a project route on an unavailable server falls back to its Projects page (${server.name})`, async ({ + page, + }) => { + const remote = "/remote/settings-demo" + await mockWorkspace(page, { + name: "Settings demo", + directory, + provider: NO_PROVIDER, + sessions: [], + seed: { tabs: [] }, + }) + + if (server.password) + await mockRemoteServer(page, { name: server.name, directory: remote, password: server.password }) + + if (!server.password) await seed(page, { servers: [{ url: server.url, name: server.name }] }) + await page.goto( + `/settings?server=${encodeURIComponent(server.url)}&project=${encodeURIComponent(remote)}&tab=general`, + ) + const settings = page.getByTestId("settings-screen") + await expect(settings.getByRole("status").filter({ hasText: `Can't reach ${server.name}` })).toBeVisible() + await expect(settings.getByRole("heading", { name: "Projects", exact: true })).toBeVisible() + await expect(page).toHaveURL( + (url) => + url.searchParams.get("server") === server.url && + url.searchParams.get("tab") === "projects" && + !url.searchParams.has("project"), + ) + }) +} + test("project list menus rename, edit, add, and stay inside the scrollport", async ({ page }) => { const projects = ["rebase", "dinocms", "opencode", "Playground"].map((name, index) => project({ id: `project-${index}`, directory: `/projects/${name}`, name }), @@ -583,6 +656,30 @@ test("project list menus rename, edit, add, and stay inside the scrollport", asy await expect(page.locator('[data-component="home-project-row"]').filter({ hasText: "dinocms" })).toBeVisible() }) +test("a project rename that hangs keeps its field focused, and Escape cancels it without leaving settings", async ({ + page, +}) => { + const { settings } = await open(page) + const hold = await holdRoute(page, (url) => url.pathname === `/api/project/${projectID}`, { method: "PATCH" }) + await settings.getByRole("tab", { name: "Projects", exact: true }).click() + const card = settings.getByRole("listitem").filter({ hasText: "Settings demo" }) + await card.getByRole("button", { name: "More options", exact: true }).click() + await page.getByRole("menu").getByRole("menuitem", { name: "Rename", exact: true }).click() + const rename = settings.getByRole("textbox", { name: "Rename", exact: true }) + await expect(rename).toBeFocused() + await rename.fill("Renamed demo") + await rename.press("Enter") + await hold.arrived + + await expect(rename).toHaveAttribute("aria-busy", "true") + await expect(rename).toHaveAttribute("readonly", "") + await expect(rename).toBeFocused() + await rename.press("Escape") + await expect(card.getByRole("button", { name: "Settings demo", exact: true })).toBeFocused() + await expect(settings).toBeVisible() + hold.release() +}) + test("project settings open as a nested view that keeps its route", async ({ page }) => { const { settings } = await open(page) await openProject(page) @@ -650,6 +747,42 @@ test("a project whose folder is gone opens its settings with a notice", async ({ await expect(notice).toContainText(directory) }) +test("a project plugin list that fails to load offers Retry instead of an empty list", async ({ page }) => { + const { settings } = await open(page) + await openProject(page) + const lists = { failing: true } + + // Only the project's list carries a location; the server-wide list still loads. + await page.route(/\/api\/plugin\?.*location/, (route) => + route.fulfill( + lists.failing + ? { + status: 500, + json: { name: "UnknownError", data: { message: "config is invalid" } }, + headers: { "access-control-allow-origin": "*" }, + } + : { + json: { + location: { directory }, + data: [{ id: "project-plugin", source: { type: "package", target: "project-plugin" } }], + }, + headers: { "access-control-allow-origin": "*" }, + }, + ), + ) + + await settings.getByRole("tab", { name: "Extensions", exact: true }).click() + await settings.getByRole("tab", { name: "Plugins", exact: true }).click() + const panel = settings.getByRole("tabpanel", { name: "Plugins", exact: true }) + await expect(panel.getByRole("status")).toContainText("Could not load plugins") + await expect(panel.getByText("No plugins yet", { exact: true })).toHaveCount(0) + + lists.failing = false + await panel.getByRole("button", { name: "Try again", exact: true }).click() + await expect(panel.getByText("project-plugin", { exact: true })).toBeVisible() + await expect(panel.getByRole("status")).toHaveCount(0) +}) + for (const field of [ { name: "color", @@ -750,6 +883,45 @@ test("clearing project fields sends explicit removal values", async ({ page }) = } }) +test("Enter removes a custom project icon, and a failed save stays marked until it is sent again", async ({ page }) => { + const { settings } = await open(page) + await openProject(page) + const icon = settings.getByRole("button", { name: "Project icon", exact: true }) + await expect(icon.locator("img")).toHaveCount(1) + + // Keyboard and touch users never hover, so activating the icon alone removes it. + const cleared = patched(page) + await icon.focus() + await page.keyboard.press("Enter") + expect((await cleared).postDataJSON()).toEqual({ icon: { color: "orange", override: "" } }) + await expect(icon.locator("img")).toHaveCount(0) + await expect(settings.locator('[aria-busy="true"]')).toHaveCount(0) + + // Only the next save fails. + let failed = false + + await page.route(new RegExp(`/api/project/${projectID}(\\?|$)`), (route) => { + if (route.request().method() !== "PATCH" || failed) return route.fallback() + failed = true + + return route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ message: "down" }) }) + }) + + const blue = settings.getByRole("button", { name: "Select blue color", exact: true }) + const retry = settings.getByRole("button", { name: "Try again", exact: true }) + await blue.click() + await expect(retry).toBeVisible() + await expect(icon).toHaveAttribute("aria-invalid", "true") + await expect(blue).toHaveAttribute("aria-pressed", "true") + await expect(settings.locator('[aria-busy="true"]')).toHaveCount(0) + + const resent = patched(page) + await retry.click() + expect((await resent).postDataJSON()).toEqual({ icon: { color: "blue", override: "" } }) + await expect(retry).toHaveCount(0) + await expect(icon).not.toHaveAttribute("aria-invalid") +}) + test("shortcuts list Search sessions once and unbind a shortcut while recording it", async ({ page }) => { // Opening Settings from Home registers Home's Find, which must not add a second Search sessions. const { settings } = await open(page) @@ -784,6 +956,23 @@ for (const own of [false, true]) { }) } +test("typing in the shortcut search while recording filters instead of binding the key", async ({ page }) => { + const { settings } = await open(page) + await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click() + const binding = settings.locator('[data-keybind-id="tab.new"]') + const shortcut = (await binding.textContent()) ?? "" + await binding.click() + await expect(binding).toHaveText("Press keys") + + const search = settings.getByRole("searchbox", { name: "Search shortcuts", exact: true }) + await search.click() + await expect(binding).toHaveText(shortcut) + // "t" still lists the row: its shortcut contains T. + await page.keyboard.type("t") + await expect(search).toHaveValue("t") + await expect(binding).toHaveText(shortcut) +}) + test("the new session shortcut waits for a shortcut recording, then leaves settings", async ({ page }) => { const { settings } = await open(page) await settings.getByRole("tab", { name: "Shortcuts", exact: true }).click() @@ -967,6 +1156,20 @@ test.describe("pages open before slow data", () => { } }) +test("the version's Copied tooltip closes when another settings page opens", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]) + const { settings } = await open(page) + await page.route(contributors, (route) => route.abort("failed")) + await settings.getByRole("tab", { name: "About", exact: true }).click() + await settings.getByRole("button", { name: "Copy", exact: true }).click() + const tooltip = page.getByRole("tooltip") + await expect(tooltip).toHaveText("Copied") + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toMatch(/^Version /) + + await settings.getByRole("tab", { name: "Preferences", exact: true }).click() + await expect(tooltip).toBeHidden() +}) + test("worktrees follow inventory events, wait for session counts, and delete by project", async ({ page }) => { const empty = `${directory}/empty-workspace` const discovered = `${directory}/discovered-workspace` @@ -1048,6 +1251,103 @@ test("worktrees follow inventory events, wait for session counts, and delete by await expect(settings.getByLabel(sandboxes[0]!, { exact: true })).toHaveCount(0) }) +test("a failed worktree delete restores its row, and the next confirmation still deletes it", async ({ page }) => { + const inventory: WorktreeDirectory[] = [ + { directory }, + ...sandboxes.map((item) => ({ directory: item, strategy: "git" })), + ] + + const removals = { failing: true, requests: 0 } + + const { settings } = await open(page, { + worktrees: () => inventory, + onWorktreeRemove: (body) => { + inventory.splice( + inventory.findIndex((item) => item.directory === body.directory), + 1, + ) + }, + }) + + // The first removal fails at once, so its dialog is still closing when the row comes back. + await page.route(/\/api\/worktree(?:\?|$)/, (route) => { + if (route.request().method() !== "DELETE") return route.fallback() + removals.requests += 1 + + if (!removals.failing) return route.fallback() + removals.failing = false + + return route.fulfill({ status: 500, json: { name: "UnknownError", data: { message: "worktree is locked" } } }) + }) + + await settings.getByRole("tab", { name: "Worktrees", exact: true }).click() + await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible() + const trash = settings.getByRole("button", { name: "Delete “workspace-1”?", exact: true }) + + const confirm = page + .getByRole("dialog", { name: "Delete “workspace-1”?", exact: true }) + .getByRole("button", { name: "Delete worktree", exact: true }) + + await trash.click() + await confirm.click() + await expect(page.getByText("Failed to delete worktree", { exact: true })).toBeVisible() + await expect(trash).toBeEnabled() + await expect(settings.getByLabel(sandboxes[0]!, { exact: true })).toBeVisible() + expect(removals.requests).toBe(1) + + await trash.click() + await confirm.click() + await expect(settings.getByText("11 worktrees", { exact: true })).toBeVisible() + await expect(settings.getByLabel(sandboxes[0]!, { exact: true })).toHaveCount(0) + expect(removals.requests).toBe(2) +}) + +test("a failed worktree check offers Retry, and the passing retry enables Delete", async ({ page }) => { + const inventory: WorktreeDirectory[] = [ + { directory }, + ...sandboxes.map((item) => ({ directory: item, strategy: "git" })), + ] + + const { settings } = await open(page, { + worktrees: () => inventory, + onWorktreeRemove: (body) => { + inventory.splice( + inventory.findIndex((item) => item.directory === body.directory), + 1, + ) + }, + }) + + const checks = { failing: true } + + await page.route(/\/api\/vcs\/status(\?|$)/, (route) => + checks.failing + ? route.fulfill({ + status: 500, + json: { name: "UnknownError", data: { message: "git is busy" } }, + headers: { "access-control-allow-origin": "*" }, + }) + : route.fallback(), + ) + + await settings.getByRole("tab", { name: "Worktrees", exact: true }).click() + await expect(settings.getByText("12 worktrees", { exact: true })).toBeVisible() + await settings.getByRole("button", { name: "Delete “workspace-1”?", exact: true }).click() + const dialog = page.getByRole("dialog", { name: "Delete “workspace-1”?", exact: true }) + const remove = dialog.getByRole("button", { name: "Delete worktree", exact: true }) + const retry = dialog.getByRole("button", { name: "Try again", exact: true }) + await expect(dialog.getByText("Unable to verify git status.", { exact: true })).toBeVisible() + await expect(remove).toBeDisabled() + + checks.failing = false + await retry.click() + await expect(remove).toBeEnabled() + await expect(retry).toHaveCount(0) + await expect(dialog.getByText("Unable to verify git status.", { exact: true })).toHaveCount(0) + await remove.click() + await expect(settings.getByText("11 worktrees", { exact: true })).toBeVisible() +}) + test.describe("worktrees prefetch", () => { const other = project({ id: "proj_other", directory: "/repo/other", name: "Other project" }) @@ -1356,9 +1656,7 @@ test("providers: a rejected API key shows the server error and can be sent again expect(keys).toEqual([expect.objectContaining({ key: "sk-bad" })]) }) -test("providers: Back during a pending API key request does not report the provider as connected", async ({ - page, -}) => { +test("providers: Back during a pending API key request does not report the provider as connected", async ({ page }) => { const keys: string[] = [] const { settings } = await open(page, { @@ -1579,6 +1877,117 @@ test("providers: adding an account starts a lone method once", async ({ page, co expect(attempts).toEqual(["github-copilot"]) }) +test("providers: Back from a pending sign-in cancels it and lets a backdrop click close the list", async ({ + page, + context, +}) => { + await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" })) + const cancelled: string[] = [] + + const { settings } = await open(page, { + integrations: [ + { + id: "github-copilot", + name: "GitHub Copilot", + methods: [{ id: "device", type: "oauth", label: "GitHub" }], + connections: [], + }, + ], + onIntegrationOAuth: () => ({ url: "https://auth.example.test/device?user_code=GH12-3456" }), + onIntegrationOAuthCancel: (attemptID) => cancelled.push(attemptID), + }) + + await settings.getByRole("tab", { name: "Providers", exact: true }).click() + await settings.getByRole("button", { name: "Show more providers", exact: true }).click() + const dialog = page.getByRole("dialog") + const popup = page.waitForEvent("popup") + await dialog.locator('[data-provider-id="github-copilot"]').click() + await popup + await expect(dialog.getByText("Waiting for authorization…", { exact: true })).toBeVisible() + + await dialog.getByRole("button", { name: "Navigate back", exact: true }).click() + await expect(dialog.locator('[data-provider-id="github-copilot"]')).toBeVisible() + await expect.poll(() => cancelled).toEqual(["con_mock_1"]) + + // The page corner is outside the dialog, so the click lands on the backdrop. + await page.mouse.click(8, 8) + await expect(dialog).toHaveCount(0) +}) + +test("providers: Back from a Claude Agent check started by Add account returns to its accounts", async ({ page }) => { + const { settings } = await open(page, { + integrations: [ + { + id: "claude-agent", + name: "Claude Agent", + methods: [{ id: "claude-login", type: "external", label: "Claude Code login (claude auth login)" }], + connections: [{ type: "credential", id: "cred_claude", label: "Claude Code", method: "external" }], + }, + ], + }) + + const held = await holdRoute(page, /\/api\/integration\/claude-agent\/connect\/external(\?|$)/, { method: "POST" }) + await settings.getByRole("tab", { name: "Providers", exact: true }).click() + await settings.getByRole("button", { name: "Show more providers", exact: true }).click() + const dialog = page.getByRole("dialog") + await dialog.locator('[data-provider-id="claude-agent"]').click() + await dialog.getByRole("button", { name: "Add account", exact: true }).click() + await dialog.getByRole("button", { name: "Check again", exact: true }).click() + await held.arrived + await expect(dialog.getByText("Checking Claude Code…", { exact: true })).toBeVisible() + + await dialog.getByRole("button", { name: "Navigate back", exact: true }).click() + await expect(dialog.getByRole("radio", { name: "Claude Code", exact: true })).toBeVisible() + held.release() +}) + +test("providers: Back from a Console connection without models returns to its sign-in methods", async ({ + page, + context, +}) => { + await context.route("https://auth.example.test/**", (route) => route.fulfill({ body: "Sign in" })) + const state = { authorized: false } + + const { settings } = await open(page, { + // The workspace has loaded, but it offers no models. + provider: () => + state.authorized + ? { + all: [ + { id: "opencode", integrationID: "opencode", name: "Anomaly / OpenCode", models: {} }, + { id: "console-google", integrationID: "opencode", name: "Anomaly / Google", models: {} }, + ], + connected: ["opencode", "console-google"], + default: {}, + } + : NO_PROVIDER, + integrations: consoleIntegrations, + onIntegrationOAuth: () => ({ url: "https://auth.example.test/device?user_code=ABCD-EFGH" }), + onIntegrationOAuthStatus: () => { + state.authorized = true + + return "complete" + }, + }) + + await settings.getByRole("tab", { name: "Providers", exact: true }).click() + await settings + .locator(".settings-provider-row", { hasText: "OpenCode Console" }) + .getByRole("button", { name: "Connect", exact: true }) + .click() + const dialog = page.getByRole("dialog", { name: "Connect OpenCode Console", exact: true }) + const popup = page.waitForEvent("popup") + await dialog.getByRole("button", { name: "OpenCode Console account", exact: true }).click() + await popup + await expect(page.getByRole("dialog").getByText("OpenCode connected", { exact: true })).toBeVisible() + + await page.getByRole("dialog").getByRole("button", { name: "Navigate back", exact: true }).click() + await expect(dialog.locator('[data-action="provider-connect-method"]')).toHaveText([ + "OpenCode Console account", + "API key (service account)", + ]) +}) + test("providers: the account options rename and remove the active account", async ({ page }) => { const account = { type: "credential", id: "cred_work", label: "Work", method: "key" } const other = { type: "credential", id: "cred_personal", label: "Personal", method: "key" } @@ -1858,6 +2267,65 @@ test("providers: switching Console accounts keeps the list until the new workspa await expect(connected).not.toHaveAttribute("data-flashed") }) +test("models: a Console provider picked on Providers opens its collapsed group, then the search types normally", async ({ + page, +}) => { + const model = (id: string, name: string) => ({ [id]: { id, name, limit: { context: 200_000 } } }) + + const { settings } = await open(page, { + provider: { + all: [ + { + id: "opencode", + integrationID: "opencode", + name: "Anomaly / OpenCode", + models: model("console-model", "Console Model"), + }, + { + id: "console-google", + canonical: "google", + integrationID: "opencode", + name: "Anomaly / Google", + models: model("managed-gemini", "Managed Gemini"), + }, + ], + connected: ["opencode", "console-google"], + default: {}, + }, + integrations: [ + { + id: "opencode", + name: "OpenCode Console", + methods: [{ id: "device", type: "oauth", label: "OpenCode Console account" }], + connections: [{ type: "credential", id: "cred_anomaly", label: "Anomaly", method: "oauth" }], + }, + ], + }) + + const group = settings + .locator('[data-component="settings-models-console"]') + .getByRole("button", { name: /^OpenCode Console/ }) + + await settings.getByRole("tab", { name: "Models", exact: true }).click() + await group.click() + await expect(group).toHaveAttribute("aria-expanded", "false") + + await settings.getByRole("tab", { name: "Providers", exact: true }).click() + const connected = settings.locator('[data-component="connected-providers-section"]') + await connected.getByRole("button", { name: "2 providers available", exact: true }).click() + await connected.getByRole("button", { name: "Google", exact: true }).click() + + // The nested provider mounts only inside the expanded Console group, so the reveal opens the group first. + const google = settings.locator('[data-component="provider-model-group"][data-provider="console-google"]') + await expect(group).toHaveAttribute("aria-expanded", "true") + await expect(google.locator(".provider-model-group-trigger")).toBeFocused() + + const search = settings.getByRole("searchbox", { name: "Search models", exact: true }) + await search.pressSequentially("gemini") + await expect(search).toHaveValue("gemini") + await expect(settings.getByRole("switch", { name: "Managed Gemini", exact: true })).toBeVisible() +}) + test("the add server dialog keeps focus above fullscreen settings", async ({ page }) => { await mockRemoteServer(page, { directory: "/remote/settings-demo" }) const { settings } = await open(page) @@ -1916,6 +2384,44 @@ test("the add server dialog pairs from a one-time link and explains a spent one" ) }) +test("a server check that answers after its dialog closed saves nothing and leaves the next dialog open", async ({ + page, +}) => { + const late = "http://127.0.0.1:4098" + await mockRemoteServer(page, { directory: "/remote/settings-demo" }) + await mockOpenCodeServer(page, { + server: late, + directory: "/remote/late", + project: project({ id: "proj_late", directory: "/remote/late" }), + provider: NO_PROVIDER, + sessions: [], + pageMessages: () => ({ items: [] }), + }) + const check = await holdRoute(page, /^http:\/\/127\.0\.0\.1:4098\/api\/info/) + const { settings } = await open(page) + await settings.getByRole("tab", { name: "Servers", exact: true }).click() + await settings.getByRole("button", { name: "Add server" }).click() + const editor = page.getByRole("dialog", { name: "Add server" }) + await editor.getByRole("button", { name: "Use password", exact: true }).click() + await editor.getByLabel("Server address", { exact: true }).fill(late) + await editor.getByRole("button", { name: "Add server", exact: true }).click() + await check.arrived + await page.keyboard.press("Escape") + await expect(editor).toHaveCount(0) + + await settings.getByRole("button", { name: "Add server" }).click() + const link = editor.getByLabel("Pairing link", { exact: true }) + await expect(link).toBeFocused() + const answered = page.waitForResponse(/^http:\/\/127\.0\.0\.1:4098\/api\/info/) + check.release() + await answered + // A round trip after the answer: the cancelled check had every chance to save and close by now. + await link.fill("still open") + + await expect(link).toHaveValue("still open") + await expect(settings.getByText(late, { exact: true })).toHaveCount(0) +}) + test("a pairing code with several addresses keeps the first one that works with its token", async ({ page }) => { // Both addresses reach one server. The second spends the code first, so the first answers 401, and the token works on // it as on every address of that server. diff --git a/packages/app/e2e/regression/side-panels.spec.ts b/packages/app/e2e/regression/side-panels.spec.ts index ef129849eb1e..d03eb1d705b1 100644 --- a/packages/app/e2e/regression/side-panels.spec.ts +++ b/packages/app/e2e/regression/side-panels.spec.ts @@ -96,6 +96,52 @@ test("new tab selection and closing stay in the focused pane", async ({ page }) await expect(sideTabs.nth(0)).toHaveAttribute("aria-selected", "true") }) +test("closing another pane's tab keeps the side pane's New tab", async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }) + const directory = "C:/OpenCode/OtherPaneClose" + const key = `local\u0000${base64Encode(directory)}/ses_otherpaneclose` + + await openSession(page, { + name: "OtherPaneClose", + fileList: () => [], + fileContent: (path) => ({ type: "text", content: `contents:${path}` }), + seed: { + panes: { ses_otherpaneclose: { review: true } }, + storage: { + "opencode.global.dat:layout": { + sessionTabs: { + // The side pane selects nothing of its own, so it shows its fallback tab while the split pane is active. + [key]: { + all: ["review:changes", "file://README.md", "file://notes.md"], + active: "file://notes.md", + panes: { "file://notes.md": "split" }, + selected: { split: "file://notes.md" }, + }, + }, + }, + }, + }, + }) + + const side = page.locator('[data-pane-content="side"]') + const split = page.locator('[data-pane-content="split"]') + const sideNewTab = side.getByRole("tab", { name: "New tab", exact: true }) + await expect(side.getByRole("tab", { name: "README.md", exact: true })).toHaveAttribute("aria-selected", "true") + + await side.getByRole("button", { name: "Add tab", exact: true }).click() + await expect(sideNewTab).toHaveAttribute("aria-selected", "true") + + // The selection falls back to the side pane's first tab, which is already listed there: no launcher opened it. + await split.getByRole("tab", { name: "notes.md", exact: true }).hover() + await split + .locator('div[data-value="file://notes.md"]') + .getByRole("button", { name: "Close tab", exact: true }) + .click() + await expect(split).toHaveCount(0) + await expect(sideNewTab).toHaveCount(1) + await expect(sideNewTab).toHaveAttribute("aria-selected", "true") +}) + test("closing the last New tab closes the side region, and only a New tab lists the launchers", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }) await openSession(page, { name: "LastNewTab", seed: { panes: { ses_lastnewtab: { review: true } } } }) @@ -127,6 +173,54 @@ test("closing the last New tab closes the side region, and only a New tab lists } }) +test("New tabs stay when a launcher in another one opens a tab, or when the tab before them closes", async ({ + page, +}) => { + await page.setViewportSize({ width: 1440, height: 900 }) + await openSession(page, { name: "ManyNewTabs", seed: { panes: { ses_manynewtabs: { review: true } } } }) + + const panel = page.locator("#review-panel") + const toggle = page.getByRole("button", { name: "Toggle review", exact: true }) + const newTabs = panel.getByRole("tab", { name: "New tab", exact: true }) + const review = panel.getByRole("tab", { name: "Review", exact: true }) + + await expect(newTabs).toHaveCount(1) + await panel.getByRole("button", { name: "Add tab", exact: true }).click() + await panel.getByRole("button", { name: "Add tab", exact: true }).click() + await expect(newTabs).toHaveCount(3) + await expect(newTabs.nth(2)).toHaveAttribute("aria-selected", "true") + + // A launcher in the middle New tab replaces only that one. + await newTabs.nth(1).click() + await openReviewLauncher(panel) + await expect(review).toHaveAttribute("aria-selected", "true") + await expect(newTabs).toHaveCount(2) + + // Selecting another tab keeps the New tabs too. + await newTabs.nth(0).click() + await expect(newTabs.nth(0)).toHaveAttribute("aria-selected", "true") + await review.click() + await expect(review).toHaveAttribute("aria-selected", "true") + await expect(newTabs).toHaveCount(2) + + // Closing the strip's first tab shows a New tab instead of closing the region. + await review.hover() + await panel + .locator('div[data-value="review:changes"]') + .getByRole("button", { name: "Close tab", exact: true }) + .click() + await expect(review).toHaveCount(0) + await expect(toggle).toHaveAttribute("aria-expanded", "true") + await expect(newTabs).toHaveCount(2) + await expect(newTabs.nth(1)).toHaveAttribute("aria-selected", "true") + + // The region closes with its last New tab. + await newTabs.nth(0).click({ button: "middle" }) + await expect(newTabs).toHaveCount(1) + await newTabs.click({ button: "middle" }) + await expect(toggle).toHaveAttribute("aria-expanded", "false") +}) + test("tabs in a narrow side strip shrink to keep their close buttons, and a tab's menu closes the others", async ({ page, }) => { @@ -238,12 +332,12 @@ test("the new tab view lists recently closed tabs, expands to the rest, and keep await expect(recent.getByRole("button", { name: "Show more", exact: true })).toHaveCount(0) await expect(recent.getByRole("button", { name: "Show less", exact: true })).toHaveCount(0) - // Closing the last tab closes the region; it opens on its launchers with that tab listed first. + // Closing the last tab keeps the region open on the New tab beside it, which lists that tab first. const readme = panel.getByRole("tab", { name: "README.md" }) await readme.click() + await expect(panel.getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "false") await readme.locator("..").getByRole("button", { name: "Close tab" }).click() - await expect(toggle).toHaveAttribute("aria-expanded", "false") - await toggle.click() + await expect(toggle).toHaveAttribute("aria-expanded", "true") await expect(panel.getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true") await expect(rows.first()).toContainText("README.md") diff --git a/packages/app/e2e/regression/tabs.spec.ts b/packages/app/e2e/regression/tabs.spec.ts index bef7c8638d9f..7a5bd803a42e 100644 --- a/packages/app/e2e/regression/tabs.spec.ts +++ b/packages/app/e2e/regression/tabs.spec.ts @@ -396,6 +396,36 @@ for (const tabLayout of ["horizontal", "vertical"] as const) { }) } +test("a tab whose overlapping renames both fail shows its saved title again", async ({ page }) => { + await mockWorkspace(page, { name: "Tabs", sessions: [a, b] }) + await page.goto(sessionHref(a.id)) + const title = page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(a.id)}"]) [data-slot="tab-title"]`) + const editor = page.locator('[data-slot="tab-title"][contenteditable="plaintext-only"]') + await expect(title).toHaveText(a.title) + const released = Promise.withResolvers() + const saves: string[] = [] + await page.route(new RegExp(`/api/session/${a.id}(\\?|$)`), async (route) => { + if (route.request().method() !== "PATCH") return route.fallback() + saves.push(route.request().postDataJSON().title) + await released.promise + await route.fulfill({ status: 500, json: { message: "Rename failed" } }) + }) + + for (const name of ["First name", "Second name"]) { + await title.dblclick() + await expect(editor).toBeFocused() + await editor.fill(name) + await editor.press("Enter") + await expect(title).toHaveText(name) + } + + await expect.poll(() => saves).toEqual(["First name", "Second name"]) + released.resolve() + // The rollback restores the title the server holds, never the first rename that was never saved. + await expect(title).toHaveText(a.title) + await expect(page.locator('[data-testid^="toast-v2-"]').filter({ hasText: "Request failed" })).toHaveCount(1) +}) + for (const tabLayout of ["horizontal", "vertical"] as const) { test(`a ${tabLayout} tab deletes its session after confirmation`, async ({ page }) => { await mockWorkspace(page, { name: "Tabs", sessions: [a, b], seed: { settings: { appearance: { tabLayout } } } }) @@ -624,6 +654,22 @@ test("icon-only inactive tabs retain their avatar and attention badge instead of await expect(tabB.locator('[data-slot="tab-avatar-unread-dot"]')).toHaveCount(0) }) +test("an unread tab whose run failed shows the failed dot, as the inbox does", async ({ page }) => { + const time = { created: T0, updated: T0, idle: T0 + 1 } + + await mockWorkspace(page, { + name: "FailedTabs", + sessions: [a, { ...b, outcome: "failed", time }, { ...c, outcome: "succeeded", time }], + }) + await page.goto(sessionHref(a.id)) + const tab = (id: string) => page.locator(`[data-titlebar-tab-slot]:has(a[href="${sessionHref(id)}"])`) + + await expect(tab(b.id).locator('[data-mark="failed"]')).toBeVisible() + await expect(tab(b.id).locator('[data-mark="unread"]')).toBeHidden() + await expect(tab(c.id).locator('[data-mark="unread"]')).toBeVisible() + await expect(tab(c.id).locator('[data-mark="failed"]')).toBeHidden() +}) + test("vertical tabs resize, scroll, show shortcut hints, and navigate", async ({ page }) => { await page.setViewportSize({ width: 1280, height: 480 }) const directory = "C:/OpenCode/Tabs" @@ -808,6 +854,47 @@ for (const [screen, href] of [ }) } +test("the collapsed sidebar peeks from a resting toggle, Escape cancels a pending peek, and a click docks it", async ({ + page, +}) => { + await mockWorkspace(page, { + name: "Tabs", + sessions: [a], + seed: { settings: { appearance: { tabLayout: "vertical", sidebarOpen: false } } }, + }) + await page.goto(sessionHref(a.id)) + + const sidebar = page.locator('[data-slot="vertical-tabs-sidebar"]') + + const toggle = page + .locator('[data-slot="collapsed-sidebar-toggle"]') + .getByRole("button", { name: "Toggle sidebar", exact: true }) + + await expect(sidebar).toHaveAttribute("data-state", "closed") + await expect(toggle).toBeVisible() + // See "tab preview opens cold": pause at a fixed offset from an explicit install time. + const start = Date.now() + await page.clock.install({ time: start }) + await page.clock.pauseAt(start + 10_000) + + // The toggle's 500ms dwell, cut short by Escape, never peeks. + await toggle.hover() + await page.keyboard.press("Escape") + await page.clock.runFor(600) + await expect(sidebar).not.toHaveAttribute("data-peek") + + await page.mouse.move(600, 400) + await toggle.hover() + await page.clock.runFor(600) + await expect(sidebar).toHaveAttribute("data-peek", "") + + // Docking from the peek hands the sidebar over, and the peek ends once the dock lands. + await toggle.click() + await page.clock.runFor(2000) + await expect(sidebar).toHaveAttribute("data-state", "open") + await expect(sidebar).not.toHaveAttribute("data-peek") +}) + test("vertical tab gaps hover and select the nearest row", async ({ page }) => { await mockWorkspace(page, { name: "Tabs", @@ -1409,6 +1496,39 @@ test("⌘W past the side panel's last tab keeps the session tab", async ({ page await expect(sessions.alphaTab).toHaveCount(0) }) +test("⌘W past the side panel's last tab keeps the session tab when focus leaves the panel just after", async ({ + page, +}) => { + // Stands in for a panel that hands focus back after its close rather than during it. + await page.addInitScript(() => { + const observer = new MutationObserver((records) => { + const hidden = records.some( + (record) => + record.target instanceof Element && + record.target.id === "review-panel" && + record.target.getAttribute("aria-hidden") === "true", + ) + + if (!hidden) return + observer.disconnect() + document.querySelector('[data-component="composer-editor"]')?.focus() + }) + + observer.observe(document, { subtree: true, attributes: true, attributeFilter: ["aria-hidden"] }) + }) + + const sessions = await emptySidePanel(page) + const composer = page.getByRole("textbox", { name: "Prompt", exact: true }) + await expect(composer).toBeFocused() + await page.keyboard.press("ControlOrMeta+w") + + // Only a swallowed press above leaves Beta for this one to land on. + await composer.click() + await page.keyboard.press("ControlOrMeta+w") + await expectPath(page, sessionHref(sessions.beta.id)) + await expect(sessions.alphaTab).toHaveCount(0) +}) + test("⌘W closes the session tab again once the window loses focus after the side panel empties", async ({ page }) => { const sessions = await emptySidePanel(page) // ⌘Tab away and back sends no click or key the page sees. @@ -1726,14 +1846,69 @@ test("the inbox Archived dialog searches only archived sessions and restores the await expect(dialog.getByText("No results found", { exact: true })).toBeVisible() await search.fill("First archived") await expect(dialog.getByRole("option")).toHaveCount(1) - await expect(dialog.getByRole("option", { name: /First archived session/ })).toHaveAttribute("aria-selected", "true") + const option = dialog.getByRole("option", { name: /First archived session/ }) + await expect(option).toHaveAttribute("aria-selected", "true") + + // A second Enter while the restore is in flight restores and opens the session once. + const restore = await holdRoute(page, /\/api\/session\/ses_archive_0(\?|$)/, { method: "PATCH" }) + await search.press("Enter") + await restore.arrived + await expect(option).toHaveAttribute("aria-busy", "true") + await expect(option.getByRole("img", { name: "Loading", exact: true })).toBeVisible() await search.press("Enter") + await expect(dialog).toBeVisible() + restore.release() await expect(dialog).toHaveCount(0) + expect(restore.requests).toHaveLength(1) await expectPath(page, sessionHref("ses_archive_0")) await expect(page.locator('[data-component="composer-editor"]')).toBeEditable() await expect(rows.filter({ hasText: "First archived session" })).toHaveAttribute("data-state", "active") }) +test("deleting from the inbox closes its dialog at once and a slow delete leaves the next dialog open", async ({ + page, +}) => { + await mockWorkspace(page, { + name: "DeleteInbox", + sessions: [ + { id: "ses_delete_kept", title: "Kept inbox session", time: { created: T0, updated: T0, idle: T0, viewed: T0 } }, + { + id: "ses_delete_target", + title: "Deleted inbox session", + time: { created: T0, updated: T0 + 1, idle: T0 + 1, viewed: T0 + 1 }, + }, + ], + seed: { settings: { appearance: { tabLayout: "inbox" } }, tabs: [] }, + }) + const remove = await holdRoute(page, /\/api\/session\/ses_delete_target(\?|$)/, { method: "DELETE" }) + await page.goto("/") + + const rows = page.locator('[data-slot="sidebar-inbox"] [data-slot="sidebar-inbox-item"]') + await expect(rows).toHaveCount(2) + await rows.filter({ hasText: "Deleted inbox session" }).click({ button: "right" }) + await page.getByRole("menuitem", { name: "Delete…", exact: true }).click() + + const confirm = page.getByRole("dialog", { name: "Delete session" }) + await confirm.getByRole("button", { name: "Delete session", exact: true }).click() + await remove.arrived + await expect(confirm).toHaveCount(0) + await expect(rows).toHaveCount(1) + await expect(rows).toContainText("Kept inbox session") + + await page.getByRole("button", { name: "Search sessions", exact: true }).click() + const search = page.getByRole("dialog") + await expect(search.getByRole("combobox")).toBeFocused() + + const removed = page.waitForResponse( + (response) => response.request().method() === "DELETE" && response.url().includes("/api/session/ses_delete_target"), + ) + + remove.release() + await removed + await expect(search.getByRole("combobox")).toBeFocused() + expect(remove.requests).toHaveLength(1) +}) + test("opening a working session expands its shelf and still allows manual collapse", async ({ page }) => { await openSession(page, { name: "WorkingInbox", diff --git a/packages/app/e2e/regression/terminal.spec.ts b/packages/app/e2e/regression/terminal.spec.ts index 6223c2473c38..762fd293853c 100644 --- a/packages/app/e2e/regression/terminal.spec.ts +++ b/packages/app/e2e/regression/terminal.spec.ts @@ -1,5 +1,6 @@ import { expect, test, type Page } from "@playwright/test" -import { holdRoute } from "../utils/app" +import { SERVER, holdRoute } from "../utils/app" +import { installSseTransport } from "../utils/sse-transport" import { terminalScreen, terminalText } from "../utils/terminal" import { openSession } from "../utils/workspace" @@ -147,6 +148,70 @@ test("the New terminal shortcut creates the next numbered terminal", async ({ pa await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeFocused() }) +// Closing the palette returns focus to the composer while the terminal is still being created. +test("New terminal from the command palette opens the terminal focused", async ({ page }) => { + const { persistentPty, editor } = await openSession(page, { name: "Terminals", persistentPty: {} }) + + await editor.click() + await page.keyboard.press("Control+Shift+P") + const palette = page.getByRole("dialog") + const input = palette.getByRole("combobox") + await expect(input).toBeFocused() + await input.fill("New terminal") + await expect(palette.getByRole("option", { name: /^New terminal/ })).toHaveAttribute("aria-selected", "true") + await input.press("Enter") + + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute( + "aria-selected", + "true", + ) + await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeFocused() +}) + +test("a click into the composer while a new terminal is created keeps the focus there", async ({ page }) => { + const { persistentPty, editor } = await openSession(page, { name: "Terminals", persistentPty: {} }) + + const create = await holdRoute(page, /\/api\/experimental\/session\/ses_terminals\/terminal(\?|$)/, { + method: "POST", + }) + + await editor.click() + await page.keyboard.press("Control+Alt+T") + await create.arrived + await editor.click() + create.release() + + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute( + "aria-selected", + "true", + ) + await expect.poll(() => persistentPty.sockets.length).toBe(1) + await expect(editor).toBeFocused() +}) + +// Both presses used to send a create, so two tabs both titled "Terminal 1" opened. +test("pressing New terminal again while one is created creates one terminal", async ({ page }) => { + const { persistentPty, editor } = await openSession(page, { name: "Terminals", persistentPty: {} }) + + const create = await holdRoute(page, /\/api\/experimental\/session\/ses_terminals\/terminal(\?|$)/, { + method: "POST", + }) + + await editor.click() + await page.keyboard.press("Control+Alt+T") + await create.arrived + await page.keyboard.press("Control+Alt+T") + create.release() + + await expect(side(page).getByRole("tab", { name: "Terminal 1", exact: true })).toHaveAttribute( + "aria-selected", + "true", + ) + await expect(terminalScreen(page, persistentPty.created[0]!.id).locator("textarea")).toBeFocused() + expect(create.requests).toHaveLength(1) + expect(persistentPty.created.map((info) => info.title)).toEqual(["Terminal 1"]) +}) + test("another client's control ends at a click, which resizes the terminal to the pane", async ({ page }) => { const { persistentPty } = await openSession(page, { name: "Terminals", @@ -246,6 +311,37 @@ test("a terminal list that fails says why, and Try again lists the terminals", a await expect(side(page).getByText("Couldn't load terminals", { exact: true })).toHaveCount(0) }) +// A list the server accepted and never answered used to leave "Loading terminal." on screen with no way to retry. +test("a terminal list the server never answers says so, and Try again lists the terminals", async ({ page }) => { + await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_build", sessionID: SESSION, title: "Build", output: "still-here\r\n" }] }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + const screen = terminalScreen(page, "pty_build") + await expect.poll(() => terminalText(page, screen)).toBe("still-here") + + const list = await holdRoute(page, /\/api\/experimental\/session\/ses_terminals\/terminal(\?|$)/, { method: "GET" }) + await page.clock.install() + await page.reload() + await list.arrived + await expect(side(page).getByText("Loading terminal…", { exact: true })).toBeVisible() + // The request budget, `TERMINAL_REQUEST_TIMEOUT_MS`. + await page.clock.fastForward(15_000) + + const failure = side(page).getByRole("alert") + await expect(failure.getByText("Couldn't load terminals", { exact: true })).toBeVisible() + await expect(failure.getByText("The server took too long to answer", { exact: true })).toBeVisible() + + list.release() + await failure.getByRole("button", { name: "Try again", exact: true }).click() + + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "true") + await expect.poll(() => terminalText(page, screen)).toBe("still-here") +}) + test("after a server restart, showing the terminal again restores it from a new snapshot", async ({ page }) => { const output = "before-restart\r\n" @@ -266,7 +362,7 @@ test("after a server restart, showing the terminal again restores it from a new // Showing the tab again takes a new snapshot and reconnects. await side(page).getByRole("button", { name: "Add tab", exact: true }).click() - await expect(side(page).getByRole("tab", { name: "New tab", exact: true })).toHaveAttribute("aria-selected", "true") + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "false") await side(page).getByRole("tab", { name: "Build", exact: true }).click() await expect.poll(() => terminalText(page, screen)).toBe("before-restart\nafter-restart") await expect(side(page).getByText("Terminal disconnected", { exact: true })).toHaveCount(0) @@ -276,6 +372,37 @@ test("after a server restart, showing the terminal again restores it from a new ]) }) +test("once a restarted server reconnects, the shown terminal restores itself from a new snapshot", async ({ page }) => { + const output = "before-restart\r\n" + const transport = await installSseTransport(page, { server: SERVER, retry: 20 }) + + const { persistentPty } = await openSession(page, { + name: "Terminals", + persistentPty: { initial: [{ id: "pty_handoff", sessionID: SESSION, title: "Build", output }] }, + }) + + await openSide(page) + await side(page).getByRole("tab", { name: "Build", exact: true }).click() + const screen = terminalScreen(page, "pty_handoff") + await expect.poll(() => terminalText(page, screen)).toBe("before-restart") + + // The terminal socket closes first; the event stream drops and reconnects to the restarted server after it. + await persistentPty.restart() + await expect(side(page).getByText("Terminal disconnected", { exact: true })).toBeVisible() + persistentPty.output("pty_handoff", "after-restart\r\n") + const connection = await transport.waitForConnection() + await transport.disconnect() + await transport.waitForConnection({ after: connection.id }) + + await expect.poll(() => terminalText(page, screen)).toBe("before-restart\nafter-restart") + await expect(side(page).getByText("Terminal disconnected", { exact: true })).toHaveCount(0) + await expect(side(page).getByRole("tab", { name: "Build", exact: true })).toHaveAttribute("aria-selected", "true") + expect(persistentPty.sockets.map((socket) => socket.cursor)).toEqual([ + Buffer.byteLength(output), + Buffer.byteLength(output + "after-restart\r\n"), + ]) +}) + test("a server without persistent terminals offers no terminal commands", async ({ page }) => { const { editor } = await openSession(page, { name: "Terminals", persistentPty: { capability: false } }) @@ -300,11 +427,21 @@ test("selected terminal output quotes into the composer", async ({ page }) => { await side(page).getByRole("tab", { name: "Build", exact: true }).click() const screen = terminalScreen(page, "pty_quote") await expect.poll(() => terminalText(page, screen)).toBe("quote-me") + const toolbar = page.getByRole("toolbar", { name: "Quote selection", exact: true }) + await expect(toolbar).toBeVisible() - await page - .getByRole("toolbar", { name: "Quote selection", exact: true }) - .getByRole("button", { name: "Quote" }) - .click() + // A right click opens a context menu without a pointerup; it neither closes the toolbar nor blocks later reads. + await page.locator("body").dispatchEvent("pointerdown", { button: 2 }) + await page.locator("body").dispatchEvent("contextmenu") + await expect(toolbar).toBeVisible() + + // A cancelled touch ends without a pointerup too; the selection it left in place gets its toolbar back. + await page.locator("body").dispatchEvent("pointerdown", { button: 0 }) + await expect(toolbar).toHaveCount(0) + await page.locator("body").dispatchEvent("pointercancel") + await expect(toolbar).toBeVisible() + + await toolbar.getByRole("button", { name: "Quote" }).click() await expect(page.locator('[data-component="composer"]').getByText("quote-me")).toBeVisible() }) diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts index e1d41a7cf6c0..f5990a4fd69a 100644 --- a/packages/app/e2e/regression/timeline-geometry.spec.ts +++ b/packages/app/e2e/regression/timeline-geometry.spec.ts @@ -560,6 +560,76 @@ for (const failed of [false, true]) { }) } +test("keeps a reader scrolled up in place when they submit a prompt", async ({ page }) => { + await setupTimeline(page, { + reducedMotion: true, + sessionMessages: [ + ...validateTimelineMessages([...historyMessages(18), userMessage()]), + { id: "msg_1002_timeline_idle", type: "idle", outcome: "succeeded", time: { created: 1700000003000 } }, + ], + }) + const scroller = page.locator('[data-slot="session-timeline-scroll"] > [data-scrollable]') + const top = () => scroller.evaluate((element) => element.scrollTop) + const fromEnd = () => scroller.evaluate((element) => element.scrollHeight - element.clientHeight - element.scrollTop) + const jump = page.getByRole("button", { name: "Jump to latest" }) + const text = "Sent while reading above." + const editor = page.locator('[data-component="composer"]').getByRole("textbox") + await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + await expect.poll(fromEnd).toBeLessThanOrEqual(1) + + await scroller.hover() + await page.mouse.wheel(0, -1200) + await expect.poll(fromEnd).toBeGreaterThan(600) + await expect(jump).toBeInViewport() + await editor.fill(text) + const resting = await top() + const below = await fromEnd() + + const requested = page.waitForRequest( + (request) => request.method() === "POST" && new URL(request.url()).pathname === `/api/session/${sessionID}/prompt`, + ) + + // Records the scroll position in every frame from submission until the sent prompt has grown the timeline. + const observation = await scroller.evaluateHandle((element) => { + const tops: number[] = [] + let frame = 0 + + const sample = () => { + tops.push(element.scrollTop) + frame = requestAnimationFrame(sample) + } + + frame = requestAnimationFrame(sample) + + return { + stop: () => { + cancelAnimationFrame(frame) + + return tops + }, + } + }) + + try { + await editor.press("Enter") + expect((await requested).postDataJSON()).toMatchObject({ text }) + await expect(editor).toHaveText("") + // The sent prompt lands below the reader, so the distance to the end grows while the reader stays put. + await expect.poll(fromEnd).toBeGreaterThan(below) + const tops = await observation.evaluate((value) => value.stop()) + expect(tops.length).toBeGreaterThan(0) + expect(tops.every((value) => Math.abs(value - resting) <= 1)).toBe(true) + expect(Math.abs((await top()) - resting)).toBeLessThanOrEqual(1) + await expect(jump).toBeInViewport() + } finally { + await observation.dispose() + } + + await jump.click() + await expect(page.locator('[data-timeline-row="UserMessage"]').filter({ hasText: text })).toBeInViewport() + await expect.poll(fromEnd).toBeLessThanOrEqual(1) +}) + async function captureCardEdges(page: Page, card: Locator) { const box = await card.boundingBox() @@ -633,10 +703,28 @@ async function captureCardEdges(page: Page, card: Locator) { ) } -test("scrolls the timeline behind the composer region, fading at the card, and keeps its end above the region", async ({ - page, -}) => { +// Without hover the activity pill grows to its 44px touch size, and the tail it floats in grows with it. +for (const input of [ + { name: "a pointer", touch: false, viewport: { width: 1400, height: 900 }, pill: 32 }, + { name: "touch", touch: true, viewport: { width: 390, height: 844 }, pill: 44 }, +]) { + test.describe(`with ${input.name}`, () => { + test.use({ hasTouch: input.touch, isMobile: input.touch }) + + test("scrolls the timeline behind the composer region, fading at the card, and keeps its end above the region", async ({ + page, + }) => { + await scrollsBehindComposerRegion(page, input) + }) + }) +} + +async function scrollsBehindComposerRegion( + page: Page, + input: { viewport: { width: number; height: number }; pill: number }, +) { await setupTimeline(page, { + viewport: input.viewport, sessionMessages: [ ...validateTimelineMessages(historyMessages(18)), { id: "msg_9000_user", type: "user", text: "Split the work.", time: { created: 1 } }, @@ -681,7 +769,10 @@ test("scrolls the timeline behind the composer region, fading at the card, and k const dock = region.getBoundingClientRect() const card = region.querySelector('[data-component="composer"]')!.getBoundingClientRect() const pill = region.querySelector('[data-slot="session-activity-chip"]')!.getBoundingClientRect() - const hint = viewport.querySelector('[data-component="session-background-hint-row"]')!.getBoundingClientRect() + const row = viewport.querySelector('[data-component="session-background-hint-row"]')! + const hint = row.getBoundingClientRect() + // The live status lane that holds Working and the background hint. + const lane = row.parentElement!.getBoundingClientRect() const parts = [...viewport.querySelectorAll("[data-timeline-part-id]")] const last = parts.find((element) => element.textContent?.includes("The last answer ends"))! @@ -695,13 +786,25 @@ test("scrolls the timeline behind the composer region, fading at the card, and k ), // The pill floats above the region out of flow, so it never changes the inset the timeline scrolls above. floats: pill.bottom <= dock.top, - // It floats in the timeline's reserved tail, below the background hint and the last answer. - reserved: hint.bottom <= pill.top && last.getBoundingClientRect().bottom <= hint.top, + pill: Math.round(pill.height), + // It floats in the timeline's reserved tail, a clear gap below the live status lane and the last answer. + clearance: Math.round(pill.top - lane.bottom), + reserved: lane.top <= hint.top && last.getBoundingClientRect().bottom <= hint.top, atEnd: viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop <= 1, } }) - const expected = { behind: 0, inset: 0, fade: 0, floats: true, reserved: true, atEnd: true } + const expected = { + behind: 0, + inset: 0, + fade: 0, + floats: true, + pill: input.pill, + clearance: 14, + reserved: true, + atEnd: true, + } + await expect.poll(geometry).toEqual(expected) const before = (await dock.boundingBox())!.height @@ -715,7 +818,7 @@ test("scrolls the timeline behind the composer region, fading at the card, and k await expect.poll(async () => (await dock.boundingBox())!.height).toBeGreaterThan(before + 40) await expect.poll(geometry).toEqual(expected) -}) +} test("groups consecutive sent prompts under the last one's meta line, with each bubble's actions beside it", async ({ page, diff --git a/packages/app/e2e/regression/timeline-history.spec.ts b/packages/app/e2e/regression/timeline-history.spec.ts index 273176e61826..8beb71693d0d 100644 --- a/packages/app/e2e/regression/timeline-history.spec.ts +++ b/packages/app/e2e/regression/timeline-history.spec.ts @@ -8,11 +8,12 @@ import { historyMessages, messageUpdated, partUpdated, + session, sessionID, setupTimeline, status, - stepStarted, textPart, + userID, userMessage, validateTimelineMessages, } from "../utils/timeline" @@ -22,221 +23,6 @@ import { openSession } from "../utils/workspace" test.use({ serviceWorkers: "block" }) test.describe("timeline history", () => { - test("reopens at the first locally unseen reply", async ({ page }) => { - const notice = await openUnreadSession(page) - - await expect(notice.getByText("New", { exact: true })).toBeInViewport() - await expect(page.getByText("New paragraph 0.", { exact: true })).toBeInViewport() - }) - - test("reopens at the end when the new-messages divider is disabled", async ({ page }) => { - const notice = await openUnreadSession(page, { disabled: true }) - - await expect(page.getByText("New paragraph 59.", { exact: true })).toBeInViewport() - await expect(notice).toHaveCount(0) - }) - - test("reaching the end dismisses the new-messages divider without moving the reply", async ({ page }) => { - const notice = await openUnreadSession(page, { paragraphs: 5 }) - - const paragraph = page.getByText("New paragraph 4.", { exact: true }) - - await expect(notice.getByText("New", { exact: true })).toBeInViewport() - await timelineScroller(page).evaluate((element) => { - element.scrollTop = element.scrollHeight - }) - await expect(paragraph).toBeInViewport() - await expect(notice.getByText("New", { exact: true })).toBeInViewport() - const top = await paragraph.evaluate((element) => element.getBoundingClientRect().top) - - await timelineScroller(page).dispatchEvent("wheel", { deltaY: 1 }) - await expect(notice.getByText("New", { exact: true })).toBeHidden() - await expect.poll(() => paragraph.evaluate((element) => element.getBoundingClientRect().top)).toBeCloseTo(top, 0) - }) - - test("returning to a cached session lands on work streamed while another tab was open", async ({ page }) => { - const other = "ses_new_other" - - let history = [userMessage(), assistantMessage([textPart("prt_cached_seen", "Read before switching")])] - - const workspace = await openSession(page, { - name: "NewMessagesCached", - sessions: [{ id: sessionID }, { id: other, directory: "C:/OpenCode/UnreadOther" }], - pageMessages: (id) => ({ - items: id === other ? [userMessage([textPart("prt_other", "Other session")])] : history, - }), - }) - - await expect(page.getByText("Read before switching", { exact: true })).toBeVisible() - await page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(other)}"]`).click() - await expect(page.getByText("Other session", { exact: true })).toBeVisible() - - const text = textPart( - "prt_cached_reply", - Array.from({ length: 40 }, (_, index) => `Cached reply ${index}.`).join("\n\n"), - ) - - const reply = assistantMessage([], { id: "msg_cached_new_reply", completed: false, created: 1700000002000 }) - - history = [ - ...history, - { ...reply, content: [{ type: "text", text: text.text }], time: { ...reply.time, completed: 1700000003000 } }, - ] - - await workspace.push([ - status("busy"), - stepStarted(reply), - ...partUpdated({ - ...text, - messageID: reply.id, - }), - messageUpdated(reply), - status("idle"), - status("busy", 1, other), - ]) - const tab = page.locator(`[data-slot="titlebar-tabs"] a[href="${sessionHref(sessionID)}"]`) - - // Wait for the stream to reach the active session before switching back. - await expect(page.getByRole("button", { name: "Stop", exact: true })).toBeVisible() - await tab.click() - await expect( - page.locator('[data-slot="session-timeline-notice"]').getByText("New", { exact: true }), - ).toBeInViewport() - await expect(page.getByText("Cached reply 0.", { exact: true })).toBeInViewport() - await page.getByRole("button", { name: "Jump to latest" }).click() - await expect(page.getByText("Cached reply 39.", { exact: true })).toBeInViewport() - await expect(page.locator('[data-timeline-row="NewMessages"]')).toHaveCount(0) - }) - - test("marks new work above an undelivered steer", async ({ page }) => { - const id = "ses_unread_steer" - - let messages = [ - userMessage([textPart("prt_unread_prompt", "Read the code")], { id: "msg_1000_unread_prompt", created: 1 }), - assistantMessage([textPart("prt_unread_seen", "Read work")], { - id: "msg_1001_unread_work", - parentID: "msg_1000_unread_prompt", - created: 2, - completed: false, - }), - ] - - await openSession(page, { - name: "UnreadSteer", - sessions: [{ id }], - sessionStatus: { [id]: { type: "busy" } }, - pageMessages: () => ({ items: messages }), - inbox: [ - { - id: "msg_1002_unread_steer", - sessionID: id, - type: "user", - delivery: "steer", - payload: { text: "Waiting prompt" }, - time: { created: 3 }, - }, - ], - }) - await expect( - page.locator('[data-timeline-row="UserMessage"]').getByText("Waiting prompt", { exact: true }), - ).toBeVisible() - await expect(page.getByText("Read work", { exact: true })).toBeVisible() - await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") - messages = [ - messages[0], - assistantMessage( - [ - textPart("prt_unread_seen", "Read work"), - textPart("prt_unread_new", Array.from({ length: 60 }, (_, index) => `Unseen work ${index}.`).join("\n\n")), - ], - { id: "msg_1001_unread_work", parentID: "msg_1000_unread_prompt", created: 2, completed: false }, - ), - ] - await page.reload() - await expect(page.locator('[data-timeline-row="NewMessages"]').getByText("New", { exact: true })).toBeInViewport() - await expect(page.getByText("Unseen work 0.", { exact: true })).toBeInViewport() - }) - - test("lands at the true unread boundary when older unread history loads", async ({ page }) => { - const id = "ses_unread_pages" - - let messages: SessionMessageInfo[] = [ - userMessage([textPart("prt_unread_pages_prompt", "Keep working")], { id: "msg_0000_unread_pages", created: 1 }), - assistantMessage([textPart("prt_unread_pages_seen", "Read before leaving")], { - id: "msg_0001_unread_pages", - parentID: "msg_0000_unread_pages", - created: 2, - }), - ] - - await openSession(page, { - name: "UnreadPages", - sessions: [{ id }], - pageMessages: (_id, _limit, before) => { - const end = before ? Number(before) : messages.length - - const start = Math.max(0, end - 20) - - return { items: messages.slice(start, end), cursor: start ? String(start) : undefined } - }, - }) - await expect(page.getByText("Read before leaving", { exact: true })).toBeVisible() - await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") - // The unread span exceeds the initial page and three enrichment pages. - messages = [ - ...messages, - ...Array.from({ length: 90 }, (_, index) => - assistantMessage([textPart(`prt_unread_page_${index}`, `Unread response ${index}`)], { - id: `msg_${String(index + 2).padStart(4, "0")}_unread_pages`, - parentID: "msg_0000_unread_pages", - created: index + 3, - }), - ), - ] - await page.reload() - const notice = page.locator('[data-timeline-key="new-messages:msg_0002_unread_pages:text:0"]') - - await expect(notice).toBeInViewport() - await expect(page.getByText("Unread response 0", { exact: true })).toBeInViewport() - }) - - test("keeps unread replies before a prompt sent from another client", async ({ page }) => { - const id = "ses_unread_remote" - - let messages = [ - userMessage([textPart("prt_remote_prompt", "Start working")], { id: "msg_remote_0", created: 1 }), - assistantMessage([textPart("prt_remote_seen", "Already read")], { id: "msg_remote_1", created: 2 }), - ] - - const view = await openSession(page, { - name: "UnreadRemote", - sessions: [{ id }], - pageMessages: () => ({ items: messages }), - }) - - await expect(page.getByText("Already read", { exact: true })).toBeVisible() - await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") - messages = [ - ...messages, - assistantMessage([textPart("prt_remote_unread", "Unread before the other client's prompt")], { - id: "msg_remote_2", - created: 3, - }), - userMessage([textPart("prt_remote_other", "Sent from another client")], { id: "msg_remote_3", created: 4 }), - assistantMessage( - [textPart("prt_remote_reply", Array.from({ length: 40 }, (_, index) => `Remote reply ${index}.`).join("\n\n"))], - { id: "msg_remote_4", created: 5 }, - ), - ] - await page.reload() - await expect(page.locator('[data-timeline-key="new-messages:msg_remote_2:text:0"]')).toBeInViewport() - await expect(page.getByText("Unread before the other client's prompt", { exact: true })).toBeInViewport() - await view.editor.fill("Continue from this client") - await view.editor.press("Enter") - await expect(page.getByText("Remote reply 39.", { exact: true })).toBeInViewport() - await expect(page.locator('[data-timeline-row="NewMessages"]')).toHaveCount(0) - }) - test("restoring a paged transcript waits for another upward scroll before loading history", async ({ page }) => { const id = "ses_history_restore" const other = "ses_history_other" @@ -718,6 +504,81 @@ test.describe("timeline history", () => { await expect(editor).toBeFocused() await expect(editor).toHaveText("keep this draft") }) + + test("a message hash and message navigation keep the prompt in view and the hash in step", async ({ page }) => { + const messages = validateTimelineMessages([ + ...historyMessages(20), + userMessage(), + assistantMessage([textPart("prt_cursor_tail", "Latest answer")]), + ]) + + const prompt = (index: number) => messages.filter((message) => message.type === "user")[index]!.id + const row = (index: number) => page.locator(`[data-timeline-row="UserMessage"][data-message-id="${prompt(index)}"]`) + const hash = () => page.evaluate(() => location.hash) + + await setupTimeline(page, { sessionMessages: messages }) + await expect(page.getByText("Latest answer", { exact: true })).toBeInViewport() + await page.evaluate((id) => (location.hash = `#message-${id}`), prompt(10)) + await expect(row(10)).toBeInViewport() + + await page.keyboard.press("Control+Alt+BracketLeft") + await expect.poll(hash).toBe(`#message-${prompt(9)}`) + await expect(row(9)).toBeInViewport() + await page.keyboard.press("Control+Alt+BracketRight") + await expect.poll(hash).toBe(`#message-${prompt(10)}`) + await expect(row(10)).toBeInViewport() + + await page.getByRole("button", { name: "Jump to latest" }).click() + await expect.poll(hash).toBe("") + const latest = page.getByText("Latest answer", { exact: true }) + await expect(latest).toBeInViewport() + + // Browser Back off a page anchor returns to the latest message, as Back off a prompt does. + await page.evaluate(() => (location.hash = "#notes")) + await expect.poll(hash).toBe("#notes") + await timelineScroller(page).hover() + await page.mouse.wheel(0, -5_000) + await expect(latest).not.toBeInViewport() + await page.evaluate(() => history.back()) + await expect.poll(hash).toBe("") + await expect(latest).toBeInViewport() + }) + + test("a hash for a prompt the revert hides, or one that does not exist, clears without paging history", async ({ + page, + }) => { + const messages = validateTimelineMessages([ + ...historyMessages(30), + userMessage(), + assistantMessage([textPart("prt_hash_missing_tail", "Reverted answer")]), + ]) + + const older: string[] = [] + const hash = () => page.evaluate(() => location.hash) + + await setupTimeline(page, { + sessions: [session({ revert: { messageID: userID } })], + message: (_, id) => messages.find((message) => message.id === id), + pageMessages: (_, limit, before) => { + const end = before ? messages.findIndex((message) => message.id === before) : messages.length + const start = Math.max(0, end - limit) + + return { items: messages.slice(start, end), cursor: start > 0 ? messages[start]!.id : undefined } + }, + onMessages: (request) => { + if (request.before && request.phase === "start") older.push(request.before) + }, + }) + await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + const loaded = [...older] + + // The revert hides this prompt, and older pages hold only older messages, so neither link can ever load. + await page.evaluate((id) => (location.hash = `#message-${id}`), userID) + await expect.poll(hash).toBe("") + await page.evaluate(() => (location.hash = "#message-msg_9999_missing")) + await expect.poll(hash).toBe("") + expect(older).toEqual(loaded) + }) }) declare global { @@ -726,40 +587,6 @@ declare global { } } -async function openUnreadSession(page: Page, input: { disabled?: boolean; paragraphs?: number } = {}) { - const id = "ses_new_messages" - - let messages = [ - userMessage([textPart("prt_new_prompt", "Explain the implementation")], { id: "msg_new_prompt", created: 1 }), - assistantMessage([textPart("prt_seen", "Already read")], { id: "msg_seen", created: 2 }), - ] - - await openSession(page, { - name: "NewMessages", - sessions: [{ id }], - pageMessages: () => ({ items: messages }), - seed: input.disabled ? { settings: { general: { newMessagesDivider: false } } } : undefined, - }) - await expect(page.getByText("Already read", { exact: true })).toBeVisible() - await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") - messages = [ - ...messages, - assistantMessage( - [ - textPart( - "prt_new_reply", - Array.from({ length: input.paragraphs ?? 60 }, (_, index) => `New paragraph ${index}.`).join("\n\n"), - ), - ], - { id: "msg_new_reply", created: 3 }, - ), - ] - await page.reload() - await expectSessionTitle(page, id) - - return page.locator('[data-timeline-row="NewMessages"]') -} - async function openStressTarget(page: Page, input: Parameters[1] = {}) { await mockStressTimeline(page, input) await installTimelineSettings(page) diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 1fc26e260970..64430108b6ac 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -1155,7 +1155,9 @@ test.describe("background shortcut", () => { const capsule = page.getByRole("button", { name: "1 shell", exact: true, includeHidden: true }) const list = page.getByRole("menu", { name: "1 shell", exact: true }) const closed = (await capsule.boundingBox())! - const inset = (await capsule.locator('[data-component="session-progress-indicator-v2"]').boundingBox())!.x - closed.x + + const inset = + (await capsule.locator('[data-component="session-progress-indicator-v2"]').boundingBox())!.x - closed.x await capsule.click() // Right placement shares the capsule's end edge and mirrors its inset there; centre placement shares its centre. @@ -1400,13 +1402,23 @@ test.describe("background shortcut", () => { await interrupt await expect(list).toBeVisible() - const kill = page.waitForRequest( - (request) => request.method() === "DELETE" && new URL(request.url()).pathname === "/api/shell/shell_backgrounded", - ) + const kill = await holdRoute(page, /\/api\/shell\/shell_backgrounded(\?|$)/, { method: "DELETE" }) + const shellRow = list.getByRole("menuitem", { name: /sleep 120/ }) - await list.getByRole("menuitem", { name: /sleep 120/ }).hover() + await shellRow.hover() + await page.keyboard.press("Delete") + await kill.arrived + // A second Delete, or a click on the row's stop button, while the first stop runs sends nothing more. + const stopping = shellRow.getByRole("button", { name: "Kill shell command", exact: true }) + await expect(stopping).toHaveAttribute("aria-busy", "true") await page.keyboard.press("Delete") - await kill + // aria-disabled leaves a real click through, which Playwright's actionability check would refuse. + await stopping.click({ force: true }) + await expect(stopping).toHaveAttribute("aria-busy", "true") + expect(kill.requests).toHaveLength(1) + kill.release() + await expect(stopping).not.toHaveAttribute("aria-busy") + expect(kill.requests).toHaveLength(1) await page.keyboard.press("Escape") await expect(list).toHaveCount(0) await expect(backgroundCard).toContainText("Background task (background)") @@ -2208,6 +2220,44 @@ test("a pending quote send hides mentions and keeps the comment read-only", asyn await expect.poll(() => sent).toEqual(["queue"]) }) +test("a double-clicked quote send sends once and keeps the popup open until it settles", async ({ page }) => { + const sent: string[] = [] + + await setupTimeline(page, { + messages: [userMessage(), assistantMessage([textPart("prt_quote_double", "Keep this quoted passage.")])], + onPrompt: (input) => void sent.push(String(input.body.delivery)), + }) + + const answer = page.locator( + `[data-timeline-part-id="${renderedPartID("prt_quote_double")}"] [data-slot="text-part-body"]`, + ) + + await expect(answer).toHaveText("Keep this quoted passage.") + await selectQuoteText(answer) + await page + .getByRole("toolbar", { name: "Quote selection" }) + .getByRole("button", { name: "Quote", exact: true }) + .click() + const popup = page.locator('[data-component="composer-quote-comment"]') + + const chip = page.locator('[data-component="composer-attachments"] [data-component="attachment-card"]') + + const modifier = await page.evaluate(() => (/(Mac|iPod|iPhone|iPad)/.test(navigator.platform) ? "Meta" : "Control")) + + await popup.locator("textarea").fill("Only once") + const admission = await holdRoute(page, new RegExp(`/api/session/${sessionID}/prompt(\\?|$)`), { method: "POST" }) + + await popup.locator('[data-slot="line-comment-v2-submit"]').dblclick({ modifiers: [modifier] }) + await admission.arrived + // A click on the quote's chip while the send is in flight leaves the popup and its pending send alone. + await chip.click() + await expect(popup.locator('[data-component="loader-v2"]')).toBeVisible() + admission.release() + await expect(popup).toHaveCount(0) + await expect.poll(() => sent.length).toBe(1) + expect(admission.requests).toHaveLength(1) +}) + function selectQuoteText(target: Locator) { return target.evaluate((element) => { const range = document.createRange() @@ -3317,6 +3367,16 @@ test("reaches the quote action from the keyboard and blocks a selection over the await expect(more).not.toBeFocused() expect(await page.evaluate(() => !!document.activeElement?.closest('[data-component="timeline-quote"]'))).toBe(false) await expect(composer).toHaveCount(1) + + // A press that turns into a native drag of the selection ends with dragend, and no pointerup follows. + await page.evaluate(() => window.getSelection()?.removeAllRanges()) + await expect(toolbar).toHaveCount(0) + await short.hover() + await page.mouse.down() + await page.evaluate(() => document.dispatchEvent(new Event("dragend"))) + await short.evaluate((element) => window.getSelection()?.selectAllChildren(element)) + await expect(toolbar).toBeVisible() + await page.mouse.up() }) function pauseExitAnimations(locator: Locator) { diff --git a/packages/app/e2e/service-worker/cache.spec.ts b/packages/app/e2e/service-worker/cache.spec.ts index 2877b6730d41..143fb11f1ac3 100644 --- a/packages/app/e2e/service-worker/cache.spec.ts +++ b/packages/app/e2e/service-worker/cache.spec.ts @@ -10,6 +10,11 @@ import { fileURLToPath } from "node:url" import { build } from "vite" import { onDemandAsset, serviceWorker } from "../../vite.pwa" +// The updater the web app ships (Settings › Updates and the titlebar), built into the fixture pages. +const updaterDriver = fileURLToPath( + new URL("../../../gui-plugins/src/updater/web-driver.ts", import.meta.url), +).replaceAll("\\", "/") + type Site = { url: string deploy: (fault?: "failed" | "html" | "corrupt" | "mixed-html" | "blocked") => void @@ -35,7 +40,20 @@ const fixture = test.extend<{ site: Site }, { builds: Record { document.querySelector("output").textContent = await (await import("./lazy.js")).load() - };`, + }; + // ?updater runs the web app's real update driver, with its actions as buttons. + if (location.search.includes("updater")) import(${JSON.stringify(updaterDriver)}).then(({ startWebUpdater }) => { + const state = Object.assign(document.createElement("p"), { ariaLabel: "Update state" }); + const announced = Object.assign(document.createElement("p"), { ariaLabel: "Update offered" }); + const updater = startWebUpdater({ + changed: (next) => (state.textContent = next.status), + announce: () => (announced.textContent = "yes"), + report: () => {}, + }); + state.textContent = updater.state().status; + const action = (name, run) => Object.assign(document.createElement("button"), { textContent: name, onclick: run }); + document.body.append(state, announced, action("Check for updates", updater.check), action("Update now", updater.apply), action("Reload from server", updater.reset)); + });`, "lazy.js": `export async function load() { return (await import("./nested.js")).value }`, "nested.js": `export const value = "${version} nested lazy loaded"`, "public/nested/data.json": JSON.stringify({ version }), @@ -286,7 +304,9 @@ fixture( replacement.evaluate(() => { // This runs in the service worker, whose global scope holds its registration. const registration = - "registration" in self && self.registration instanceof ServiceWorkerRegistration ? self.registration : undefined + "registration" in self && self.registration instanceof ServiceWorkerRegistration + ? self.registration + : undefined return { waiting: !!registration?.waiting, active: registration?.active?.state } }), @@ -301,6 +321,63 @@ fixture( }, ) +fixture( + "the updater offers a new build and moves every open tab to it with one click", + async ({ page, context, site }) => { + await install(page, `${site.url}/?updater`) + await expect(page.getByLabel("Update state")).toHaveText("idle") + const second = await context.newPage() + await second.goto(`${site.url}/?updater`) + await expect(second.getByLabel("Update state")).toHaveText("idle") + + site.deploy() + await page.getByRole("button", { name: "Check for updates" }).click() + await expect(page.getByLabel("Update state")).toHaveText("ready") + await expect(page.getByLabel("Update offered")).toHaveText("yes") + // Every tab hears about the download, not only the one that checked. + await expect(second.getByLabel("Update state")).toHaveText("ready") + // A tab opened while the build waits offers it at once; before, it waited for every tab to close. + const third = await context.newPage() + await third.goto(`${site.url}/?updater`) + await expect(third.getByRole("heading")).toHaveText("old") + await expect(third.getByLabel("Update state")).toHaveText("ready") + + await second.getByRole("button", { name: "Update now" }).click() + + for (const tab of [page, second, third]) { + await expect(tab.getByRole("heading")).toHaveText("new") + await expect(tab.getByLabel("Update state")).toHaveText("idle") + } + + await page.getByRole("button", { name: "Load lazy" }).click() + await expect(page.getByRole("status")).toHaveText("new nested lazy loaded") + }, +) + +fixture( + "reload from server replaces a saved build that cannot update, in every open tab", + async ({ page, context, site }) => { + await install(page, `${site.url}/?updater`) + const second = await context.newPage() + await second.goto(`${site.url}/?updater`) + await expect(second.getByLabel("Update state")).toHaveText("idle") + site.deploy("failed") + await page.getByRole("button", { name: "Check for updates" }).click() + await expect(page.getByLabel("Update state")).toHaveText("error") + await page.reload() + await expect(page.getByRole("heading")).toHaveText("old") + + await page.getByRole("button", { name: "Reload from server" }).click() + await expect(page.getByRole("heading")).toHaveText("new") + expect(await page.evaluate(() => navigator.serviceWorker.controller)).toBeNull() + expect(await page.evaluate(async () => (await caches.keys()).length)).toBe(0) + // The other tab's old lazy chunks went with the caches, so it reloads too instead of failing its next import. + await expect(second.getByRole("heading")).toHaveText("new") + await second.getByRole("button", { name: "Load lazy" }).click() + await expect(second.getByRole("status")).toHaveText("new nested lazy loaded") + }, +) + for (const fault of ["failed", "html", "corrupt", "mixed-html"] as const) { fixture(`retains the old complete build when a precache download is ${fault}`, async ({ page, context, site }) => { await install(page, site.url) diff --git a/packages/app/e2e/user-story/model-selection-flow.spec.ts b/packages/app/e2e/user-story/model-selection-flow.spec.ts index f244db683a78..1a4b3322a6ee 100644 --- a/packages/app/e2e/user-story/model-selection-flow.spec.ts +++ b/packages/app/e2e/user-story/model-selection-flow.spec.ts @@ -165,3 +165,50 @@ test("restores each existing session's model and variant when switching tabs", a await expect(modelControl).toHaveText("Model A") await expect(variant).toHaveText("high") }) + +test("keeps a variant picked in another directory's session with that session across a reload", async ({ page }) => { + // The session view stays mounted while its tabs switch between sessions in different directories. + const sessions = [ + { name: "Home", directory: "C:/OpenCode/ModelHome" }, + { name: "Away", directory: "C:/OpenCode/ModelAway" }, + ].map((item) => ({ + id: `ses_model_${item.name.toLowerCase()}`, + title: `${item.name} session`, + directory: item.directory, + model: { id: `model-${item.name.toLowerCase()}`, providerID: "opencode", variant: "balanced" }, + })) + + await openSession(page, { + name: "ModelHome", + sessions, + provider: provider( + ...sessions.map((session) => ({ + id: session.model.id, + name: session.title, + variants: { balanced: {}, high: {} }, + })), + ), + }) + + const [home, away] = sessions.map((session) => sessionHref(session.id)) + const composer = page.locator('[data-component="composer"]') + const modelControl = composer.locator('[data-action="composer-model"]') + const variant = composer.getByRole("button", { name: "Choose model variant", exact: true }) + await expect(modelControl).toHaveText("Home session") + await page.locator(`[data-titlebar-tab-link][href="${away}"]`).click() + await expect(page).toHaveURL(away!) + await expect(modelControl).toHaveText("Away session") + await expect(variant).toHaveText("balanced") + await variant.click() + await page.getByRole("menuitemradio", { name: "high", exact: true }).click() + await expect(variant).toHaveText("high") + + await page.reload() + await expect(modelControl).toHaveText("Away session") + await expect(variant).toHaveText("high") + + await page.locator(`[data-titlebar-tab-link][href="${home}"]`).click() + await expect(page).toHaveURL(home!) + await expect(modelControl).toHaveText("Home session") + await expect(variant).toHaveText("balanced") +}) diff --git a/packages/app/e2e/utils/mock-api.ts b/packages/app/e2e/utils/mock-api.ts index f9784c872fa7..4d59be07c4b0 100644 --- a/packages/app/e2e/utils/mock-api.ts +++ b/packages/app/e2e/utils/mock-api.ts @@ -39,6 +39,7 @@ const Query = Schema.Struct({ query: Schema.optional(Schema.String), type: Schema.optional(Schema.String), mode: Schema.optional(Schema.String), + context: Schema.optional(Schema.String), }) const SessionParams = { sessionID: Schema.String } @@ -149,6 +150,31 @@ const Group = HttpApiGroup.make("mock") error: MockNotFound.pipe(HttpApiSchema.status(404)), }), ) + .add( + HttpApiEndpoint.post( + "integrationOAuthComplete", + "/api/integration/:integrationID/connect/oauth/:attemptID/complete", + { + params: { integrationID: Schema.String, attemptID: Schema.String }, + payload: JsonPayload, + success: NoContent, + error: Unsupported, + }, + ), + ) + .add( + HttpApiEndpoint.delete("integrationOAuthCancel", "/api/integration/:integrationID/connect/oauth/:attemptID", { + params: { integrationID: Schema.String, attemptID: Schema.String }, + success: NoContent, + }), + ) + .add( + HttpApiEndpoint.post("integrationConnectExternal", "/api/integration/:integrationID/connect/external", { + params: { integrationID: Schema.String }, + payload: JsonPayload, + success: NoContent, + }), + ) .add( HttpApiEndpoint.post("credentialActivate", "/api/credential/:credentialID/activate", { params: { credentialID: Schema.String }, @@ -186,7 +212,12 @@ const Group = HttpApiGroup.make("mock") error: MockNotFound.pipe(HttpApiSchema.status(404)), }), ) - .add(HttpApiEndpoint.get("mcpResource", "/api/mcp/resource", { success: Json })) + .add( + HttpApiEndpoint.get("mcpResource", "/api/mcp/resource", { + success: Json, + error: MockInternal.pipe(HttpApiSchema.status(500)), + }), + ) .add(HttpApiEndpoint.get("projectList", "/api/project", { success: Json })) .add( HttpApiEndpoint.patch("projectUpdate", "/api/project/:projectID", { @@ -417,6 +448,13 @@ const Group = HttpApiGroup.make("mock") success: Json, }), ) + .add( + HttpApiEndpoint.post("sessionFork", "/api/session/:sessionID/fork", { + params: SessionParams, + payload: JsonPayload, + success: Json, + }), + ) .add( HttpApiEndpoint.post("sessionCommand", "/api/session/:sessionID/command", { params: SessionParams, diff --git a/packages/app/e2e/utils/mock-server.ts b/packages/app/e2e/utils/mock-server.ts index 3d8dae416028..85d8b522c5de 100644 --- a/packages/app/e2e/utils/mock-server.ts +++ b/packages/app/e2e/utils/mock-server.ts @@ -90,8 +90,11 @@ export interface MockServerConfig { branches?: (input: { directory: string; search?: string; limit?: number }) => string[] | Promise // Initializes the mock project's VCS; without a handler this mutation answers 501. onVcsInit?: (input: { directory: string; provider?: string }) => void - vcsDiff?: unknown[] | ((input: { mode?: string }) => unknown[]) + // `directory` is the requested `location[directory]`, such as an untracked folder the review opened. + /** `context` is the patch's lines of context, sent when the review asks for a large file's full patch. */ + vcsDiff?: unknown[] | ((input: { mode?: string; directory: string; context?: string }) => unknown[]) beforeMessagesResponse?: (input: { sessionID: string; before?: string }) => Promise + beforeAgentsResponse?: () => Promise onMessages?: (input: { sessionID: string; before?: string; phase: "start" | "end" }) => void message?: (sessionID: string, messageID: string) => SessionMessageInfo | undefined onMessage?: (input: { sessionID: string; messageID: string }) => void @@ -109,6 +112,10 @@ export interface MockServerConfig { // Without it, permission replies answer 501 MockUnsupported. onPermissionReply?: (input: { sessionID: string; permissionID: string; body: unknown }) => void forms?: unknown[] | (() => unknown[]) + // Records form replies. The mock keeps listing a replied form unless `forms` stops returning it. + onFormReply?: (input: { sessionID: string; formID: string; body: unknown }) => void + // Web search providers (`GET /api/websearch/provider`), none by default. + websearchProviders?: Resolvable // MCP servers. A list serves every workspace; a function receives the requested directory. mcp?: unknown[] | ((directory: string) => unknown[]) // Connect/disconnect record the server's new status in that workspace (`connected`/`disabled`); the hook may return @@ -116,9 +123,19 @@ export interface MockServerConfig { onMcpAction?: (input: { server: string; action: "connect" | "disconnect"; directory: string }) => void | MockMcpStatus // Starts an OAuth attempt (POST .../connect/oauth) and returns its authorization URL; the attempt then stays pending. // Without it, OAuth connects answer 501 MockUnsupported. - onIntegrationOAuth?: (input: { integrationID: string; directory: string; body: unknown }) => { url: string } + // `paste` starts a sign-in that also accepts the redirect URL pasted from the browser. + onIntegrationOAuth?: (input: { integrationID: string; directory: string; body: unknown }) => { + url: string + paste?: boolean + } // Answers status polls for an OAuth attempt; without it every attempt stays pending. onIntegrationOAuthStatus?: (attemptID: string) => "pending" | "complete" + // Accepts a pasted redirect URL (POST .../connect/oauth/:attemptID/complete). Without it, pastes answer 501. + onIntegrationOAuthComplete?: (input: { attemptID: string; body: unknown }) => void + // Returning true fails the next `/api/mcp/resource` listing with a 500. + mcpResourceFailures?: () => boolean + // Runs on DELETE .../connect/oauth/:attemptID, which closes an OAuth attempt the dialog left. + onIntegrationOAuthCancel?: (attemptID: string) => void plugins?: Resolvable skills?: Resolvable // Replaces the `/api/worktree` inventory, which defaults to the directory plus project sandboxes. @@ -127,8 +144,9 @@ export interface MockServerConfig { // and return the answer; by default it creates `/`. A created directory joins the project's sandboxes. onWorktreeCreate?: (input: Schema.Json) => void | MockAnswer | Promise onWorktreeRemove?: (input: Worktree.RemoveInput) => void | Promise - // POST /api/session keeps the client-reserved `id` and `location`. Return an answer to fail the attempt (1-based). - onSessionCreate?: (body: Schema.JsonObject, attempt: number) => void | MockAnswer + // POST /api/session keeps the client-reserved `id` and `location`. Return an answer to fail the attempt (1-based); the + // hook may hold the request. + onSessionCreate?: (body: Schema.JsonObject, attempt: number) => void | MockAnswer | Promise // Title of created sessions (default: the request's title, else "New session"). createdSessionTitle?: string // Slash commands served by `/api/command`. @@ -143,6 +161,9 @@ export interface MockServerConfig { inbox?: unknown[] | (() => unknown[]) onPrompt?: (input: { sessionID: string; body: Schema.JsonObject }) => void onCompact?: (input: { sessionID: string; body: Schema.JsonObject }) => void + // POST /api/session/:id/fork creates `_fork` in the same directory. The hook may hold the request, or return an + // answer to replace the response. + onFork?: (input: { sessionID: string; body: Schema.JsonObject }) => void | MockAnswer | Promise generate?: (input: { sessionID: string; prompt: string }) => { text: string } | Promise<{ text: string }> onInboxChange?: (input: { sessionID: string; inboxID: string; action: "cancel" | "steer" | "queue" }) => void onBackground?: (input: { sessionID: string }) => void @@ -711,7 +732,8 @@ function mockHandlers( const payload = Option.getOrElse(decodeJsonObject(input), () => ({})) const fields = Option.getOrUndefined(decodeSessionCreate(payload)) state.sessionCreates += 1 - const answer = config.onSessionCreate?.(payload, state.sessionCreates) + const attempt = state.sessionCreates + const answer = yield* Effect.promise(async () => config.onSessionCreate?.(payload, attempt)) if (answer) return HttpServerResponse.jsonUnsafe(answer.body, { status: answer.status }) @@ -731,6 +753,27 @@ function mockHandlers( return HttpServerResponse.jsonUnsafe({ data: created }) }), ) + .handleRaw("sessionFork", (ctx) => + Effect.gen(function* () { + const input = yield* Effect.orDie(ctx.request.json) + const body = Option.getOrElse(decodeJsonObject(input), (): Schema.JsonObject => ({})) + const answer = yield* Effect.promise(async () => config.onFork?.({ sessionID: ctx.params.sessionID, body })) + + if (answer) return HttpServerResponse.jsonUnsafe(answer.body, { status: answer.status }) + + const parent = config.sessions.find((item) => item.id === ctx.params.sessionID) + const id = `${ctx.params.sessionID}_fork` + + const forked = currentSession( + { ...parent, id, title: `${parent?.title ?? ctx.params.sessionID} (fork)` }, + config.directory, + ) + + if (!config.sessions.some((item) => item.id === id)) config.sessions.push(forked) + + return HttpServerResponse.jsonUnsafe({ data: forked }) + }), + ) .handleAll({ info: () => Effect.succeed({ @@ -746,20 +789,23 @@ function mockHandlers( }), config: () => Effect.succeed(configEntries), reference: () => Effect.succeed({ location: location(config), data: [] }), + // `beforeAgentsResponse` holds the Location's agent list, as a cold Location does while its plugins activate. agent: (ctx) => - Effect.succeed({ - location: location(config, requestDirectory(config, ctx.request)), - data: [ - { - id: "build", - name: "Build", - mode: "primary", - hidden: false, - request: { settings: {}, headers: {}, body: {} }, - permissions: [], - }, - ], - }), + Effect.promise(async () => config.beforeAgentsResponse?.()).pipe( + Effect.as({ + location: location(config, requestDirectory(config, ctx.request)), + data: [ + { + id: "build", + name: "Build", + mode: "primary", + hidden: false, + request: { settings: {}, headers: {}, body: {} }, + permissions: [], + }, + ], + }), + ), provider: () => Effect.succeed({ location: location(config), data: currentProviders(resolve(config.provider)) }), model: () => Effect.succeed({ location: location(config), data: currentModels(resolve(config.provider)) }), @@ -799,16 +845,15 @@ function mockHandlers( state.attempts.set(attemptID, created) const started = start({ integrationID: ctx.params.integrationID, directory, body: ctx.payload }) - return { - location: location(config, directory), - data: { - attemptID, - url: started.url, - instructions: "", - mode: "auto", - time: { created, expires: created + 600_000 }, - }, + const data = { + attemptID, + url: started.url, + instructions: "", + mode: "auto", + time: { created, expires: created + 600_000 }, } + + return { location: location(config, directory), data: started.paste ? { ...data, paste: true } : data } }) }, integrationOAuthStatus: (ctx) => @@ -825,6 +870,18 @@ function mockHandlers( }, }) }), + integrationOAuthComplete: (ctx) => { + const complete = config.onIntegrationOAuthComplete + + if (!complete) return unsupported("complete pasted OAuth sign-ins", "onIntegrationOAuthComplete") + + return Effect.sync(() => complete({ attemptID: ctx.params.attemptID, body: ctx.payload })).pipe( + Effect.andThen(noContent), + ) + }, + integrationOAuthCancel: (ctx) => + Effect.sync(() => config.onIntegrationOAuthCancel?.(ctx.params.attemptID)).pipe(Effect.andThen(noContent)), + integrationConnectExternal: () => noContent, credentialActivate: (ctx) => Effect.sync(() => config.onCredentialActivate?.(ctx.params.credentialID)).pipe(Effect.andThen(noContent)), credentialUpdate: (ctx) => @@ -848,10 +905,14 @@ function mockHandlers( mcpConnect: (ctx) => mcpAction(ctx.params.server, "connect", ctx.request), mcpDisconnect: (ctx) => mcpAction(ctx.params.server, "disconnect", ctx.request), mcpResource: (ctx) => - Effect.succeed({ - location: location(config, requestDirectory(config, ctx.request)), - data: { resources: [], templates: [] }, - }), + Effect.suspend(() => + config.mcpResourceFailures?.() + ? Effect.fail(new MockInternal({ message: "MCP resource list failed" })) + : Effect.succeed({ + location: location(config, requestDirectory(config, ctx.request)), + data: { resources: [], templates: [] }, + }), + ), projectList: () => Effect.sync(() => { if (config.projects) return resolve(config.projects) @@ -868,7 +929,8 @@ function mockHandlers( }), configShells: () => Effect.succeed(config.shells ?? []), configUpdate: () => noContent, - websearchProviders: () => Effect.succeed({ location: location(config), data: [] }), + websearchProviders: () => + Effect.sync(() => ({ location: location(config), data: resolve(config.websearchProviders ?? []) })), // No scenario signs in to an OpenCode Console workspace, so none has usage limits. usageLimits: () => Effect.succeed({ location: location(config), data: null }), worktreeList: () => @@ -964,7 +1026,11 @@ function mockHandlers( Effect.sync(() => ({ location: location(config), data: Predicate.isFunction(config.vcsDiff) - ? config.vcsDiff({ mode: ctx.query.mode }) + ? config.vcsDiff({ + mode: ctx.query.mode, + directory: requestDirectory(config, ctx.request), + context: ctx.query.context, + }) : (config.vcsDiff ?? []), })), fsList: (ctx) => @@ -1159,9 +1225,11 @@ function mockHandlers( ...Object.entries(config.sessionPermissions ?? {}).flatMap(([id, list]) => currentPermissions(list).length > 0 && status[id]?.type !== "idle" ? [id] : [], ), + // Location elicitations (`sessionID: "global"`) belong to no Session. ...resolve(config.forms ?? []).flatMap((form) => Predicate.isObject(form) && Predicate.isString(form.sessionID) && + form.sessionID !== "global" && status[form.sessionID]?.type !== "idle" ? [form.sessionID] : [], @@ -1188,7 +1256,10 @@ function mockHandlers( (form) => Predicate.isObject(form) && form.sessionID === ctx.params.sessionID, ), }), - sessionFormReply: () => noContent, + sessionFormReply: (ctx) => + Effect.sync(() => + config.onFormReply?.({ sessionID: ctx.params.sessionID, formID: ctx.params.formID, body: ctx.payload }), + ).pipe(Effect.andThen(noContent)), sessionFormCancel: () => noContent, sessionBackground: (ctx) => Effect.sync(() => config.onBackground?.({ sessionID: ctx.params.sessionID })).pipe(Effect.andThen(noContent)), diff --git a/packages/app/e2e/utils/settings-wsl.fixture.tsx b/packages/app/e2e/utils/settings-wsl.fixture.tsx index 19c46d57d1b8..fd2491b1066c 100644 --- a/packages/app/e2e/utils/settings-wsl.fixture.tsx +++ b/packages/app/e2e/utils/settings-wsl.fixture.tsx @@ -19,7 +19,7 @@ type FixtureMethod = (input: FixtureInput) => number | void // A desktop window. `wsl` is the Ubuntu server's endpoint (default `server`); updating OpenCode restarts it on `restart` // (default `wsl`). `ssh` adds a saved SSH server `box`, ready on that endpoint with password `ssh-1`; each connect // brings up a new remote server with the next password (`ssh-2`, ...). `storage=async` stores in localStorage behind -// asynchronous reads like the desktop app's; reads of keys containing `hold` wait for "Load held storage". +// asynchronous reads like the desktop app's; reads of keys matching the pattern `hold` wait for "Load held storage". export function mount(input: { server: string mode: "failed" | "stopped" | "ready" @@ -46,7 +46,7 @@ export function mount(input: { return { getItem: async (key: string) => { - if (input.hold && key.includes(input.hold)) await held.promise + if (input.hold && new RegExp(input.hold).test(key)) await held.promise return localStorage.getItem(item(key)) }, @@ -299,6 +299,16 @@ export function mount(input: { > Require SSH sign-in + {/* The remote server answering with a version this app does not support. */} + {store.connects} diff --git a/packages/app/e2e/utils/windows-menu.fixture.tsx b/packages/app/e2e/utils/windows-menu.fixture.tsx index deee98939b6d..3668277aa5af 100644 --- a/packages/app/e2e/utils/windows-menu.fixture.tsx +++ b/packages/app/e2e/utils/windows-menu.fixture.tsx @@ -6,8 +6,9 @@ import { AppBaseProviders, AppInterface } from "../../src/app" import { PlatformProvider, type Platform } from "../../src/runtime/platform/platform" // The app on a Windows desktop platform, so the titlebar shows the app menu. Menu actions are listed in an output. -// `path` opens a route other than Home. -export function mount(input: { server: string; path?: string; os?: "macos"; openApps?: boolean }) { +// `path` opens a route other than Home. `holdOpen` records an opened path but never answers, like an editor that keeps +// the launch running until it exits. +export function mount(input: { server: string; path?: string; os?: "macos"; openApps?: boolean; holdOpen?: boolean }) { const root = document.getElementById("root") if (!root) throw new Error("Missing fixture root") @@ -62,7 +63,12 @@ export function mount(input: { server: string; path?: string; os?: "macos"; open if (input.openApps) { platform.checkAppExists = async (app) => app === "Visual Studio Code" || app === "code" - platform.openPath = async (path, app) => void setStore("opened", (opened) => [...opened, { path, app }]) + platform.openPath = (path, app) => { + setStore("opened", (opened) => [...opened, { path, app }]) + + return input.holdOpen ? new Promise(() => undefined) : Promise.resolve() + } + platform.revealPath = async () => true } diff --git a/packages/app/e2e/utils/windows-menu.html b/packages/app/e2e/utils/windows-menu.html index 5b2cc1d045d9..7acadc0fc990 100644 --- a/packages/app/e2e/utils/windows-menu.html +++ b/packages/app/e2e/utils/windows-menu.html @@ -13,6 +13,7 @@ path: params.get("path") ?? undefined, os: params.get("os") === "macos" ? "macos" : undefined, openApps: params.get("openApps") === "1", + holdOpen: params.get("holdOpen") === "1", }) diff --git a/packages/app/perf/README.md b/packages/app/perf/README.md index 6dd23c2beec4..a9295b22425f 100644 --- a/packages/app/perf/README.md +++ b/packages/app/perf/README.md @@ -5,17 +5,19 @@ launches (A B, B A, …) at normal speed, decides one primary metric per case wi cannot defend (a hidden window, a software GPU, a throttled CPU, a busy machine). The web cases run the production build on the e2e mock server, so they need no backend. -| File | Cases | Workload | -| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -| `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. | -| `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. | -| `tabs.bench.ts` | switch tab (warm, review open, after a resize, 1,200 models) · away and back with review open · open an unvisited tab (± review) | Two tabs of 200 long markdown exchanges each, loaded in full. | -| `navigation.bench.ts` | Home → session · close the last tab · new session (Home, titlebar) · new session page in and out · child session · restore 8 tabs · activate a restored tab · command palette (session, Home) | The stress fixture, paginated, from a fresh document every run. | -| `home.bench.ts` | load home · update a session in the background | 500, 5,000 and 10,000 root sessions across 12 folders. | -| `review.bench.ts` | open review · filter files · next file | 100 and 10,000 changed files of 100 lines each. | -| `diff.bench.ts` | open a long diff · open a huge diff · return to a long diff | A 1,559-line diff, highlighted; a 15,599-line one, plain. | -| `composer.bench.ts` | type in a large draft · move the cursor in it · recall a prompt from history | A 44,000-character saved draft; 100 prompts with screenshots. | -| `desktop.bench.ts` | idle | The packaged desktop app, every process, doing nothing for 5 s. | +| File | Cases | Workload | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | +| `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. | +| `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · with Find open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. | +| `tabs.bench.ts` | switch tab (warm, review open, after a resize, 1,200 models) · away and back with review open · open an unvisited tab (± review) | Two tabs of 200 long markdown exchanges each, loaded in full. | +| `navigation.bench.ts` | Home → session · close the last tab · new session (Home, titlebar) · new session page in and out · child session · restore 8 tabs · activate a restored tab · command palette (session, Home, scroll) | The stress fixture, paginated, from a fresh document every run. | +| `home.bench.ts` | load home · update a session in the background | 500, 5,000 and 10,000 root sessions across 12 folders. | +| `review.bench.ts` | open review · filter files · next file | 100 and 10,000 changed files of 100 lines each. | +| `diff.bench.ts` | open a long diff · open a huge diff · return to a long diff | A 1,559-line diff, highlighted; a 15,599-line one, plain. | +| `composer.bench.ts` | type in a large draft · move the cursor in it · recall a prompt from history | A 44,000-character saved draft; 100 prompts with screenshots. | +| `docks.bench.ts` | open and close request docks | A permission dock and an MCP elicitation over a 20-turn session. | +| `question.bench.ts` | switch questions | The new question dock with its motion on: five questions. | +| `desktop.bench.ts` | idle | The packaged desktop app, every process, doing nothing for 5 s. | Every case decides `main.work` (renderer main-thread task time per run) unless it says otherwise: it is continuous, while durations that end on a presented frame move in whole vsyncs. Durations, interaction latency, frames and the @@ -69,11 +71,22 @@ strobe bench packages/desktop/perf/startup.bench.ts --target desktop --base app: bun packages/core/perf/snapshot.ts medium opencode strobe bench packages/core/perf/snapshot.bench.ts --base origin/dev --head . -# The interactive report, and the tables and rerun command for a pull request body. +# The interactive report, and the results block in pull request (see "In a pull request"). strobe report experiment --open -strobe report experiment --format pr +strobe report experiment --format pr --update-pr ``` +### In a pull request + +Write the PR's own text: what strobe showed that led to the change (the command and recording id), and what the change +does. Then `strobe report experiment --format pr --update-pr ` adds strobe's generated results block to PR +`n`'s body, or replaces that experiment's block after a rerun, and leaves the rest of the body alone. Don't edit inside +the block (strobe refuses to update a hand-edited one); put your reading of the numbers above or below it. Without +`--update-pr`, the block goes to stdout for pasting. + +Every page target expects the `OpenCode` title (`expect`): a block that lands on another page (an error page, a blank +document) is refused `WrongScreen` instead of timed, and the block's `On screen:` line says what each block showed. + `bunx strobe` runs the strobe version pinned in the root catalog (`@hona/strobe`), which ships builds for Windows x64, macOS (arm64, x64) and Linux (x64, arm64); a `strobe` on your PATH also works. Script cases (core, ui) run the same on every OS. Page and desktop cases measure the most on Windows: diff --git a/packages/app/perf/composer.bench.ts b/packages/app/perf/composer.bench.ts index 9a143f6f1a22..ae9a93f5d31d 100644 --- a/packages/app/perf/composer.bench.ts +++ b/packages/app/perf/composer.bench.ts @@ -15,6 +15,7 @@ const typed = " Keep the existing error handling and add coverage." export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1440, height: 900 }, async prepare({ case: name, playwright, mock, url }) { const server = new URL(url).origin diff --git a/packages/app/perf/diff.bench.ts b/packages/app/perf/diff.bench.ts index 70f5891f7160..b0452c4eeae9 100644 --- a/packages/app/perf/diff.bench.ts +++ b/packages/app/perf/diff.bench.ts @@ -23,6 +23,7 @@ const open: Case<{}> = { export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1366, height: 768 }, async prepare({ case: name, playwright, mock, url }) { const page = cached(playwright.page, mock) diff --git a/packages/app/perf/docks.bench.ts b/packages/app/perf/docks.bench.ts new file mode 100644 index 000000000000..1d853b8095b7 --- /dev/null +++ b/packages/app/perf/docks.bench.ts @@ -0,0 +1,109 @@ +// The composer giving way to request docks and back, under a 20-turn session: a permission request morphs the +// composer into its dock, an MCP elicitation grows in above it and closes, and the answered permission morphs back +// to the composer. Every frame of the four flights steps the docks' springs and writes their styles. +import { bench, web } from "@hona/strobe" +import type { OpenCodeEvent } from "@opencode/client/promise" +import { cached } from "./fixtures/mock" +import { composer, mockTimelineSession, timeline } from "./fixtures/timeline" + +// The session `mockTimelineSession` serves. +const sessionID = "ses_timeline_state_regression" + +const location = { directory: "C:/OpenCode/TimelineStateRegression" } + +const permission = '[data-component="dock-prompt"][data-kind="permission"]' + +// The elicitation dock shares the question dock's frame. +const elicitation = '[data-component="dock-prompt"][data-kind="question"]' + +let round = 0 + +export default bench({ + targets: { + web: web({ + expect: { title: "OpenCode" }, + viewport: { width: 1366, height: 768 }, + prepare: ({ playwright, mock, url }) => + mockTimelineSession(cached(playwright.page, mock), { + server: new URL(url).origin, + historyTurns: 20, + stream: true, + }), + url: ({ prepared }) => prepared.path, + }), + }, + + async setup({ page }) { + await page.waitFor(timeline, { timeout: 60_000 }) + await page.waitFor(composer) + await page.idle() + }, + + teardown: ({ prepared }) => prepared.source?.stop(), + + cases: { + // Each step waits for the page to settle, so the run spans every frame of all four flights. + "open and close request docks": { + primary: "main.work", + metrics: ["main.script", "main.style", "main.layout", "frames.dropped.pct", "frames.interval.p95"], + async run({ page, prepared }) { + const events = requestDocks() + prepared.source!.send([events.asked]) + await page.waitFor(permission) + await page.idle() + prepared.source!.send([events.elicited]) + await page.waitFor(elicitation) + await page.idle() + prepared.source!.send([events.cancelled]) + await page.idle() + prepared.source!.send([events.replied]) + await page.waitFor(composer) + await page.idle() + }, + }, + }, +}) + +// One round of request docks, with fresh IDs so the client never takes an event for a repeat. +function requestDocks() { + round++ + const permission = `per_docks_bench_${round}` + const form = `frm_docks_bench_${round}` + + const envelope = (step: number) => ({ + id: `evt_docks_bench_${round}_${step}`, + created: 1700000003000 + round, + location, + }) + + return { + asked: { + ...envelope(0), + type: "permission.asked", + data: { id: permission, sessionID, action: "shell", resources: ["bun test"], metadata: {} }, + } satisfies Extract, + elicited: { + ...envelope(1), + type: "form.created", + data: { + form: { + id: form, + sessionID, + title: "Input", + metadata: { kind: "mcp-elicitation" }, + fields: [{ key: "answer", type: "string", title: "Continue?" }], + }, + }, + } satisfies Extract, + cancelled: { + ...envelope(2), + type: "form.cancelled", + data: { sessionID, id: form }, + } satisfies Extract, + replied: { + ...envelope(3), + type: "permission.replied", + data: { sessionID, requestID: permission, reply: "once" }, + } satisfies Extract, + } +} diff --git a/packages/app/perf/home.bench.ts b/packages/app/perf/home.bench.ts index 26109087d0b8..fde36c8772a0 100644 --- a/packages/app/perf/home.bench.ts +++ b/packages/app/perf/home.bench.ts @@ -17,6 +17,7 @@ export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1440, height: 900 }, async prepare({ params, playwright, mock, url }) { const server = new URL(url).origin diff --git a/packages/app/perf/navigation.bench.ts b/packages/app/perf/navigation.bench.ts index 2ee9bab80aa0..d59f1dce7b14 100644 --- a/packages/app/perf/navigation.bench.ts +++ b/packages/app/perf/navigation.bench.ts @@ -38,6 +38,8 @@ const palette = '[role="dialog"] [role="combobox"]' const selected = '[role="dialog"] [role="option"][aria-selected="true"]' +const paletteList = '[role="dialog"] [data-component="menu-scroll"] > [data-scrollable]' + // Eight restored tabs of a normal 20-message first page each (44 parts, 139 KB). const restored = Array.from({ length: 8 }, (_, index) => ({ ...fixture.sessions[0], @@ -85,6 +87,7 @@ const scenes = new Map([ ["activate a restored tab", restoring], ["search commands in a session", inSource], ["search commands on home", onHome], + ["scroll the command palette", inSource], ]) const fresh: Pick, "reset"> = { @@ -99,6 +102,7 @@ const metrics = ["run.duration", "interaction.p50"] export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1440, height: 900 }, async prepare({ case: name, playwright, mock, url }) { const server = new URL(url).origin @@ -132,8 +136,10 @@ export default bench({ }), }, - async setup({ page, prepared }) { + async setup({ case: name, page, prepared }) { await page.waitFor(prepared.ready, { timeout: 60_000 }) + + if (name === "scroll the command palette") await page.press("ControlOrMeta+Shift+P", { until: paletteList }) await page.idle() }, @@ -260,5 +266,21 @@ export default bench({ await page.idle() }, }, + + // The palette's result list scrolls in a MenuScroll, which moves its thumb on every scroll frame. + "scroll the command palette": { + primary: "main.busy", + metrics: ["main.work", "frames.dropped.pct"], + async run({ page }) { + await page.scroll(paletteList, { by: 3000, speed: 3000 }) + await page.scroll(paletteList, { by: -3000, speed: 3000 }) + }, + // Opens the palette again each run, so a run starts at the top even if something closed it. + async reset({ page }) { + await page.press("Escape") + await page.press("ControlOrMeta+Shift+P", { until: paletteList }) + await page.idle() + }, + }, }, }) diff --git a/packages/app/perf/question.bench.ts b/packages/app/perf/question.bench.ts new file mode 100644 index 000000000000..b95c8c2f9f81 --- /dev/null +++ b/packages/app/perf/question.bench.ts @@ -0,0 +1,84 @@ +// The new question dock with its motion on: five questions, switched with the arrow keys while each switch is still +// moving, so the frame loop steps the switch, the dock's heights and the footer every frame. At 1440×900. +import { bench, web } from "@hona/strobe" +import { sessionHref } from "../e2e/utils/app" +import { mockOpenCodeServer } from "../e2e/utils/mock-server" +import { fixture } from "../e2e/utils/session-fixture" +import { cached } from "./fixtures/mock" + +const sessionID = "ses_perf_question" + +const question = '[data-component="dock-prompt"][data-kind="question"]' + +const title = `${question} [data-slot="question-header-title"]` + +export default bench({ + targets: { + web: web({ + expect: { title: "OpenCode" }, + viewport: { width: 1440, height: 900 }, + async prepare({ playwright, mock, url }) { + const server = new URL(url).origin + const page = cached(playwright.page, mock) + + await mockOpenCodeServer(page, { + server, + directory: fixture.directory, + project: fixture.project, + provider: fixture.provider, + sessions: [{ ...fixture.sessions[0], id: sessionID, title: "Question workload" }], + pageMessages: () => ({ items: [] }), + forms: [ + { + id: "frm_perf_question", + sessionID, + title: "Questions", + metadata: { kind: "question" }, + fields: Array.from({ length: 5 }, (_, index) => ({ + key: `q${index}`, + type: index % 2 ? "multiselect" : "string", + title: `Question ${index + 1}`, + description: `Question ${index + 1}: ${"Which of these should the change keep as it is? ".repeat(index + 1)}`, + options: Array.from({ length: 3 + index }, (_, option) => ({ + value: `option-${option}`, + label: `Option ${option + 1}`, + description: "Keeps the current behavior and adds coverage for it.", + })), + custom: true, + })), + }, + ], + }) + await page.addInitScript(() => { + localStorage.setItem("settings.v3", JSON.stringify({ general: { newQuestionUI: true } })) + localStorage.setItem("opencode.motion.v2", JSON.stringify({ "question.motion": 1 })) + }) + + return { path: sessionHref(sessionID, server) } + }, + url: ({ prepared }) => prepared.path, + }), + }, + + async setup({ page }) { + await page.waitFor(`${question} [data-slot="question-option"]:focus`, { timeout: 60_000 }) + await page.idle() + }, + + cases: { + // Four switches on and four back, each key a frame into the last switch. + "switch questions": { + primary: "main.work", + metrics: ["frames.dropped.pct"], + async run({ page }) { + for (const key of ["ArrowRight", "ArrowRight", "ArrowRight", "ArrowRight"]) + await page.press(key, { until: "frame" }) + await page.waitFor(title, { text: "5 of 5 questions" }) + + for (const key of ["ArrowLeft", "ArrowLeft", "ArrowLeft", "ArrowLeft"]) await page.press(key, { until: "frame" }) + await page.waitFor(title, { text: "1 of 5 questions" }) + await page.idle() + }, + }, + }, +}) diff --git a/packages/app/perf/review.bench.ts b/packages/app/perf/review.bench.ts index 0906bddeecb6..b2d494c19955 100644 --- a/packages/app/perf/review.bench.ts +++ b/packages/app/perf/review.bench.ts @@ -12,6 +12,7 @@ export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1366, height: 768 }, async prepare({ params, playwright, mock, url }) { const page = cached(playwright.page, mock) @@ -61,6 +62,22 @@ export default bench({ }, }, + // Closing the side panel and opening it again, each flight until it lands: every frame of the edge panel's motion. + "close and reopen review": { + primary: "main.work", + metrics: ["run.duration", "frames.dropped.pct"], + async run({ page }) { + await page.click(review.toggle) + await page.idle() + await page.click(review.toggle, { until: review.file }) + await page.idle() + }, + async reset({ page }) { + await openReview(page) + await page.idle() + }, + }, + // Three files ahead, each to its diff on screen. "next file": { primary: "main.work", diff --git a/packages/app/perf/stream.bench.ts b/packages/app/perf/stream.bench.ts index 334b124a4bee..b47564deca42 100644 --- a/packages/app/perf/stream.bench.ts +++ b/packages/app/perf/stream.bench.ts @@ -1,6 +1,6 @@ // A reply streaming into a long session: 160 markdown deltas (bold text, tables, code fences) at 40 a second, from a // server that never waits for the renderer. Per-delta cost that grows with the reply or the history shows up here. -import { bench, web, type Case } from "@hona/strobe" +import { bench, web, type Case, type Page } from "@hona/strobe" import { reviewDiffs } from "./fixtures/diffs" import { cached } from "./fixtures/mock" import { openReview } from "./fixtures/review" @@ -8,6 +8,22 @@ import { mockTimelineSession, reply, streamedReply, timeline } from "./fixtures/ const { start, deltas } = streamedReply(160) +const withFind = "stream with Find open" + +const find = '[data-component="timeline-search-bar"] input' + +// A phrase only the reply's last delta holds, so Find stays on the reply while every delta rescans the transcript. +// One input event: typed key by key, its prefixes would match the history and seek the timeline away from the reply. +async function openFind(page: Page) { + await page.press("ControlOrMeta+f", { until: find }) + await page.eval(() => { + const input = document.querySelector('[data-component="timeline-search-bar"] input')! + input.value = "benchmark-complete" + input.dispatchEvent(new InputEvent("input", { bubbles: true })) + }) + await page.waitFor('[data-slot="timeline-search-count"]', { text: "0/0" }) +} + const stream: Case<{}> = { primary: "main.work", metrics: ["frames.interval.p95", "frames.dropped.pct", "main.script", "main.layout", "main.style"], @@ -23,6 +39,8 @@ const stream: Case<{}> = { await page.goto(prepared.path, { until: timeline, timeout: 60_000 }) if (name === "stream with review open") await openReview(page) + + if (name === withFind) await openFind(page) await page.idle() }, } @@ -30,6 +48,7 @@ const stream: Case<{}> = { export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1366, height: 768 }, prepare: ({ case: name, playwright, mock, url }) => mockTimelineSession(cached(playwright.page, mock), { @@ -49,6 +68,8 @@ export default bench({ if (name === "stream with review open") await openReview(page) + if (name === withFind) await openFind(page) + // Its animations never stop, and with the attribution probes on a slow machine their frames can run long enough // that the page never counts as idle. if (name === "wait on a running session") return page.wait(2000) @@ -64,6 +85,8 @@ export default bench({ "stream into a tool-heavy history": stream, // The review pane open beside the timeline on 72 changed files. "stream with review open": stream, + // Find open on a phrase that only the last delta holds: each delta rescans the 120-turn transcript for it. + [withFind]: stream, // Five seconds of a running session between deltas: the tab's spinner and the Working shimmer animate, and nothing // else changes. Animation the compositor runs costs the page's main thread nothing. "wait on a running session": { diff --git a/packages/app/perf/tabs.bench.ts b/packages/app/perf/tabs.bench.ts index 28de47e813b2..f2eab8299c21 100644 --- a/packages/app/perf/tabs.bench.ts +++ b/packages/app/perf/tabs.bench.ts @@ -97,6 +97,7 @@ const cases = { export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1440, height: 900 }, async prepare({ case: name, playwright, mock, url }) { const server = new URL(url).origin diff --git a/packages/app/perf/timeline.bench.ts b/packages/app/perf/timeline.bench.ts index bf08ebab4902..a5a2e9682524 100644 --- a/packages/app/perf/timeline.bench.ts +++ b/packages/app/perf/timeline.bench.ts @@ -24,6 +24,7 @@ let divider: Divider | undefined export default bench({ targets: { web: web({ + expect: { title: "OpenCode" }, viewport: { width: 1366, height: 768 }, prepare: async ({ case: name, playwright, mock, url }) => ({ ...(await mockTimelineSession(cached(playwright.page, mock), { diff --git a/packages/app/src/components-lab/lab.tsx b/packages/app/src/components-lab/lab.tsx index 2a2b83c48763..3c2a6297f89b 100644 --- a/packages/app/src/components-lab/lab.tsx +++ b/packages/app/src/components-lab/lab.tsx @@ -47,6 +47,17 @@ import { type StoryArgs, type StoryModule, } from "./catalog" +import { + createLabStageState, + INITIAL_LAB_BROWSE_STATE, + labStageIndex, + selectShouldToggleFolder, + transitionLabBrowse, + transitionLabStage, + type LabBrowseEvent, + type LabStageEffect, + type LabStageEvent, +} from "./machine" import { applyMotionPatch, motionFields, motionScopes, motionValues, sameMotion, storyMotion } from "./motion" // How long Play holds each state at full speed. Slow motion doubles it while the motion itself runs 4× longer, so @@ -117,18 +128,20 @@ export default function ComponentsLab() { let palette: CommandPalette | undefined let toggle: ((id: string) => void) | undefined let focusTree: ((id?: string) => void) | undefined - // While browsing the tree by keys, a story that focuses something as it mounts (a dialog, a field) would take the - // keys away. A press or Tab anywhere ends browsing; a few returns at most, so a story that traps focus still wins. - let browsing = 0 - // The key behind the latest selection; none for a press. - let key: string | undefined + let browse = INITIAL_LAB_BROWSE_STATE + + const dispatchBrowse = (event: LabBrowseEvent) => { + const next = transitionLabBrowse(browse, event) + browse = next.state + next.effects.forEach(() => focusTree?.(params.story)) + } const entries = () => catalog()?.entries ?? [] const grid = () => params.view === "grid" const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === params.story))) const open = (file: string) => { - browsing = stories.contains(document.activeElement) ? 3 : 0 + dispatchBrowse({ type: "story.opened", fromTree: stories.contains(document.activeElement) }) setParams({ story: file, view: undefined }) } @@ -222,7 +235,7 @@ export default function ComponentsLab() { onSelect={(_, primary) => { if (!primary?.startsWith("folder:")) return primary && open(primary) - if (key === undefined || key === " ") toggle?.(primary) + if (selectShouldToggleFolder(browse)) toggle?.(primary) }} onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} /> @@ -254,20 +267,23 @@ export default function ComponentsLab() { )) - makeEventListener(window, "pointerdown", () => ((browsing = 0), (key = undefined)), { capture: true }) + const inTree = (event: Event) => event.target instanceof Node && stories.contains(event.target) + + makeEventListener(window, "pointerdown", (event) => dispatchBrowse({ type: "pointer.down", inTree: inTree(event) }), { + capture: true, + }) + // Bubbling, so the tree's own pointerup (which completes a press on a selected row) selects first. + makeEventListener(window, "pointerup", () => dispatchBrowse({ type: "pointer.ended" })) + makeEventListener(window, "pointercancel", () => dispatchBrowse({ type: "pointer.ended" })) makeEventListener( window, "keydown", - (event) => { - key = event.key - - if (event.key === "Tab") browsing = 0 - }, + (event) => dispatchBrowse({ type: "key.down", key: event.key, inTree: inTree(event) }), { capture: true }, ) - makeEventListener(stage, "focusin", () => { - if (browsing-- > 0) focusTree?.(params.story) - }) + makeEventListener(window, "keyup", () => dispatchBrowse({ type: "key.ended" })) + makeEventListener(window, "blur", () => dispatchBrowse({ type: "window.blurred" })) + makeEventListener(stage, "focusin", () => dispatchBrowse({ type: "stage.focused" })) let element!: HTMLDivElement @@ -323,33 +339,59 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" const fields = labFields(entry) const names = entry.states.map((state) => state.name) const [args, setArgs] = createStore(stateArgs(entry, 0)) - const [index, setIndex] = createSignal(0) + const [stageState, setStageState] = createSignal(createLabStageState(names)) + const index = createMemo(() => labStageIndex(stageState())) const [canvas, setCanvas] = createSignal() const component = entry.component const fallback = component && ((values: StoryArgs) => ) // Switching to a state that shares the current render function keeps the mounted instance, so its transitions play. const render = () => entry.states[index()]?.render ?? entry.render ?? fallback let timer: ReturnType | undefined - // The state Play is moving to. Any other change is a hand's, and a hand's change stops Play. - let advancing: number | undefined // A state is a variant: its chip, a digit, `[` and `]` and Play all apply it, so the panel shows where it is. const preset = (next: number): void => store.preset(next === 0 ? "default" : (names[next] ?? "default")) - const step = (by: number) => preset((index() + by + names.length) % names.length) + // One batch, so a state with its own render function never renders with the previous state's args. + const dispatch = (event: LabStageEvent) => + batch(() => { + const next = transitionLabStage(untrack(stageState), event) + setStageState(next.state) + next.effects.forEach(perform) + }) - const pause = () => clearTimeout(timer) + const perform = (effect: LabStageEffect) => { + if (effect.type === "timer.schedule") { + clearTimeout(timer) + timer = setTimeout( + () => dispatch({ type: "tick", attempt: effect.attempt }), + (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, + ) - const play = () => { - clearTimeout(timer) - timer = setTimeout( - () => { - advancing = (index() + 1) % names.length - preset(advancing) - play() - }, - (hold * (motionGlobals.slow.value ? 2 : 1)) / motionGlobals.speed.value, - ) + return + } + + if (effect.type === "timer.clear") return clearTimeout(timer) + + if (effect.type === "state.apply") { + setArgs(reconcile(stateArgs(entry, effect.index))) + + if (effect.preset === "now") preset(effect.index) + + // Undo or a reset moved the state: bring the other knobs to the state's args too. + if (effect.preset === "later") + queueMicrotask(() => { + if (untrack(stageState).status !== "disposed") preset(effect.index) + }) + + return + } + + // Coalesced: a story registers its replay buttons one by one. + if (effect.type === "motion.queue") return queueMicrotask(() => dispatch({ type: "motion.flushed" })) + const next = storyMotion(entry.motion) + + if (!sameMotion(next, motion)) return setShown(next) + store.sync(motionValues(motion)) } const [first, ...rest] = names @@ -365,15 +407,15 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" id: "previous", label: language.t("lab.previous"), icon: "M200 48 80 128l120 80ZM48 48h16v160H48Z", - run: () => step(-1), + run: () => dispatch({ type: "step", delta: -1 }), }, - { id: "play", label: language.t("lab.play"), icon: "play", run: play }, - { id: "pause", label: language.t("lab.pause"), icon: "pause", run: () => clearTimeout(timer) }, + { id: "play", label: language.t("lab.play"), icon: "play", run: () => dispatch({ type: "play" }) }, + { id: "pause", label: language.t("lab.pause"), icon: "pause", run: () => dispatch({ type: "pause" }) }, { id: "next", label: language.t("lab.next"), icon: "M56 48l120 80-120 80ZM192 48h16v160h-16Z", - run: () => step(1), + run: () => dispatch({ type: "step", delta: 1 }), }, ], { labels: false }, @@ -407,23 +449,12 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" applyMotionPatch(motion, patch) if (!("state" in patch)) { - if (meta.source !== "preset") pause() + if (meta.source !== "preset") dispatch({ type: "pause" }) return setArgs(Object.fromEntries(Object.entries(patch).filter(([key]) => key in fields))) } - // One batch, so a state with its own render function never renders with the previous state's args. - const next = Math.max(0, names.indexOf(String(values.state))) - - if (next !== advancing) pause() - advancing = undefined - batch(() => { - setArgs(reconcile(stateArgs(entry, next))) - setIndex(next) - }) - - // Undo or a reset moved the state: bring the other knobs to the state's args too. - if (meta.source !== "preset") queueMicrotask(() => preset(next)) + dispatch({ type: "panel.state", name: String(values.state), fromPreset: meta.source === "preset" }) }, }, ) @@ -446,27 +477,16 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" }), ) - // A rebuild stays on the state it was showing. - if (rest.length > 0) untrack(() => preset(index())) - }) - - // Coalesced: a story registers its replay buttons one by one. - let queued = false - onCleanup( - motionTuning.subscribe(() => { - if (queued) return - queued = true - queueMicrotask(() => { - queued = false - const next = storyMotion(entry.motion) - - if (!sameMotion(next, motion)) return setShown(next) - store.sync(motionValues(motion)) + // A rebuild stays on the state it was showing, and its fresh knobs show that state's args. + if (rest.length > 0) + untrack(() => { + setArgs(reconcile(stateArgs(entry, index()))) + preset(index()) }) - }), - ) + }) - onCleanup(() => clearTimeout(timer)) + onCleanup(motionTuning.subscribe(() => dispatch({ type: "motion.changed" }))) + onCleanup(() => dispatch({ type: "disposed" })) makeEventListener(window, "keydown", (event) => { const digit = Number(event.key) @@ -475,7 +495,7 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey || typing(event.target)) return event.preventDefault() - preset(digit - 1) + dispatch({ type: "select", index: digit - 1 }) }) return ( @@ -485,7 +505,7 @@ function Stage(props: { entry: LabEntry; inspector: HTMLElement; scheme: "dark" ref={setCanvas} class="flex size-full overflow-auto bg-v2-background-bg-base [contain:layout]" classList={{ "items-center justify-center p-8": !entry.fullscreen, "flex-col": entry.fullscreen }} - onPointerDown={pause} + onPointerDown={() => dispatch({ type: "pause" })} > diff --git a/packages/app/src/components-lab/machine.test.ts b/packages/app/src/components-lab/machine.test.ts new file mode 100644 index 000000000000..8650e39532df --- /dev/null +++ b/packages/app/src/components-lab/machine.test.ts @@ -0,0 +1,177 @@ +import { expect, test } from "bun:test" +import { + createLabStageState, + INITIAL_LAB_BROWSE_STATE, + labStageIndex, + selectShouldToggleFolder, + transitionLabBrowse, + transitionLabStage, + type LabBrowseEvent, + type LabBrowseState, + type LabStageEvent, + type LabStageState, + type LabStageTransition, +} from "./machine" + +/** Each event's effects from `state`, and the state after the last. */ +const browse = (state: LabBrowseState, ...events: LabBrowseEvent[]) => + events.reduce<{ state: LabBrowseState; effects: string[] }>( + (current, event) => { + const next = transitionLabBrowse(current.state, event) + + return { state: next.state, effects: [...current.effects, ...next.effects.map((effect) => effect.type)] } + }, + { state, effects: [] }, + ) + +test("focus moving inside the stage at rest stays at rest", () => { + const focused = browse(INITIAL_LAB_BROWSE_STATE, { type: "stage.focused" }, { type: "stage.focused" }) + + expect(focused.state).toBe(INITIAL_LAB_BROWSE_STATE) + expect(focused.effects).toEqual([]) + + // Many focus moves later, a story opened from the tree still gets exactly three returns. + const opened = browse( + focused.state, + { type: "story.opened", fromTree: true }, + ...Array.from({ length: 4 }, () => ({ type: "stage.focused" }) as const), + ) + + expect(opened.effects).toEqual(["focus.tree", "focus.tree", "focus.tree"]) + expect(opened.state).toBe(INITIAL_LAB_BROWSE_STATE) +}) + +test.each([{ type: "key.ended" }, { type: "window.blurred" }] as const)( + "a Space press in the tree no longer toggles folders after $type", + (end) => { + const pressed = browse(INITIAL_LAB_BROWSE_STATE, { type: "key.down", key: " ", inTree: true }) + + expect(selectShouldToggleFolder(pressed.state)).toBe(true) + expect(selectShouldToggleFolder(browse(pressed.state, end).state)).toBe(false) + }, +) + +test("a Space press outside the tree and arrow keys in it never toggle folders", () => { + expect(selectShouldToggleFolder(INITIAL_LAB_BROWSE_STATE)).toBe(false) + expect(browse(INITIAL_LAB_BROWSE_STATE, { type: "key.down", key: " ", inTree: false }).state).toBe( + INITIAL_LAB_BROWSE_STATE, + ) + expect( + selectShouldToggleFolder( + browse( + INITIAL_LAB_BROWSE_STATE, + { type: "key.down", key: " ", inTree: true }, + { type: "key.down", key: "ArrowDown", inTree: true }, + ).state, + ), + ).toBe(false) +}) + +test("a click in the tree toggles folders until the press ends", () => { + const pressed = browse(INITIAL_LAB_BROWSE_STATE, { type: "pointer.down", inTree: true }) + + expect(selectShouldToggleFolder(pressed.state)).toBe(true) + expect(browse(pressed.state, { type: "pointer.ended" }).state).toBe(INITIAL_LAB_BROWSE_STATE) +}) + +test.each([ + { type: "key.down", key: "Tab", inTree: true }, + { type: "pointer.down", inTree: false }, +] as const)("$type ends browsing before the stage takes focus", (exit) => { + const ended = browse(INITIAL_LAB_BROWSE_STATE, { type: "story.opened", fromTree: true }, exit, { + type: "stage.focused", + }) + + expect(ended.effects).toEqual([]) + expect(ended.state).toBe(INITIAL_LAB_BROWSE_STATE) +}) + +const names = ["Closed", "Opening", "Open"] + +/** The last transition of `events` from `state`. */ +const run = (state: LabStageState, ...events: LabStageEvent[]) => + events.reduce((current, event) => transitionLabStage(current.state, event), { + state, + effects: [], + }) + +test("an inspector rebuild after an advance keeps Play running", () => { + const advanced = run(createLabStageState(names), { type: "play" }, { type: "tick", attempt: 1 }) + expect(advanced.effects).toEqual([ + { type: "state.apply", index: 1, preset: "now" }, + { type: "timer.schedule", attempt: 2 }, + ]) + + // A story registering a motion knob rebuilds the panel, which restores the state it was showing. + const rebuilt = transitionLabStage(advanced.state, { type: "panel.state", name: "Opening", fromPreset: true }) + expect(rebuilt.state).toBe(advanced.state) + expect(rebuilt.effects).toEqual([]) + expect(rebuilt.state.status).toBe("playing") +}) + +test("Play advances even when the panel reports no change, and a later hand still stops it", () => { + const twins = createLabStageState(["Open", "Open"]) + const advanced = run(twins, { type: "play" }, { type: "tick", attempt: 1 }) + expect(labStageIndex(advanced.state)).toBe(1) + expect(advanced.effects.at(-1)).toEqual({ type: "timer.schedule", attempt: 2 }) + + const stepped = transitionLabStage(advanced.state, { type: "step", delta: 1 }) + expect(stepped.state.status).toBe("paused") + expect(stepped.effects).toEqual([{ type: "timer.clear" }, { type: "state.apply", index: 0, preset: "now" }]) +}) + +test("the digit of the state shown pauses Play", () => { + const paused = run(createLabStageState(names), { type: "play" }, { type: "select", index: 0 }) + expect(paused.state.status).toBe("paused") + expect(paused.effects).toEqual([{ type: "timer.clear" }, { type: "state.apply", index: 0, preset: "now" }]) +}) + +test("Play while playing, Pause while paused and Play with one state do nothing", () => { + const paused = createLabStageState(names) + expect(transitionLabStage(paused, { type: "pause" })).toEqual({ state: paused, effects: [] }) + + const playing = run(paused, { type: "play" }).state + expect(transitionLabStage(playing, { type: "play" })).toEqual({ state: playing, effects: [] }) + + const single = createLabStageState(["Only"]) + expect(transitionLabStage(single, { type: "play" })).toEqual({ state: single, effects: [] }) +}) + +test("motion registrations coalesce, and a sync queued before unmount never runs", () => { + const queued = run(createLabStageState(names), { type: "motion.changed" }) + expect(queued.effects).toEqual([{ type: "motion.queue" }]) + expect(transitionLabStage(queued.state, { type: "motion.changed" }).state).toBe(queued.state) + expect(transitionLabStage(queued.state, { type: "motion.flushed" }).effects).toEqual([{ type: "motion.sync" }]) + + const disposed = transitionLabStage(queued.state, { type: "disposed" }) + expect(transitionLabStage(disposed.state, { type: "motion.flushed" })).toEqual({ state: disposed.state, effects: [] }) +}) + +test("a timer from an earlier Play is ignored", () => { + const replayed = run(createLabStageState(names), { type: "play" }, { type: "pause" }, { type: "play" }) + expect(replayed.effects).toEqual([{ type: "timer.schedule", attempt: 2 }]) + expect(transitionLabStage(replayed.state, { type: "tick", attempt: 1 }).state).toBe(replayed.state) + expect(labStageIndex(transitionLabStage(replayed.state, { type: "tick", attempt: 2 }).state)).toBe(1) +}) + +test("Undo or Reset moving the state stops Play and syncs the knobs afterwards", () => { + const undone = run( + createLabStageState(names), + { type: "play" }, + { type: "panel.state", name: "Open", fromPreset: false }, + ) + + expect(undone.state.status).toBe("paused") + expect(undone.effects).toEqual([{ type: "timer.clear" }, { type: "state.apply", index: 2, preset: "later" }]) + + const chip = transitionLabStage(undone.state, { type: "panel.state", name: "Closed", fromPreset: true }) + expect(chip.effects).toEqual([{ type: "state.apply", index: 0, preset: "none" }]) +}) + +test("a disposed stage stops its timer and ignores everything after", () => { + const playing = run(createLabStageState(names), { type: "play" }).state + const disposed = transitionLabStage(playing, { type: "disposed" }) + expect(disposed.effects).toEqual([{ type: "timer.clear" }]) + expect(transitionLabStage(disposed.state, { type: "tick", attempt: 1 }).state).toBe(disposed.state) + expect(transitionLabStage(disposed.state, { type: "play" }).effects).toEqual([]) +}) diff --git a/packages/app/src/components-lab/machine.ts b/packages/app/src/components-lab/machine.ts new file mode 100644 index 000000000000..1f1cd9b10ceb --- /dev/null +++ b/packages/app/src/components-lab/machine.ts @@ -0,0 +1,229 @@ +type Stage = { + /** The story's state names, in order. */ + readonly names: readonly string[] + /** The state shown. */ + readonly index: number + /** A motion sync is queued for the next microtask; registrations in between join it. */ + readonly motionQueued: boolean + /** Each Play advance takes a new attempt, so a timer from an earlier Play or advance is ignored. */ + readonly attempt: number +} + +export type LabStageState = + | ({ readonly status: "paused" } & Stage) + | ({ readonly status: "playing" } & Stage) + | { readonly status: "disposed" } + +export type LabStageEvent = + | { readonly type: "play" } + /** The Pause button, a press in the story or a knob edit. */ + | { readonly type: "pause" } + | { readonly type: "tick"; readonly attempt: number } + /** Previous and Next. */ + | { readonly type: "step"; readonly delta: -1 | 1 } + /** A digit key. */ + | { readonly type: "select"; readonly index: number } + /** The panel's state moved: a chip, Undo or Reset, or the echo of a preset this machine applied. */ + | { readonly type: "panel.state"; readonly name: string; readonly fromPreset: boolean } + | { readonly type: "motion.changed" } + | { readonly type: "motion.flushed" } + | { readonly type: "disposed" } + +export type LabStageEffect = + /** Dispatch `tick` with `attempt` once the hold has passed. */ + | { readonly type: "timer.schedule"; readonly attempt: number } + | { readonly type: "timer.clear" } + /** + * Shows the state's args. `preset` brings the panel to the state now, `later` in a microtask (the panel moved the + * state itself through Undo or Reset), `none` when the panel already applied it. + */ + | { readonly type: "state.apply"; readonly index: number; readonly preset: "now" | "later" | "none" } + /** Dispatch `motion.flushed` in a microtask. */ + | { readonly type: "motion.queue" } + | { readonly type: "motion.sync" } + +export type LabStageTransition = { + readonly state: LabStageState + readonly effects: readonly LabStageEffect[] +} + +export function createLabStageState(names: readonly string[]): LabStageState { + return { status: "paused", names, index: 0, motionQueued: false, attempt: 0 } +} + +export function transitionLabStage(state: LabStageState, event: LabStageEvent): LabStageTransition { + if (state.status === "disposed") return unchanged(state) + + if (event.type === "disposed") + return { state: { status: "disposed" }, effects: state.status === "playing" ? [{ type: "timer.clear" }] : [] } + + if (event.type === "play") { + if (state.status === "playing" || state.names.length < 2) return unchanged(state) + const attempt = state.attempt + 1 + + return { state: { ...state, status: "playing", attempt }, effects: [{ type: "timer.schedule", attempt }] } + } + + if (event.type === "pause") { + if (state.status !== "playing") return unchanged(state) + + return { state: { ...state, status: "paused" }, effects: [{ type: "timer.clear" }] } + } + + if (event.type === "tick") { + if (state.status !== "playing" || state.attempt !== event.attempt) return unchanged(state) + const index = (state.index + 1) % state.names.length + const attempt = state.attempt + 1 + + return { + state: { ...state, index, attempt }, + effects: [ + { type: "state.apply", index, preset: "now" }, + { type: "timer.schedule", attempt }, + ], + } + } + + if (event.type === "step") { + if (state.names.length < 2) return unchanged(state) + + return show(state, (state.index + event.delta + state.names.length) % state.names.length, "now") + } + + if (event.type === "select") { + if (state.names.length < 2 || event.index < 0 || event.index >= state.names.length) return unchanged(state) + + return show(state, event.index, "now") + } + + if (event.type === "panel.state") { + const index = state.names.indexOf(event.name) + + // The echo of a preset applied here, or of the inspector's rebuild, names the state already shown. + if (index < 0 || state.names[state.index] === event.name) return unchanged(state) + + return show(state, index, event.fromPreset ? "none" : "later") + } + + if (event.type === "motion.changed") { + if (state.motionQueued) return unchanged(state) + + return { state: { ...state, motionQueued: true }, effects: [{ type: "motion.queue" }] } + } + + if (!state.motionQueued) return unchanged(state) + + return { state: { ...state, motionQueued: false }, effects: [{ type: "motion.sync" }] } +} + +/** The state the stage shows. */ +export function labStageIndex(state: LabStageState) { + return state.status === "disposed" ? 0 : state.index +} + +/** A hand's choice of state stops Play. */ +function show( + state: Exclude, + index: number, + preset: "now" | "later" | "none", +): LabStageTransition { + return { + state: { ...state, status: "paused", index }, + effects: [ + ...(state.status === "playing" ? [{ type: "timer.clear" } as const] : []), + { type: "state.apply", index, preset }, + ], + } +} + +function unchanged(state: LabStageState): LabStageTransition { + return { state, effects: [] } +} + +/** + * How a press reached the tree. A folder opens and closes only by a click or Space in the tree, so moving by arrows + * (which selects as it goes) or a selection from elsewhere leaves it as it is. + */ +export type LabTreeGesture = "none" | "pointer" | "space" + +/** + * While browsing the tree by keys, a story that focuses something as it mounts (a dialog, a field) would take the + * keys away. A press or Tab anywhere ends browsing; a few returns at most, so a story that traps focus still wins. + */ +export type LabBrowseState = + | { readonly status: "idle"; readonly gesture: LabTreeGesture } + | { readonly status: "browsing"; readonly redirects: 1 | 2 | 3; readonly gesture: LabTreeGesture } + +export type LabBrowseEvent = + | { readonly type: "pointer.down"; readonly inTree: boolean } + | { readonly type: "pointer.ended" } + | { readonly type: "key.down"; readonly key: string; readonly inTree: boolean } + | { readonly type: "key.ended" } + | { readonly type: "window.blurred" } + | { readonly type: "story.opened"; readonly fromTree: boolean } + /** Focus moved into the stage. */ + | { readonly type: "stage.focused" } + +export type LabBrowseEffect = { readonly type: "focus.tree" } + +export type LabBrowseTransition = { + readonly state: LabBrowseState + readonly effects: readonly LabBrowseEffect[] +} + +export const INITIAL_LAB_BROWSE_STATE: LabBrowseState = Object.freeze({ status: "idle", gesture: "none" }) + +export function transitionLabBrowse(state: LabBrowseState, event: LabBrowseEvent): LabBrowseTransition { + if (event.type === "pointer.down") { + const gesture = event.inTree ? "pointer" : "none" + + return { state: state.status === "idle" && state.gesture === gesture ? state : idle(gesture), effects: [] } + } + + if (event.type === "key.down") { + if (event.key === "Tab") return { state: INITIAL_LAB_BROWSE_STATE, effects: [] } + + return { state: withGesture(state, event.key === " " && event.inTree ? "space" : "none"), effects: [] } + } + + if (event.type === "pointer.ended") + return { state: state.gesture === "pointer" ? withGesture(state, "none") : state, effects: [] } + + if (event.type === "key.ended") + return { state: state.gesture === "space" ? withGesture(state, "none") : state, effects: [] } + + if (event.type === "window.blurred") return { state: INITIAL_LAB_BROWSE_STATE, effects: [] } + + if (event.type === "story.opened") { + if (!event.fromTree) return { state: idle(state.gesture), effects: [] } + + return { state: { status: "browsing", redirects: 3, gesture: state.gesture }, effects: [] } + } + + if (state.status === "idle") return { state, effects: [] } + + return { + state: + state.redirects === 1 + ? idle(state.gesture) + : { status: "browsing", redirects: state.redirects === 3 ? 2 : 1, gesture: state.gesture }, + effects: [{ type: "focus.tree" }], + } +} + +/** A selection of a folder toggles it only while a click or Space in the tree caused it. */ +export function selectShouldToggleFolder(state: LabBrowseState) { + return state.gesture !== "none" +} + +function idle(gesture: LabTreeGesture): LabBrowseState { + return gesture === "none" ? INITIAL_LAB_BROWSE_STATE : { status: "idle", gesture } +} + +function withGesture(state: LabBrowseState, gesture: LabTreeGesture): LabBrowseState { + if (state.gesture === gesture) return state + + if (state.status === "idle") return idle(gesture) + + return { ...state, gesture } +} diff --git a/packages/app/src/composer/adapter.ts b/packages/app/src/composer/adapter.ts index 21e9a8e18878..98f95a17ba6a 100644 --- a/packages/app/src/composer/adapter.ts +++ b/packages/app/src/composer/adapter.ts @@ -56,8 +56,12 @@ export type ComposerQueue = { export type ComposerSession = { id: string directory: string + // The timeline's optimistic prompt: shown on `set` (or `hold` while the send waits for the Location's agents and models), + // held after `settle` until its admission echo, removed on `clear`. handoff: { set: (handoff: SessionMessageHandoff) => void + hold: (handoff: SessionMessageHandoff) => void + settle: (messageID: string) => void clear: (messageID: string) => void } api: { diff --git a/packages/app/src/composer/attachments/attachments.ts b/packages/app/src/composer/attachments/attachments.ts index 0e1c00e760c9..6547a9aed3de 100644 --- a/packages/app/src/composer/attachments/attachments.ts +++ b/packages/app/src/composer/attachments/attachments.ts @@ -1,5 +1,4 @@ import { onCleanup, onMount } from "solid-js" -import { createStore } from "solid-js/store" import { makeEventListener } from "@solid-primitives/event-listener" import { createBlobReference } from "@/runtime/persistence/drafts" import { uuid } from "@opencode/util/uuid" @@ -9,6 +8,8 @@ import type { AttachmentDestination } from "./destination" import { uploads } from "./uploads" type PromptTarget = { + /** The draft the prompt belongs to, which owns uploads started for it across composer remounts. */ + scope?: object current: () => ComposerPrompt cursor: () => number | undefined set: (prompt: ComposerPrompt, cursor?: number) => void @@ -55,8 +56,9 @@ export function createComposerAttachments( return { prompt, cursor: prompt.cursor() ?? cursorPosition(editor) } } - // Uploads this composer started; they finish (or fail) even if the composer unmounts. - const [pending, setPending] = createStore<{ ids: string[] }>({ ids: [] }) + // A composer without a draft scope owns its uploads itself. + const fallbackScope = {} + const scopeOf = (prompt = input.capture()) => prompt.scope ?? fallbackScope // Media the model reads natively travels inline with the prompt, so its bytes live in the draft // store. Everything else, including text, reaches the model as a path on the server that its @@ -125,19 +127,16 @@ export function createComposerAttachments( target: NonNullable>, destination: AttachmentDestination, ) => { - const id = uuid() - setPending("ids", (ids) => [...ids, id]) - const path = await uploads - .track({ id, filename: file.name, mime, size: file.size }, (report, signal) => - destination.upload(file, report, signal), + .track( + { id: uuid(), scope: scopeOf(target.prompt), filename: file.name, mime, size: file.size }, + (report, signal) => destination.upload(file, report, signal), ) .catch((error) => { input.onUploadError(error) return undefined }) - .finally(() => setPending("ids", (ids) => ids.filter((item) => item !== id))) if (path) addPath(target, { filename: file.name, mime, path }) } @@ -251,10 +250,8 @@ export function createComposerAttachments( handlePaste, handleDrop, /** Uploads still in flight for this composer; sending waits for them. */ - pending: () => uploads.items().filter((item) => pending.ids.includes(item.id)), - cancel(id: string) { - uploads.items().find((item) => item.id === id)?.cancel() - }, + pending: () => uploads.forScope(scopeOf()), + cancel: (id: string) => uploads.cancel(id), pick(fallback: () => void, done: () => void) { if (!input.picker) { fallback() diff --git a/packages/app/src/composer/attachments/upload-machine.ts b/packages/app/src/composer/attachments/upload-machine.ts new file mode 100644 index 000000000000..00f0423aa352 --- /dev/null +++ b/packages/app/src/composer/attachments/upload-machine.ts @@ -0,0 +1,185 @@ +// An upload whose body stops advancing for this long is stuck on a dead connection; it fails instead of blocking sends. +export const UPLOAD_STALL_TIMEOUT_MS = 60_000 + +/** The failure a stalled upload rejects with; it carries no message, so the toast shows the generic one. */ +export const UPLOAD_TIMED_OUT = Object.freeze({ reason: "timed-out" as const }) + +/** The draft an upload writes into, compared by identity; closing that draft cancels its uploads. */ +export type UploadScope = object + +export type UploadEntry = { + readonly id: string + readonly attempt: number + readonly scope: UploadScope + readonly filename: string + readonly mime: string + readonly size: number + readonly loaded: number + /** + * Only `sending` arms the stall timer. A `queued` request may wait behind the browser's per-host connection + * limit before its first progress event, and a `sent` body waits on the server's answer; neither is a stall. + */ + readonly transfer: "queued" | "sending" | "sent" +} + +/** + * Every upload in flight, process-wide: uploads outlive the composer view that started them. + * - `idle`: nothing uploads. + * - `uploading`: `entries` is never empty, in start order. + */ +export type UploadMachineState = + | { readonly status: "idle"; readonly issued: number } + | { readonly status: "uploading"; readonly issued: number; readonly entries: readonly UploadEntry[] } + +export type UploadMachineEvent = + | { + readonly type: "upload.started" + readonly id: string + readonly scope: UploadScope + readonly filename: string + readonly mime: string + readonly size: number + } + | { readonly type: "upload.progress"; readonly attempt: number; readonly loaded: number } + | { readonly type: "upload.succeeded"; readonly attempt: number; readonly path: string } + | { readonly type: "upload.failed"; readonly attempt: number; readonly error: unknown } + | { readonly type: "upload.timed-out"; readonly attempt: number } + | { readonly type: "upload.cancelled"; readonly id: string } + | { readonly type: "scope.cancelled"; readonly scope: UploadScope } + +export type UploadMachineEffect = + | { readonly type: "upload.run"; readonly attempt: number } + | { readonly type: "timer.reset"; readonly attempt: number; readonly timeoutMs: number } + | { readonly type: "timer.clear"; readonly attempt: number } + | { readonly type: "upload.abort"; readonly attempt: number } + | { readonly type: "upload.resolve"; readonly attempt: number; readonly path: string | undefined } + | { readonly type: "upload.reject"; readonly attempt: number; readonly error: unknown } + +export type UploadMachineTransition = { + readonly state: UploadMachineState + readonly effects: readonly UploadMachineEffect[] +} + +export const INITIAL_UPLOAD_MACHINE_STATE: UploadMachineState = Object.freeze({ status: "idle", issued: 0 }) + +const NO_EFFECTS: readonly UploadMachineEffect[] = Object.freeze([]) + +const NO_ENTRIES: readonly UploadEntry[] = Object.freeze([]) + +export function transitionUploads(state: UploadMachineState, event: UploadMachineEvent): UploadMachineTransition { + if (event.type === "upload.started") { + const entries = selectUploadEntries(state) + + if (entries.some((entry) => entry.id === event.id)) return stay(state) + const attempt = state.issued + 1 + + return { + state: { + status: "uploading", + issued: attempt, + entries: [ + ...entries, + { + id: event.id, + attempt, + scope: event.scope, + filename: event.filename, + mime: event.mime, + size: event.size, + loaded: 0, + transfer: "queued", + }, + ], + }, + effects: [{ type: "upload.run", attempt }], + } + } + + if (state.status === "idle") return stay(state) + + if (event.type === "scope.cancelled") { + const cancelled = state.entries.filter((entry) => entry.scope === event.scope) + + if (cancelled.length === 0) return stay(state) + + return finish( + state, + state.entries.filter((entry) => entry.scope !== event.scope), + cancelled.flatMap((entry) => cancel(entry.attempt)), + ) + } + + const entry = state.entries.find((item) => + event.type === "upload.cancelled" ? item.id === event.id : item.attempt === event.attempt, + ) + + if (!entry) return stay(state) + const rest = () => state.entries.filter((item) => item !== entry) + + switch (event.type) { + case "upload.progress": { + const loaded = Math.min(Math.max(event.loaded, entry.loaded), entry.size) + const transfer = loaded === entry.size ? "sent" : "sending" + + if (loaded === entry.loaded && transfer === entry.transfer) return stay(state) + + return { + state: { + ...state, + entries: state.entries.map((item) => (item === entry ? { ...entry, loaded, transfer } : item)), + }, + effects: + transfer === "sending" + ? [{ type: "timer.reset", attempt: entry.attempt, timeoutMs: UPLOAD_STALL_TIMEOUT_MS }] + : entry.transfer === "sending" + ? [{ type: "timer.clear", attempt: entry.attempt }] + : NO_EFFECTS, + } + } + + case "upload.succeeded": + return finish(state, rest(), [{ type: "upload.resolve", attempt: entry.attempt, path: event.path }]) + case "upload.failed": + return finish(state, rest(), [{ type: "upload.reject", attempt: entry.attempt, error: event.error }]) + case "upload.timed-out": + if (entry.transfer !== "sending") return stay(state) + + return finish(state, rest(), [ + { type: "upload.abort", attempt: entry.attempt }, + { type: "upload.reject", attempt: entry.attempt, error: UPLOAD_TIMED_OUT }, + ]) + case "upload.cancelled": + return finish(state, rest(), cancel(entry.attempt)) + } +} + +export function selectUploadEntries(state: UploadMachineState) { + return state.status === "uploading" ? state.entries : NO_ENTRIES +} + +export function uploadPercent(item: Pick) { + return item.size === 0 ? 100 : Math.floor((item.loaded / item.size) * 100) +} + +// A cancelled upload settles without its work: the work may wait where it cannot observe the abort. +function cancel(attempt: number): UploadMachineEffect[] { + return [ + { type: "upload.abort", attempt }, + { type: "upload.resolve", attempt, path: undefined }, + ] +} + +function finish( + state: Extract, + entries: readonly UploadEntry[], + effects: readonly UploadMachineEffect[], +): UploadMachineTransition { + return { + state: entries.length === 0 ? { status: "idle", issued: state.issued } : { ...state, entries }, + effects, + } +} + +function stay(state: UploadMachineState): UploadMachineTransition { + return { state, effects: NO_EFFECTS } +} diff --git a/packages/app/src/composer/attachments/uploads.test.ts b/packages/app/src/composer/attachments/uploads.test.ts index 2762313e623d..9d1103650b37 100644 --- a/packages/app/src/composer/attachments/uploads.test.ts +++ b/packages/app/src/composer/attachments/uploads.test.ts @@ -1,14 +1,127 @@ -import { expect, test } from "bun:test" +import { afterEach, describe, expect, jest, test } from "bun:test" import { uploads } from "./uploads" +import { + INITIAL_UPLOAD_MACHINE_STATE, + UPLOAD_STALL_TIMEOUT_MS, + UPLOAD_TIMED_OUT, + transitionUploads, + type UploadMachineEvent, + type UploadMachineState, + type UploadMachineTransition, + type UploadScope, +} from "./upload-machine" -test("cancelling an upload drops it even when its work never settles", async () => { - const pending = uploads.track({ id: "stalled", filename: "image.png", mime: "image/png", size: 1024 }, () => - new Promise(() => {}), - ) +const scopeA = {} - expect(uploads.items().map((item) => item.id)).toEqual(["stalled"]) - uploads.items()[0]?.cancel() +const scopeB = {} - expect(await pending).toBeUndefined() - expect(uploads.items()).toEqual([]) +function start(id: string, scope: UploadScope): UploadMachineEvent { + return { type: "upload.started", id, scope, filename: `${id}.bin`, mime: "application/octet-stream", size: 1024 } +} + +function replay(events: UploadMachineEvent[], state: UploadMachineState = INITIAL_UPLOAD_MACHINE_STATE) { + const initial: UploadMachineTransition = { state, effects: [] } + + return events.reduce((result, event) => transitionUploads(result.state, event), initial) +} + +afterEach(() => { + jest.useRealTimers() +}) + +describe("transitionUploads", () => { + test("a queued upload has no stall timer until its first progress event, then only forward progress resets it", () => { + const queued = replay([start("u1", scopeA)]) + + expect(queued.effects).toEqual([{ type: "upload.run", attempt: 1 }]) + expect(transitionUploads(queued.state, { type: "upload.timed-out", attempt: 1 }).state).toBe(queued.state) + + const connected = replay([{ type: "upload.progress", attempt: 1, loaded: 0 }], queued.state) + + expect(connected.state).toMatchObject({ entries: [{ id: "u1", loaded: 0, transfer: "sending" }] }) + expect(connected.effects).toEqual([{ type: "timer.reset", attempt: 1, timeoutMs: UPLOAD_STALL_TIMEOUT_MS }]) + + const progressed = replay([{ type: "upload.progress", attempt: 1, loaded: 512 }], connected.state) + + expect(progressed.effects).toEqual([{ type: "timer.reset", attempt: 1, timeoutMs: UPLOAD_STALL_TIMEOUT_MS }]) + expect(transitionUploads(progressed.state, { type: "upload.progress", attempt: 1, loaded: 256 }).state).toBe( + progressed.state, + ) + + expect(transitionUploads(progressed.state, { type: "upload.timed-out", attempt: 1 })).toEqual({ + state: { status: "idle", issued: 1 }, + effects: [ + { type: "upload.abort", attempt: 1 }, + { type: "upload.reject", attempt: 1, error: UPLOAD_TIMED_OUT }, + ], + }) + }) + + test("a fully sent body waits for the server's answer without a stall timer", () => { + const sending = replay([start("u1", scopeA), { type: "upload.progress", attempt: 1, loaded: 512 }]) + const sent = replay([{ type: "upload.progress", attempt: 1, loaded: 4096 }], sending.state) + + expect(sent.state).toMatchObject({ entries: [{ id: "u1", loaded: 1024, transfer: "sent" }] }) + expect(sent.effects).toEqual([{ type: "timer.clear", attempt: 1 }]) + expect(transitionUploads(sent.state, { type: "upload.timed-out", attempt: 1 }).state).toBe(sent.state) + expect(transitionUploads(sent.state, { type: "upload.succeeded", attempt: 1, path: "/tmp/u1.bin" })).toEqual({ + state: { status: "idle", issued: 1 }, + effects: [{ type: "upload.resolve", attempt: 1, path: "/tmp/u1.bin" }], + }) + }) + + test("closing a draft cancels only that draft's uploads", () => { + const result = replay([start("u1", scopeA), start("u2", scopeB), { type: "scope.cancelled", scope: scopeA }]) + + expect(result.state).toMatchObject({ status: "uploading", entries: [{ id: "u2", scope: scopeB }] }) + expect(result.effects).toEqual([ + { type: "upload.abort", attempt: 1 }, + { type: "upload.resolve", attempt: 1, path: undefined }, + ]) + }) + + test("a result for an upload that was cancelled or already settled is ignored", () => { + const cancelled = replay([start("u1", scopeA), { type: "upload.cancelled", id: "u1" }]) + + expect(cancelled.state).toEqual({ status: "idle", issued: 1 }) + expect(transitionUploads(cancelled.state, { type: "upload.failed", attempt: 1, error: new Error("x") }).state).toBe( + cancelled.state, + ) + expect(transitionUploads(cancelled.state, { type: "upload.cancelled", id: "u1" }).state).toBe(cancelled.state) + }) +}) + +describe("uploads", () => { + test("cancelling an upload drops it even when its work never settles", async () => { + const pending = uploads.track( + { id: "stalled", scope: scopeA, filename: "image.png", mime: "image/png", size: 1024 }, + () => new Promise(() => {}), + ) + + expect(uploads.items().map((item) => item.id)).toEqual(["stalled"]) + uploads.items()[0]?.cancel() + + expect(await pending).toBeUndefined() + expect(uploads.items()).toEqual([]) + }) + + test("an upload whose body stops advancing fails after the stall timeout instead of blocking sends", async () => { + jest.useFakeTimers() + + const pending = uploads.track( + { id: "hung", scope: scopeB, filename: "big.zip", mime: "application/zip", size: 1024 }, + (report) => { + report(100) + + return new Promise(() => {}) + }, + ) + + expect(uploads.forScope(scopeB).map((item) => item.id)).toEqual(["hung"]) + expect(uploads.forScope(scopeA)).toEqual([]) + jest.advanceTimersByTime(UPLOAD_STALL_TIMEOUT_MS) + + await expect(pending).rejects.toBe(UPLOAD_TIMED_OUT) + expect(uploads.forScope(scopeB)).toEqual([]) + }) }) diff --git a/packages/app/src/composer/attachments/uploads.tsx b/packages/app/src/composer/attachments/uploads.tsx index b8f5470b0483..e2b9aed45999 100644 --- a/packages/app/src/composer/attachments/uploads.tsx +++ b/packages/app/src/composer/attachments/uploads.tsx @@ -1,8 +1,19 @@ -import { createEffect, createRoot, For, on, onCleanup } from "solid-js" -import { createStore } from "solid-js/store" +import { createEffect, createRoot, createSignal, For, on, onCleanup, untrack } from "solid-js" +import { createStore, reconcile } from "solid-js/store" import { Icon } from "@opencode/ui/icon" import { Toast, toaster } from "@opencode/ui/toast" +import { abort } from "@opencode/util/abort" import { useLanguage } from "@/runtime/i18n/language" +import { + INITIAL_UPLOAD_MACHINE_STATE, + selectUploadEntries, + transitionUploads, + uploadPercent, + type UploadEntry, + type UploadScope, + type UploadMachineEffect, + type UploadMachineEvent, +} from "./upload-machine" export type Upload = { id: string @@ -13,39 +24,112 @@ export type Upload = { cancel: () => void } -// Uploads outlive the composer that started them, so one process-wide list feeds every chip +type UploadWork = (report: (loaded: number) => void, signal: AbortSignal) => Promise + +// Uploads outlive the composer that started them, so one process-wide machine feeds every chip // and the single progress toast. -const [state, setState] = createStore<{ items: Upload[] }>({ items: [] }) +const [machineState, setMachineState] = createSignal(INITIAL_UPLOAD_MACHINE_STATE) -export const uploads = { - items: () => state.items, - /** Runs `work` while the upload is listed. Resolves to undefined when the user cancels it. */ - async track( - input: Pick, - work: (report: (loaded: number) => void, signal: AbortSignal) => Promise, - ): Promise { - const controller = new AbortController() - - // The work may wait where it cannot observe the signal, such as a request queued behind - // others, so cancelling settles without it. - const cancelled = new Promise((resolve) => - controller.signal.addEventListener("abort", () => resolve(undefined), { once: true }), +// Rows keep their identity while progress streams, so a cancel button under the pointer is not replaced. +const [view, setView] = createStore<{ items: Upload[] }>({ items: [] }) + +type Run = { + work: UploadWork + result: PromiseWithResolvers + controller: AbortController + timer?: ReturnType +} + +const runs = new Map() + +// Handed from `track` to the `upload.run` effect its start causes in the same dispatch. +let starting: { work: UploadWork; result: PromiseWithResolvers } | undefined + +function dispatch(event: UploadMachineEvent) { + const previous = untrack(machineState) + const next = transitionUploads(previous, event) + + if (next.state !== previous) { + setMachineState(next.state) + setView("items", reconcile(selectUploadEntries(next.state).map(row), { key: "id" })) + } + + next.effects.forEach(run) +} + +function row(entry: UploadEntry): Upload { + return { + id: entry.id, + filename: entry.filename, + mime: entry.mime, + size: entry.size, + loaded: entry.loaded, + cancel: () => dispatch({ type: "upload.cancelled", id: entry.id }), + } +} + +function run(effect: UploadMachineEffect) { + const attempt = effect.attempt + + if (effect.type === "upload.run") { + if (!starting) return + const current: Run = { ...starting, controller: new AbortController() } + starting = undefined + runs.set(attempt, current) + void Promise.try(() => + current.work((loaded) => dispatch({ type: "upload.progress", attempt, loaded }), current.controller.signal), + ).then( + (path) => dispatch({ type: "upload.succeeded", attempt, path }), + (error) => dispatch({ type: "upload.failed", attempt, error }), ) - setState("items", (items) => [...items, { ...input, loaded: 0, cancel: () => controller.abort() }]) - - try { - return await Promise.race([ - work((loaded) => setState("items", (item) => item.id === input.id, "loaded", loaded), controller.signal), - cancelled, - ]) - } catch (error) { - if (controller.signal.aborted) return undefined - throw error - } finally { - setState("items", (items) => items.filter((item) => item.id !== input.id)) + return + } + + const current = runs.get(attempt) + + if (!current) return + clearTimeout(current.timer) + + if (effect.type === "timer.clear") return + + if (effect.type === "timer.reset") { + current.timer = setTimeout(() => dispatch({ type: "upload.timed-out", attempt }), effect.timeoutMs) + + return + } + + if (effect.type === "upload.abort") return abort(current.controller) + runs.delete(attempt) + + if (effect.type === "upload.resolve") return current.result.resolve(effect.path) + current.result.reject(effect.error) +} + +export const uploads = { + items: () => view.items, + /** Uploads in flight for one draft; they survive the composer view remounting. */ + forScope(scope: UploadScope) { + const ids = selectUploadEntries(machineState()).flatMap((entry) => (entry.scope === scope ? [entry.id] : [])) + + return view.items.filter((item) => ids.includes(item.id)) + }, + /** Runs `work` while the upload is listed and resolves to its path, or to undefined when it is cancelled. */ + track(input: Pick, work: UploadWork) { + const result = Promise.withResolvers() + starting = { work, result } + dispatch({ type: "upload.started", ...input }) + + // A duplicate id starts nothing. + if (starting) { + starting = undefined + result.resolve(undefined) } + + return result.promise }, + cancel: (id: string) => dispatch({ type: "upload.cancelled", id }), + cancelScope: (scope: UploadScope) => dispatch({ type: "scope.cancelled", scope }), } // Sonner builds toast content outside the app's Solid tree: no context and no owner. This host @@ -53,34 +137,45 @@ export const uploads = { // root of its own so progress stays reactive. export function UploadToastHost() { const language = useLanguage() - let active: { id: number; dispose: () => void } | undefined + let toast: { id: number; dispose: () => void } | undefined const dismiss = () => { - if (!active) return - toaster.dismiss(active.id) - active.dispose() - active = undefined + if (!toast) return + toaster.dismiss(toast.id) + toast.dispose() + toast = undefined } createEffect( on( - () => state.items.length > 0, + () => view.items.length > 0, (uploading) => { if (!uploading) return dismiss() - if (active) return + if (toast) return + let root: (() => void) | undefined const id = toaster.show( - (props) => - createRoot((dispose) => { - active = { id: props.toastId, dispose } + (props) => { + // Sonner renders the content again when the toast resizes; the previous root must not leak. + root?.() + + return createRoot((dispose) => { + root = dispose return - }), - { persistent: true, resize: () => state.items.length }, + }) + }, + { persistent: true, resize: () => view.items.length }, ) - active ??= { id, dispose: () => {} } + toast = { + id, + dispose: () => { + root?.() + root = undefined + }, + } }, ), ) @@ -90,12 +185,10 @@ export function UploadToastHost() { } function UploadToast(props: { toastId: number; language: ReturnType }) { - const percent = (item: Upload) => (item.size === 0 ? 100 : Math.floor((item.loaded / item.size) * 100)) - return ( - + {(item) => (
@@ -103,7 +196,7 @@ function UploadToast(props: { toastId: number; language: ReturnType - {props.language.t("prompt.toast.uploading.percent", { percent: percent(item) })} + {props.language.t("prompt.toast.uploading.percent", { percent: uploadPercent(item) })}
@@ -113,9 +206,9 @@ function UploadToast(props: { toastId: number; language: ReturnType -
+
diff --git a/packages/app/src/composer/editor/actions.test.ts b/packages/app/src/composer/editor/actions.test.ts index 9d3ebc5332d3..09fb2920468b 100644 --- a/packages/app/src/composer/editor/actions.test.ts +++ b/packages/app/src/composer/editor/actions.test.ts @@ -68,6 +68,32 @@ describe("Composer store", () => { expect(prompt.state.cursor).toBe(5) }) + test("removes text before the cursor without touching mentions or later text", () => { + const [state, setState] = createStore({ + prompt: [ + { type: "text", content: "A ", start: 0, end: 2 }, + { type: "file", path: "one", content: "@one", start: 2, end: 6 }, + { type: "text", content: " @ B", start: 6, end: 10 }, + ], + cursor: 8, + context: { items: [] }, + }) + + const prompt = createComposerEditorActions([state, setState]) + + prompt.removeTextBefore("/") + expect(prompt.state.cursor).toBe(8) + + prompt.removeTextBefore("@") + + expect(prompt.state.prompt).toEqual([ + { type: "text", content: "A ", start: 0, end: 2 }, + { type: "file", path: "one", content: "@one", start: 2, end: 6 }, + { type: "text", content: " B", start: 6, end: 9 }, + ]) + expect(prompt.state.cursor).toBe(7) + }) + test("mutates mentions, attachments, and context through editor actions", () => { const prompt = createPromptStore() diff --git a/packages/app/src/composer/editor/actions.ts b/packages/app/src/composer/editor/actions.ts index 9d07c455516c..2f3311f8dd56 100644 --- a/packages/app/src/composer/editor/actions.ts +++ b/packages/app/src/composer/editor/actions.ts @@ -30,35 +30,27 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) { const setStore = () => tuple()[1] - const clearRetry = () => { - if (untrack(() => store().retry) !== undefined) setStore()("retry", undefined) - } - return { get state() { return store() }, setPrompt(prompt: ComposerPrompt, cursor?: number) { - // Persisted setters encode on every call, even inside a reactive batch. - const update: Partial = { prompt, retry: undefined } - - if (cursor !== undefined) update.cursor = cursor - batch(() => setStore()(update)) + // Persisted setters encode on every call, even inside a reactive batch, so prompt and cursor go in one write. + batch(() => setStore()(cursor === undefined ? { prompt } : { prompt, cursor })) }, setCursor(cursor: number) { if (untrack(() => store().cursor) === cursor) return setStore()("cursor", cursor) }, setMode(mode: "normal" | "shell") { - if (untrack(() => store().mode === mode && store().retry === undefined)) return - setStore()({ mode, retry: undefined }) + if (untrack(() => (store().mode ?? "normal") === mode)) return + setStore()("mode", mode) }, setText(content: string) { batch(() => setStore()((state) => ({ prompt: [{ type: "text", content, start: 0, end: content.length }, ...state.prompt.filter(isAttachment)], cursor: content.length, - retry: undefined, })), ) }, @@ -68,13 +60,19 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) { setStore()((state) => ({ prompt: insertText(state.prompt, cursor, content), cursor: cursor + content.length, - retry: undefined, })), ) }, + // Removes `content` from just before the cursor, when it is there, leaving every other part as it was. + removeTextBefore(content: string) { + const cursor = store().cursor ?? promptLength(store().prompt) + const prompt = removeTextBefore(store().prompt, cursor, content) + + if (!prompt) return + batch(() => setStore()({ prompt, cursor: cursor - content.length })) + }, removeContext(key: string) { setStore()("context", "items", (items) => items.filter((item) => item.key !== key)) - clearRetry() }, addMention( mention: ComposerFilePart | ComposerAgentPart | ComposerSkillPart | ComposerSessionPart, @@ -93,11 +91,9 @@ export function createComposerEditorActions(input: ComposerStateStoreInput) { const start = range?.start ?? (part && index >= 0 ? part.start + index : end) setStore()("prompt", insertMention(prompt, start, end, mention)) setStore()("cursor", start + mention.content.length + 1) - clearRetry() }, removeAttachment(id: string) { setStore()("prompt", (parts) => parts.filter((part) => !isAttachment(part) || part.id !== id)) - clearRetry() }, } } @@ -131,6 +127,18 @@ function insertText(prompt: ComposerPrompt, cursor: number, content: string): Co return withOffsets(parts) } +function removeTextBefore(prompt: ComposerPrompt, cursor: number, content: string): ComposerPrompt | undefined { + const parts = withOffsets(prompt) + const index = parts.findIndex((item) => item.type === "text" && cursor > item.start && cursor <= item.end) + const part = parts[index] + + if (!part || isAttachment(part) || !part.content.slice(0, cursor - part.start).endsWith(content)) return + const offset = cursor - part.start + const next = { ...part, content: part.content.slice(0, offset - content.length) + part.content.slice(offset) } + + return withOffsets(parts.map((item, position) => (position === index ? next : item))) +} + function insertMention( prompt: ComposerPrompt, start: number, diff --git a/packages/app/src/composer/editor/dom.test.ts b/packages/app/src/composer/editor/dom.test.ts index 2665526621db..0a6f658516e7 100644 --- a/packages/app/src/composer/editor/dom.test.ts +++ b/packages/app/src/composer/editor/dom.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test" -import { setCursorPosition } from "./dom" +import type { ComposerPrompt } from "../types" +import { editorMatchesPrompt, getCursorPosition, isEditorDomBlank, isPromptInlineBlank, setCursorPosition } from "./dom" const br = () => document.createElement("br") @@ -51,7 +52,117 @@ test.each<{ name: string; nodes: () => Node[]; caret: [number, number | null, nu const selection = window.getSelection() expect(selection?.anchorNode).toBe(child === null ? container : container.childNodes[child]!) expect(selection?.anchorOffset).toBe(offset) + expect(getCursorPosition(container)).toBe(position) }) container.remove() }) + +test("reads a caret on or inside a mention as before or after it", () => { + const container = document.createElement("div") + const mention = pill() + container.append(text("ab"), mention, br(), text("cd")) + document.body.appendChild(container) + const selection = window.getSelection()! + + selection.collapse(mention.firstChild, 0) + expect(getCursorPosition(container)).toBe(2) + selection.collapse(mention.firstChild, 3) + expect(getCursorPosition(container)).toBe(7) + selection.collapse(container.childNodes[2]!, 0) + expect(getCursorPosition(container)).toBe(7) + + container.remove() +}) + +const part = (content: string) => ({ type: "text" as const, content, start: 0, end: 0 }) + +const filePart = { type: "file" as const, path: "src/a.ts", content: "@file", start: 0, end: 0 } + +const attachment = { type: "path" as const, id: "att", filename: "a.png", mime: "image/png", path: "/tmp/a.png" } + +const fileMention = () => { + const element = pill() + element.dataset.path = "src/a.ts" + + return element +} + +const editor = (...nodes: Node[]) => { + const element = document.createElement("div") + element.append(...nodes) + + return element +} + +const prompt = (...parts: ComposerPrompt): ComposerPrompt => parts + +test.each<{ name: string; dom: () => HTMLElement; prompt: ComposerPrompt; matches: boolean }>([ + { name: "one text node", dom: () => editor(text("hello")), prompt: prompt(part("hello")), matches: true }, + { + name: "split runs and breaks", + dom: () => editor(text("ab"), br(), text("cd")), + prompt: prompt(part("ab\ncd")), + matches: true, + }, + { + name: "adjacent text parts", + dom: () => editor(text("abcd")), + prompt: prompt(part("ab"), part("cd")), + matches: true, + }, + { + name: "a mention between text, with an attachment", + dom: () => editor(text("see "), fileMention(), text(" now")), + prompt: prompt(attachment, part("see "), filePart, part(" now")), + matches: true, + }, + { + name: "an empty editor and an empty prompt", + dom: () => editor(), + prompt: prompt(part(""), attachment), + matches: true, + }, + { name: "the store cleared the text", dom: () => editor(text("!")), prompt: prompt(part("")), matches: false }, + { name: "different text", dom: () => editor(text("hello")), prompt: prompt(part("help!")), matches: false }, + { + name: "a missing trailing part", + dom: () => editor(text("ab")), + prompt: prompt(part("ab"), filePart), + matches: false, + }, + { + name: "a mention with another target", + dom: () => editor(fileMention()), + prompt: prompt({ ...filePart, path: "src/b.ts" }), + matches: false, + }, + { name: "a break where the prompt has text", dom: () => editor(br()), prompt: prompt(part("a")), matches: false }, +])("matches the editor against the prompt: $name", (row) => { + expect(editorMatchesPrompt(row.dom(), row.prompt)).toBe(row.matches) +}) + +test("classifies blank editors and prompts the way the parser normalizes them", () => { + expect(isEditorDomBlank(editor(br(), text("\u200B\n")))).toBe(true) + expect(isEditorDomBlank(editor(text("a")))).toBe(false) + expect(isEditorDomBlank(editor(pill()))).toBe(false) + expect(isPromptInlineBlank(prompt(part(""), attachment))).toBe(true) + expect(isPromptInlineBlank(prompt(part(" ")))).toBe(false) + expect(isPromptInlineBlank(prompt(filePart))).toBe(false) +}) + +test("reads no caret for a range or a selection outside the editor", () => { + const container = document.createElement("div") + container.append(text("abcd")) + const outside = text("outside") + document.body.append(container, outside) + const selection = window.getSelection()! + + selection.setBaseAndExtent(container.firstChild!, 1, container.firstChild!, 3) + expect(getCursorPosition(container)).toBeUndefined() + selection.collapse(outside, 2) + expect(getCursorPosition(container)).toBeUndefined() + + container.remove() + outside.remove() +}) diff --git a/packages/app/src/composer/editor/dom.ts b/packages/app/src/composer/editor/dom.ts index 7ff5e15c2e92..e9950e43f6d8 100644 --- a/packages/app/src/composer/editor/dom.ts +++ b/packages/app/src/composer/editor/dom.ts @@ -1,7 +1,202 @@ +import { isAttachment } from "../prompt-parts" +import type { ComposerPrompt } from "../types" + +// Where `editorMatchesPrompt` is in the prompt: the part and the characters of it already matched. Module state so +// the per-keystroke walk allocates nothing; the walk is synchronous, so calls never interleave. +let matchPart = 0 + +let matchOffset = 0 + +/** + * Whether the editor shows `prompt`'s inline parts, read the way `parseComposerEditor` reads the DOM: text runs + * (split or not), `
` as a line break, mention pills by kind, label and target, and other elements by their + * content. Attachments and empty text parts are ignored. Reads every part when it matches, so a caller in an effect + * tracks in-place store updates. Runs on every keystroke, so it allocates nothing. + */ +export function editorMatchesPrompt(editor: HTMLElement, prompt: ComposerPrompt) { + matchPart = 0 + matchOffset = 0 + + for (let node = editor.firstChild; node; node = node.nextSibling) { + if (!matchNode(node, prompt)) return false + + // The parser joins block children with a line break. + if (node.nextSibling && node instanceof HTMLElement && (node.tagName === "DIV" || node.tagName === "P")) + if (!matchText("\n", prompt)) return false + } + + for (; matchPart < prompt.length; matchPart++, matchOffset = 0) { + const part = prompt[matchPart]! + + if (!isAttachment(part) && part.content.length > matchOffset) return false + } + + return true +} + +/** Whether the editor holds nothing but line breaks and zero-width spaces, which the parser reads as empty. */ +export function isEditorDomBlank(node: Node): boolean { + for (let child = node.firstChild; child; child = child.nextSibling) { + if (child instanceof Text) { + for (let index = 0; index < child.length; index++) { + const code = child.data.charCodeAt(index) + + if (code !== 0x0a && code !== 0x200b) return false + } + + continue + } + + if (!(child instanceof HTMLElement)) continue + + if (child.dataset.mention || (child.tagName !== "BR" && !isEditorDomBlank(child))) return false + } + + return true +} + +/** Whether `prompt` has no inline content: attachments only, or empty text. */ +export function isPromptInlineBlank(prompt: ComposerPrompt) { + for (let index = 0; index < prompt.length; index++) { + const part = prompt[index]! + + if (!isAttachment(part) && (part.type !== "text" || part.content.length > 0)) return false + } + + return true +} + +function matchNode(node: Node, prompt: ComposerPrompt): boolean { + if (node instanceof Text) return matchText(node.data, prompt) + + if (!(node instanceof HTMLElement)) return true + + if (node.dataset.mention) return matchMention(node, prompt) + + if (node.tagName === "BR") return matchText("\n", prompt) + + for (let child = node.firstChild; child; child = child.nextSibling) if (!matchNode(child, prompt)) return false + + return true +} + +function matchText(text: string, prompt: ComposerPrompt) { + let index = 0 + + while (index < text.length) { + const part = nextPart(prompt) + + if (part?.type !== "text") return false + const length = Math.min(text.length - index, part.content.length - matchOffset) + + // One native comparison covers a text node that lies inside one part, even a long draft. + const same = + index === 0 && length === text.length + ? part.content.startsWith(text, matchOffset) + : sameChars(text, index, part.content, matchOffset, length) + + if (!same) return false + index += length + matchOffset += length + } + + return true +} + +function matchMention(element: HTMLElement, prompt: ComposerPrompt) { + const part = nextPart(prompt) + + if (!part || part.type === "text" || isAttachment(part) || matchOffset !== 0) return false + const kind = part.type === "file" && part.mime === "application/x-directory" ? "reference" : part.type + const label = element.firstChild instanceof Text && !element.firstChild.nextSibling ? element.firstChild.data : null + + if (element.dataset.mention !== kind || (label ?? element.textContent) !== part.content) return false + + if (part.type === "session" && element.title !== part.id) return false + + if (part.type === "agent" && element.dataset.name !== part.name) return false + + if (part.type === "skill" && (element.dataset.id !== part.id || element.dataset.name !== part.name)) return false + + if ( + part.type === "file" && + (element.dataset.path !== part.path || + element.dataset.mime !== (part.mime || undefined) || + element.dataset.filename !== (part.filename || undefined)) + ) + return false + matchPart++ + + return true +} + +function sameChars(a: string, aStart: number, b: string, bStart: number, length: number) { + for (let offset = 0; offset < length; offset++) + if (a.charCodeAt(aStart + offset) !== b.charCodeAt(bStart + offset)) return false + + return true +} + +// The part the next character belongs to, past attachments and fully matched text. +function nextPart(prompt: ComposerPrompt) { + for (; matchPart < prompt.length; matchPart++, matchOffset = 0) { + const part = prompt[matchPart]! + + if (isAttachment(part)) continue + + if (part.type !== "text" || part.content.length > matchOffset) return part + } +} + function getNodeLength(node: Node): number { - if (node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR") return 1 + if (node instanceof Element && node.tagName === "BR") return 1 + + return textLength(node) +} + +// The node's text without zero-width spaces, like `textContent` but without building the string. +function textLength(node: Node): number { + if (node instanceof Text) return countText(node.data, node.length) + let length = 0 + + for (let child = node.firstChild; child; child = child.nextSibling) length += textLength(child) + + return length +} + +/** + * The collapsed caret's position in `parent`, counted the way `setCursorPosition` places it, or `undefined` when + * the selection is a range or lies outside `parent`. Runs on every `selectionchange`, so it allocates nothing. + */ +export function getCursorPosition(parent: HTMLElement) { + const selection = window.getSelection() + const anchor = selection?.anchorNode + + if (!selection?.isCollapsed || !anchor || !parent.contains(anchor)) return + const offset = selection.anchorOffset + let position = 0 + let index = 0 + + for (let node = parent.firstChild; node; node = node.nextSibling) { + if (anchor === parent && index === offset) return position + + if (node === anchor && node instanceof Text) return position + countText(node.data, offset) + + // Mentions and breaks are atomic: a caret on or inside one sits before or after it. + if (node.contains(anchor)) return offset === 0 ? position : position + getNodeLength(node) + position += getNodeLength(node) + index++ + } + + return position +} + +function countText(text: string, end: number) { + let count = 0 + + for (let index = 0; index < end; index++) if (text.charCodeAt(index) !== 0x200b) count++ - return (node.textContent ?? "").replace(/\u200B/g, "").length + return count } export function setCursorPosition(parent: HTMLElement, position: number) { @@ -11,8 +206,8 @@ export function setCursorPosition(parent: HTMLElement, position: number) { while (node) { const length = getNodeLength(node) const isText = node.nodeType === Node.TEXT_NODE - const isPill = node.nodeType === Node.ELEMENT_NODE && !!(node as HTMLElement).dataset.mention - const isBreak = node.nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName === "BR" + const isPill = node instanceof HTMLElement && !!node.dataset.mention + const isBreak = node instanceof Element && node.tagName === "BR" if (isText && remaining <= length) { const range = document.createRange() diff --git a/packages/app/src/composer/editor/editor.tsx b/packages/app/src/composer/editor/editor.tsx index 5ad18a04c92a..ee7d83556184 100644 --- a/packages/app/src/composer/editor/editor.tsx +++ b/packages/app/src/composer/editor/editor.tsx @@ -45,8 +45,18 @@ import type { ComposerSuggestion, } from "../types" import type { ComposerEditorModel, ComposerSelectControl } from "./interaction" -import { isAttachment } from "../prompt-parts" +import { isAttachment, promptLength } from "../prompt-parts" +import { editorMatchesPrompt, getCursorPosition, isEditorDomBlank, isPromptInlineBlank } from "./dom" +import { + INITIAL_EDITOR_SYNC_STATE, + INPUT_PARSED, + INPUT_PARSED_BLANK, + storeChanged, + transitionEditorSync, +} from "./machine" +import { composerHistoryPreviewHeight, composerPopoverActiveID, isComposerPopoverOpen } from "../suggestions/machine" import { QuoteCommentEditor } from "./quote-comment" +import { selectQuoteCommentView, type QuoteCommentController } from "../quote-comment-machine" import "../attachments/attachments.css" import "./editor.css" import "@/shell/palette-menu.css" @@ -98,7 +108,8 @@ export function ComposerEditor(props: ComposerEditorProps) { let controlsViewport!: HTMLDivElement let controlsContent!: HTMLDivElement const [overflow, setOverflow] = createStore({ start: false, end: false }) - const [historyLayout, setHistoryLayout] = createStore<{ height?: number }>({}) + // A history preview holds the composer at the height it had when the list opened. + const historyHeight = createMemo(() => composerHistoryPreviewHeight(state)) // Phones and tablets, whatever their width: a narrow desktop window keeps the desktop composer. const touch = createMediaQuery("(hover: none) and (pointer: coarse)") // The shell's slot at the bottom of the screen; without one (a story), the touch bar stays under the composer. @@ -107,11 +118,7 @@ export function ComposerEditor(props: ComposerEditorProps) { onMount(() => setDock(document.querySelector('[data-slot="composer-touch-bar-mount"]') ?? undefined)) createEffect(() => { - if (state.popover.type !== "history") setHistoryLayout("height", undefined) - }) - - createEffect(() => { - const preview = historyLayout.height !== undefined + const preview = historyHeight() !== undefined if (preview) props.controller.parts() @@ -138,7 +145,7 @@ export function ComposerEditor(props: ComposerEditorProps) { const [fadeBottom, setFadeBottom] = createSignal(0) const updateScroll = () => { - const scroller = historyLayout.height !== undefined ? content : viewport + const scroller = historyHeight() !== undefined ? content : viewport if (!scroller) return setFadeBottom(Math.min(16, Math.max(0, scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop))) @@ -158,14 +165,15 @@ export function ComposerEditor(props: ComposerEditorProps) { scrollObserver.disconnect() }) }) - let localInput = false + let sync = INITIAL_EDITOR_SYNC_STATE const updateCursor = () => { - if (!editor || !window.getSelection()?.isCollapsed) return - props.controller.onCursor(composerCursor(editor)) + const cursor = editor && getCursorPosition(editor) + + if (cursor !== undefined) props.controller.onCursor(cursor) } - const mode = createMemo(() => state.mode) + const mode = createMemo(() => props.controller.mode()) const buttons = createMemo(() => ({ opacity: mode() === "normal" ? 1 : 0, @@ -177,14 +185,15 @@ export function ComposerEditor(props: ComposerEditorProps) { const parts = props.controller.parts() if (!editor) return - - if (localInput) { - localInput = false - - return - } - - renderComposerEditor(editor, parts) + // The DOM already shows the user's own input and any update that leaves the text alone (an attachment), so + // neither rewrites it, which would move the caret and drop native undo. Each check reads every part, so an + // in-place store update runs this again. + const matches = editorMatchesPrompt(editor, parts) + const blank = !matches && isPromptInlineBlank(parts) && isEditorDomBlank(editor) + const step = transitionEditorSync(sync, storeChanged(matches, blank)) + sync = step.state + + if (step.render) renderComposerEditor(editor, parts) }) // Kept out of JSX: an inline ternary prop compiles to a memo created on every read, and the popover reads @@ -215,16 +224,19 @@ export function ComposerEditor(props: ComposerEditorProps) { event.currentTarget.value = "" }} /> - + props.controller.dispatch({ type: "popover.close" })} + history={state.popover.type === "history" ? mode() : undefined} + // Clicking into the draft keeps the previewed entry to edit; anywhere else cancels back to the draft. + onClose={(target) => + props.controller.dispatch({ type: editor?.contains(target) ? "popover.close" : "popover.dismiss" }) + } onActiveChange={(item) => props.controller.dispatch({ type: "popover.active", id: item.id })} onSelect={(item) => props.controller.dispatch({ type: "popover.select", item })} /> @@ -234,10 +246,10 @@ export function ComposerEditor(props: ComposerEditorProps) { data-component="composer" data-dock-border-underlay={props.borderUnderlay ? "true" : undefined} class="group/composer relative w-full overflow-clip rounded-xl bg-v2-background-bg-base" - style={{ height: historyLayout.height === undefined ? undefined : `${historyLayout.height}px` }} + style={{ height: historyHeight() === undefined ? undefined : `${historyHeight()}px` }} classList={{ "shadow-[var(--v2-elevation-raised)]": !props.borderUnderlay, - "flex flex-col": historyLayout.height !== undefined, + "flex flex-col": historyHeight() !== undefined, }} onSubmit={(event) => { event.preventDefault() @@ -251,13 +263,13 @@ export function ComposerEditor(props: ComposerEditorProps) {
- + props.controller.toggleContext(comment.key)} onCommentRemove={(comment) => props.controller.removeContext(comment.key)} onFileRemove={(file) => props.controller.removeContext(file.key)} - editingQuote={props.controller.editingQuote()} - quoteAnchor={props.controller.quoteAnchor()} + quoteComment={props.controller.quoteComment} onQuoteFocus={props.controller.focusQuotePrompt} - onEditQuote={props.controller.editQuote} onQuoteComment={(quote, comment) => props.controller.commentQuote(quote.key, comment)} quoteSubmit={view.submit.quote} searchPaths={props.controller.searchPaths} @@ -286,7 +296,7 @@ export function ComposerEditor(props: ComposerEditorProps) { data-component="composer-scroll" data-scrollable class="relative overflow-y-auto" - classList={{ "max-h-[180px]": historyLayout.height === undefined }} + classList={{ "max-h-[180px]": historyHeight() === undefined }} onScroll={updateScroll} ref={viewport} > @@ -300,28 +310,32 @@ export function ComposerEditor(props: ComposerEditorProps) { aria-multiline="true" aria-label={i18n.t("ui.promptInput.label")} aria-controls={state.popover.type === "history" ? suggestionsID : undefined} - dir={state.mode === "normal" ? "auto" : "ltr"} + dir={mode() === "normal" ? "auto" : "ltr"} contenteditable={!props.disabled && !props.readOnly} - autocapitalize={state.mode === "normal" ? "sentences" : "off"} - autocorrect={state.mode === "normal" ? "on" : "off"} + autocapitalize={mode() === "normal" ? "sentences" : "off"} + autocorrect={mode() === "normal" ? "on" : "off"} enterkeyhint={touch() ? "enter" : undefined} - spellcheck={state.mode === "normal"} + spellcheck={mode() === "normal"} // @ts-expect-error autocomplete="off" class="relative z-10 block w-full whitespace-pre-wrap bg-transparent ps-4 pe-[var(--composer-scroll-end)] pt-4 pb-2 text-[13px] font-[440] leading-5 text-v2-text-text-base focus:outline-none [&_[data-mention=file]]:text-syntax-property [&_[data-mention=agent]]:text-syntax-type [&_[data-mention=reference]]:text-v2-text-text-muted" - classList={{ "font-mono! tracking-[-0.04px]": state.mode === "shell", "opacity-50": props.disabled }} + classList={{ "font-mono! tracking-[-0.04px]": mode() === "shell", "opacity-50": props.disabled }} style={{ - "unicode-bidi": state.mode === "normal" ? "plaintext" : undefined, + "unicode-bidi": mode() === "normal" ? "plaintext" : undefined, "text-align": "start", }} onInput={(event) => { - const cursor = composerCursor(event.currentTarget) const prompt = parseComposerEditor(event.currentTarget) - const attachments = props.controller.parts().filter(isAttachment) - localInput = true + const cursor = getCursorPosition(event.currentTarget) ?? promptLength(prompt) + const parts = props.controller.parts() + sync = transitionEditorSync( + sync, + event.currentTarget.firstChild && isPromptInlineBlank(prompt) ? INPUT_PARSED_BLANK : INPUT_PARSED, + ).state + // Every keystroke runs this, so a plain text draft skips the copies a mixed one needs. props.controller.onInput( - prompt.map((part) => part.content).join(""), - [...prompt, ...attachments], + prompt.length === 1 ? prompt[0]!.content : prompt.map((part) => part.content).join(""), + parts.some(isAttachment) ? [...prompt, ...parts.filter(isAttachment)] : prompt, cursor, ) }} @@ -334,15 +348,11 @@ export function ComposerEditor(props: ComposerEditorProps) { // Capture the opening footprint before the controller applies its first history preview. const height = - state.popover.type === "closed" && event.shiftKey && event.key === "ArrowUp" + !isComposerPopoverOpen(state) && event.shiftKey && event.key === "ArrowUp" ? composer?.getBoundingClientRect().height : undefined - if (!view.draftOnly && props.controller.onKeyDown(event)) { - if (height !== undefined && state.popover.type === "history") setHistoryLayout("height", height) - - return - } + if (!view.draftOnly && props.controller.onKeyDown(event, height)) return const mod = event.metaKey || event.ctrlKey @@ -397,13 +407,13 @@ export function ComposerEditor(props: ComposerEditorProps) { />
{view.placeholder?.() ?? - (state.mode === "shell" + (mode() === "shell" ? i18n.t("ui.promptInput.placeholder.shell") : i18n.t("ui.promptInput.placeholder.normal", { slash: "/", at: "@" }))}
@@ -411,16 +421,16 @@ export function ComposerEditor(props: ComposerEditorProps) {
-
+
document.activeElement?.scrollIntoView({ block: "nearest", inline: "nearest" })} - aria-hidden={state.mode === "shell"} - inert={state.mode === "shell" ? true : undefined} + aria-hidden={mode() === "shell"} + inert={mode() === "shell" ? true : undefined} style={buttons()} >
@@ -480,13 +490,13 @@ export function ComposerEditor(props: ComposerEditorProps) {
- + - + diff --git a/packages/app/src/composer/editor/interaction.ts b/packages/app/src/composer/editor/interaction.ts index 21ce83f95309..eb11fa96edad 100644 --- a/packages/app/src/composer/editor/interaction.ts +++ b/packages/app/src/composer/editor/interaction.ts @@ -1,6 +1,6 @@ import { Predicate } from "effect" -import { createEffect, createMemo, createSignal, on, onCleanup, type Accessor } from "solid-js" -import { createStore, reconcile } from "solid-js/store" +import { createEffect, createMemo, createSignal, on, onCleanup, untrack, type Accessor } from "solid-js" +import { unwrap } from "solid-js/store" import { useFilteredList } from "@opencode/ui/hooks" import { abort } from "@opencode/util/abort" import { createComposerAttachments, type ComposerAttachmentConfig } from "../attachments/attachments" @@ -17,15 +17,32 @@ import type { ComposerSuggestion, } from "../types" import { + composerPopoverActiveID, createComposerInteractionState, + isComposerPopoverOpen, + selectComposerMode, transitionComposer, type ComposerInteractionCommand, type ComposerInteractionEvent, + type ComposerInteractionState, + type ComposerSavedDraft, } from "../suggestions/machine" +import { getCursorPosition, setCursorPosition } from "./dom" import { clonePrompt, isAttachment, promptLength } from "../prompt-parts" import type { ComposerDelivery, ComposerQueue } from "../adapter" import { isCommentItem } from "../state" -import type { ComposerQuoteAnchor } from "@opencode/plugin/gui" +import { createQuoteCommentController, type QuoteCommentController } from "../quote-comment-machine" +import { + INITIAL_MENTION_SEARCH_STATE, + isMentionFileStale, + selectMentionFiles, + selectMentionSessionsPending, + transitionMentionSearch, + type MentionSearchEffect, + type MentionSearchEvent, +} from "./mention-search-machine" + +const MENTION_CONTEXT_CLOSED: MentionSearchEvent = Object.freeze({ type: "context.closed" }) export type ComposerSelectControl = { options: Accessor @@ -67,32 +84,29 @@ export type ComposerEditorView = { } } -export function createComposerEditorState(mode: "normal" | "shell" = "normal") { - return createStore({ ...createComposerInteractionState(), mode }) -} +const DRAFT_EDITED: ComposerInteractionEvent = Object.freeze({ type: "draft.edited" }) + +const HISTORY_RESET: ComposerInteractionEvent = Object.freeze({ type: "history.reset" }) + +const NO_IDS: readonly string[] = Object.freeze([]) export function createComposerEditor(input: { store: ComposerStateStoreInput - state?: ReturnType history?: ComposerHistory commands: Accessor context: Accessor searchContextFiles: (query: string, signal?: AbortSignal) => ComposerSuggestion[] | Promise /** Reads reactively, so newly found sessions refresh the list without waiting on file search. */ searchSessions?: (query: string) => ComposerSuggestion[] - /** Whether the session search for this query has yet to settle; reads reactively. */ - sessionsPending?: (query: string) => boolean + /** Loads sessions matching `word` into what `searchSessions` reads; settles once they are in. */ + requestSessionSearch?: (word: string, signal: AbortSignal) => Promise openAttachment?: (attachment: ComposerAttachment, origin?: HTMLElement) => void /** An object URL for the image file at this path, which a path attachment references without its bytes. */ readImage?: (path: string) => Promise openContext?: (key: string) => void onContextRemove?: (item: ComposerComment) => void onQuoteComment?: (item: Extract, comment: string) => void - quoteComment?: { - key: Accessor - anchor?: Accessor - set: (key?: string) => void - } + quoteComment?: QuoteCommentController onEditor?: (element: HTMLElement) => void onSuggestionSelect?: (item: ComposerSuggestion) => (() => void) | void view: ComposerEditorView @@ -115,20 +129,50 @@ export function createComposerEditor(input: { if (cursor === undefined) return cancelFocus() - editor?.focus() - setEditorCursor(editor, cursor) + + if (!editor) return + editor.focus() + setCursorPosition(editor, cursor) } onCleanup(cancelFocus) const draft = createComposerEditorActions(input.store) - const [localQuoteComment, setLocalQuoteComment] = createSignal() - const quoteComment = input.quoteComment ?? { key: localQuoteComment, set: setLocalQuoteComment } - const [state, setState] = input.state ?? createComposerEditorState(draft.state.mode) - const [savedHistory, setSavedHistory] = createStore<{ entry?: ComposerHistoryEntry; cursor?: number }>({}) - const [cycle, setCycle] = createStore<{ index: number; entry?: ComposerHistoryEntry; cursor?: number }>({ index: -1 }) - const resetCycle = () => setCycle({ index: -1, entry: undefined, cursor: undefined }) + const quoteComment = input.quoteComment ?? createQuoteCommentController() + // A signal, not a store: the machine shares frozen states, which a store write would merge into and mutate. Memos + // keep readers of one field from rerunning when another changes. + const [readState, writeState] = createSignal(createComposerInteractionState()) + const popover = createMemo(() => readState().popover) + const drag = createMemo(() => readState().drag) + const focus = createMemo(() => readState().focus) + const activeContextID = createMemo(() => readState().activeContextID) - createEffect(on([() => draft.state, () => state.mode], resetCycle, { defer: true })) + const state: ComposerInteractionState = { + get popover() { + return popover() + }, + get drag() { + return drag() + }, + get focus() { + return focus() + }, + get activeContextID() { + return activeContextID() + }, + } + + // The draft holds the only copy of the mode, so hydration, queue edits and sends change it without the editor. + const mode = () => selectComposerMode(draft.state) + + createEffect(on(mode, (next) => dispatch({ type: "mode.synced", mode: next }), { defer: true })) + // Another draft replaces this one, so neither recalled history nor its saved draft applies to it. + createEffect( + on( + () => draft.state, + () => dispatch(HISTORY_RESET), + { defer: true }, + ), + ) function addPart(part: ComposerPersistedState["prompt"][number]) { if (isAttachment(part)) return false @@ -148,9 +192,13 @@ export function createComposerEditor(input: { ? createComposerAttachments({ ...input.attachments, capture: () => ({ + scope: unwrap(draft.state), current: () => draft.state.prompt, cursor: () => draft.state.cursor, - set: (prompt, cursor) => draft.setPrompt(prompt, cursor), + set: (prompt, cursor) => { + draft.setPrompt(prompt, cursor) + dispatch(DRAFT_EDITED) + }, }), editor: () => editor, focusEditor: () => editor?.focus(), @@ -159,9 +207,8 @@ export function createComposerEditor(input: { }) : undefined + // Recalled history stays recalled until a file is actually added, so a cancelled picker loses nothing. const attach = () => { - resetCycle() - if (!attachments) { input.view.add?.onAttach() @@ -175,47 +222,74 @@ export function createComposerEditor(input: { ) } - const [found, setFound] = createStore<{ query?: string; files: ComposerSuggestion[] }>({ files: [] }) - let fileQuery: string | undefined - let fileAbort = new AbortController() - onCleanup(() => abort(fileAbort)) + // Debounced and abortable: each keystroke or close replaces the pending searches instead of queueing behind them. + const [mentionSearch, setMentionSearch] = createSignal(INITIAL_MENTION_SEARCH_STATE) + const mentionRuns = new Map; controller?: AbortController }>() - // Debounced and abortable: each keystroke or close replaces the pending file search instead of queueing behind it. - // The last results stay listed until the next ones arrive, so the menu keeps its rows and height while typing. - const findFiles = (query?: string) => { - if (query === fileQuery) return - abort(fileAbort) - const controller = new AbortController() - fileQuery = query - fileAbort = controller + const dispatchMentionSearch = (event: MentionSearchEvent) => { + const previous = untrack(mentionSearch) + const next = transitionMentionSearch(previous, event) + + if (next.state !== previous) setMentionSearch(next.state) + next.effects.forEach(runMentionSearch) + } + + const runMentionSearch = (effect: MentionSearchEffect) => { + const attempt = effect.attempt - if (query === undefined || !query.trim() || /\s/.test(query)) { - if (found.files.length) setFound({ query: undefined, files: [] }) + if (effect.type === "file.debounce") { + mentionRuns.set(attempt, { + timer: setTimeout(() => dispatchMentionSearch({ type: "file.debounce.fired", attempt }), effect.delayMs), + }) return } - const timer = setTimeout( - () => - void Promise.resolve(input.searchContextFiles(query, controller.signal)).then( - (files) => !controller.signal.aborted && setFound({ query, files }), - () => undefined, - ), - 150, - ) + clearTimeout(mentionRuns.get(attempt)?.timer) + + if (effect.type === "file.abort" || effect.type === "session.abort") { + const controller = mentionRuns.get(attempt)?.controller + mentionRuns.delete(attempt) + + if (controller) abort(controller) + + return + } + + const controller = new AbortController() + + if (effect.type === "file.search") { + mentionRuns.set(attempt, { + controller, + timer: setTimeout(() => dispatchMentionSearch({ type: "file.timed-out", attempt }), effect.timeoutMs), + }) + void Promise.try(() => input.searchContextFiles(effect.query, controller.signal)).then( + (items) => dispatchMentionSearch({ type: "file.resolved", attempt, items }), + () => dispatchMentionSearch({ type: "file.failed", attempt }), + ) + + return + } - controller.signal.addEventListener("abort", () => clearTimeout(timer), { once: true }) + mentionRuns.set(attempt, { + controller, + timer: setTimeout(() => dispatchMentionSearch({ type: "session.timed-out", attempt }), effect.timeoutMs), + }) + // A failed search settles too: the titles already known still match locally. + const settled = () => dispatchMentionSearch({ type: "session.settled", attempt }) + void Promise.try(() => input.requestSessionSearch?.(effect.word, controller.signal)).then(settled, settled) } + createEffect(() => { + if (state.popover.type !== "context") return untrack(() => dispatchMentionSearch(MENTION_CONTEXT_CLOSED)) + const query = state.popover.query + untrack(() => dispatchMentionSearch({ type: "context.changed", query, hasSessions: !!input.requestSessionSearch })) + }) + onCleanup(() => dispatchMentionSearch({ type: "disposed" })) + const contextList = useFilteredList({ items: (query) => { - if (state.popover.type !== "context") { - findFiles(undefined) - - return [] - } - - findFiles(query) + if (state.popover.type !== "context") return [] const sessions = input.searchSessions?.(query) ?? [] @@ -227,7 +301,12 @@ export function createComposerEditor(input: { const seen = new Set(recent.map((item) => item.id)) - return [...fixed, ...sessions, ...recent, ...found.files.filter((item) => !seen.has(item.id))] + return [ + ...fixed, + ...sessions, + ...recent, + ...selectMentionFiles(mentionSearch()).filter((item) => !seen.has(item.id)), + ] }, key: (item) => item.id, filterKeys: ["label"], @@ -263,7 +342,7 @@ export function createComposerEditor(input: { const list = () => (state.popover.type === "context" ? contextList : commandList) const history = createMemo(() => - (input.history?.entries(state.mode) ?? []).map((entry, index) => ({ + (input.history?.entries(mode()) ?? []).map((entry, index) => ({ id: `history:${index}`, kind: "history", label: entry.prompt.map((part) => ("content" in part ? part.content : "")).join(""), @@ -274,7 +353,10 @@ export function createComposerEditor(input: { // Files from the previous query stay listed while the next search runs, but the keyboard can't highlight or pick them. const stale = (item: ComposerSuggestion) => - state.popover.type === "context" && item.kind === "file" && !item.recent && found.query !== state.popover.query + state.popover.type === "context" && + item.kind === "file" && + !item.recent && + isMentionFileStale(mentionSearch(), state.popover.query) const selectable = () => suggestions().flatMap((item) => (stale(item) ? [] : [item.id])) @@ -294,8 +376,24 @@ export function createComposerEditor(input: { return } + if (command.type === "history.apply") { + applyHistory(command.entry, { cursor: command.cursor }) + + return + } + if (command.type === "history.restore") { - if (savedHistory.entry) applyHistory(savedHistory.entry, { cursor: savedHistory.cursor }) + applyHistory(command.draft.entry, { cursor: command.draft.cursor, focus: command.focus }) + + return + } + + if (command.type === "draft.setMode") { + draft.setMode(command.mode) + + if (command.mode === "shell") input.view.shell?.onOpen() + + if (command.mode === "normal") input.view.shell?.onClose() return } @@ -312,6 +410,12 @@ export function createComposerEditor(input: { return } + if (command.type === "draft.removeTextBefore") { + draft.removeTextBefore(command.value) + + return + } + if (command.type === "mention.add") { if (command.item.mention) draft.addMention(command.item.mention, command.range) @@ -332,73 +436,41 @@ export function createComposerEditor(input: { return } - if (command.type === "focus.editor") { - if (state.popover.type === "history") return restoreFocus() - requestAnimationFrame(() => editor?.focus()) - } + if (command.type === "focus.editor") requestAnimationFrame(() => editor?.focus()) } + // Effects dispatch too, so neither the transition nor its commands subscribe the caller. function dispatch(event: ComposerInteractionEvent) { - if (event.type === "popover.active" && !selectable().includes(event.id)) return false - - if (event.type === "popover.close") cancelFocus() - - if ( - event.type === "history.open" || - event.type === "commands.open" || - event.type === "context.open" || - event.type === "popover.select" - ) - resetCycle() + return untrack(() => { + if (event.type === "popover.active" && !selectable().includes(event.id)) return false - if (event.type === "popover.select" && event.item.kind === "history") { - if (!event.item.history) return false - setState({ popover: { type: "closed" }, focus: "editor" }) - applyHistory(event.item.history) - setSavedHistory({ entry: undefined, cursor: undefined }) + if (event.type === "popover.close") cancelFocus() + const previous = readState() + const result = transitionComposer(previous, event, draft.state) + const action = event.type === "popover.select" ? input.onSuggestionSelect?.(event.item) : undefined - return true - } - - const mode = state.mode - const result = transitionComposer(state, event, draft.state) - const action = event.type === "popover.select" ? input.onSuggestionSelect?.(event.item) : undefined - - if (event.type === "popover.select") { - if (!action) result.commands.forEach(execute) + if (event.type === "popover.select") { + if (!action) result.commands.forEach(execute) - if (action && event.item.kind === "command" && state.popover.type !== "command-menu") { - draft.setPrompt(draft.state.prompt.filter(isAttachment), 0) + if (action && event.item.kind === "command" && previous.popover.type !== "command-menu") { + draft.setPrompt(draft.state.prompt.filter(isAttachment), 0) + } } - } - - setState(reconcile(result.state)) - - if (mode !== result.state.mode) draft.setMode(result.state.mode) - - if (event.type !== "popover.select") result.commands.forEach(execute) - if (state.popover.type !== "history") setSavedHistory({ entry: undefined, cursor: undefined }) + if (result.state !== previous) writeState(result.state) - if (mode !== result.state.mode) { - if (result.state.mode === "shell") input.view.shell?.onOpen() + if (event.type !== "popover.select") result.commands.forEach(execute) + action?.() - if (result.state.mode === "normal") input.view.shell?.onClose() - } - - if (event.type === "popover.select") { - if (!action) return result.handled - action() - } - - return result.handled + return result.handled + }) } - const onKeyDown = (event: KeyboardEvent) => { + const onKeyDown = (event: KeyboardEvent, height?: number) => { flushFocus() if ( - state.mode === "normal" && + mode() === "normal" && (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && @@ -410,19 +482,28 @@ export function createComposerEditor(input: { return true } - const handled = dispatch({ - type: "key.down", - key: event.key, - ctrl: event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey, - composing: event.isComposing, - ids: selectable(), - empty: draft.state.prompt.every((part) => !("content" in part) || part.content.length === 0), - }) + const ctrl = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey + const open = isComposerPopoverOpen(readState()) + + // Every keystroke lands here. With no list open only Escape, Backspace and Ctrl+G reach the machine, so typing + // neither lists suggestions nor builds an event. + const handled = + (open || event.key === "Escape" || event.key === "Backspace" || (ctrl && event.key.toLowerCase() === "g")) && + dispatch({ + type: "key.down", + key: event.key, + ctrl, + composing: event.isComposing, + ids: open ? selectable() : NO_IDS, + empty: + event.key === "Backspace" && + draft.state.prompt.every((part) => !("content" in part) || part.content.length === 0), + }) if (handled) event.preventDefault() - if (handled && event.key !== "Enter" && event.key !== "Tab" && state.popover.type !== "closed") { - const activeID = state.popover.activeID ?? "" + if (handled && event.key !== "Enter" && event.key !== "Tab" && isComposerPopoverOpen(readState())) { + const activeID = composerPopoverActiveID(readState()) ?? "" requestAnimationFrame(() => document.querySelector(`[data-suggestion-id="${CSS.escape(activeID)}"]`)?.scrollIntoView({ block: "nearest" }), ) @@ -432,7 +513,7 @@ export function createComposerEditor(input: { // The suggestion lists don't page, and a page key must not move the caret out of the query or page the timeline. if ( - state.popover.type !== "closed" && + isComposerPopoverOpen(readState()) && (event.key === "PageUp" || event.key === "PageDown") && !event.shiftKey && !event.altKey && @@ -471,7 +552,7 @@ export function createComposerEditor(input: { !event.isComposing && (event.key === "ArrowUp" || event.key === "ArrowDown") && (event.shiftKey - ? event.key === "ArrowUp" && openHistory() + ? event.key === "ArrowUp" && openHistory(height) : navigateHistory(event.key === "ArrowUp" ? "up" : "down")) ) { event.preventDefault() @@ -483,7 +564,7 @@ export function createComposerEditor(input: { } createEffect(() => { - if (state.popover.type === "closed") return + if (!isComposerPopoverOpen(state)) return const ids = selectable() if (state.popover.activeID ? state.popover.chosen && ids.includes(state.popover.activeID) : ids.length === 0) return @@ -494,7 +575,7 @@ export function createComposerEditor(input: { createEffect(() => { if (state.popover.type !== "context" || !/\s/.test(state.popover.query)) return - if (input.sessionsPending?.(state.popover.query)) return + if (selectMentionSessionsPending(mentionSearch(), state.popover.query, !!input.requestSessionSearch)) return if (contextList.grouped.state === "ready" && contextList.flat().length === 0) dispatch({ type: "popover.close" }) }) @@ -513,67 +594,43 @@ export function createComposerEditor(input: { if (options?.focus !== false) restoreFocus(cursor) } - const openHistory = () => { - if (state.popover.type !== "closed" || !editor || !history().length) return false + const captureDraft = (): ComposerSavedDraft => ({ + entry: { prompt: clonePrompt(draft.state.prompt), metadata: input.history?.capture?.() }, + cursor: draft.state.cursor, + }) + + const caretInEditor = (element: HTMLElement) => { const selection = window.getSelection() - if (!selection?.isCollapsed || !editor.contains(selection.anchorNode)) return false + return !!selection?.isCollapsed && element.contains(selection.anchorNode) + } + + // `height` is the composer's height before the first preview replaces the draft; the composer keeps it while open. + const openHistory = (height?: number) => { + if (isComposerPopoverOpen(readState()) || !editor || !history().length || !caretInEditor(editor)) return false if (draft.state.prompt.some((part) => "content" in part && part.content.length > 0)) return false - setSavedHistory({ - entry: { prompt: clonePrompt(draft.state.prompt), metadata: input.history?.capture?.() }, - cursor: draft.state.cursor, - }) - dispatch({ type: "history.open", id: history()[0]!.id }) - return true + return dispatch({ type: "history.open", id: history()[0]!.id, saved: captureDraft(), height }) } const navigateHistory = (direction: "up" | "down") => { - if (state.popover.type !== "closed" || !input.history || !editor) return false - const selection = window.getSelection() - - if (!selection?.isCollapsed || !editor.contains(selection.anchorNode)) return false + if (isComposerPopoverOpen(readState()) || !input.history || !editor || !caretInEditor(editor)) return false const text = draft.state.prompt.map((part) => ("content" in part ? part.content : "")).join("") - if (!canNavigateHistory(direction, text, editorCursor(editor), cycle.index >= 0)) return false - const entries = input.history.entries(state.mode) - - if (direction === "up") { - if (entries.length === 0 || cycle.index >= entries.length - 1) return false - - if (cycle.index === -1) { - setCycle({ - entry: { prompt: clonePrompt(draft.state.prompt), metadata: input.history.capture?.() }, - cursor: draft.state.cursor, - }) - } - - const index = cycle.index + 1 - setCycle("index", index) - applyHistory(entries[index]!, { cursor: 0 }) - - return true - } - - if (cycle.index < 0 || !cycle.entry) return false - - if (cycle.index > 0) { - const index = cycle.index - 1 - setCycle("index", index) - applyHistory(entries[index]!) - - return true - } - - applyHistory(cycle.entry, { cursor: cycle.cursor }) - resetCycle() - - return true + return dispatch({ + type: "history.step", + direction, + text, + cursor: getCursorPosition(editor) ?? text.length, + entries: input.history.entries(mode()), + capture: captureDraft, + }) } return { state, + mode, view: input.view, suggestions, dispatch, @@ -606,9 +663,7 @@ export function createComposerEditor(input: { dispatch({ type: "context.active", id }) input.openContext?.(id) }, - editingQuote: () => quoteComment.key(), - quoteAnchor: () => input.quoteComment?.anchor?.(), - editQuote: (key?: string) => quoteComment.set(key), + quoteComment, focusQuotePrompt: () => restoreFocus(), commentQuote(id: string, comment: string) { const item = draft.state.context.items.find((entry) => entry.key === id) @@ -619,11 +674,12 @@ export function createComposerEditor(input: { return (await input.searchContextFiles(query)).flatMap((item) => (item.path ? [item.path] : [])) }, removeContext(id: string) { - resetCycle() const item = draft.state.context.items.find((entry) => entry.key === id) if (item) input.onContextRemove?.(item) draft.removeContext(id) + quoteComment.retain(draft.state.context.items.map((entry) => entry.key)) + dispatch(DRAFT_EDITED) if (state.activeContextID === id) dispatch({ type: "context.active", id }) }, @@ -639,8 +695,8 @@ export function createComposerEditor(input: { return input.readImage?.(attachment.path) ?? Promise.resolve(undefined) }, removeAttachment(id: string) { - resetCycle() draft.removeAttachment(id) + dispatch(DRAFT_EDITED) }, canSubmit() { if (input.view.submit.available?.() === false) return false @@ -652,7 +708,7 @@ export function createComposerEditor(input: { if (attachments?.pending().length) return false const persisted = draft.state - if (state.mode === "shell") { + if (selectComposerMode(persisted) === "shell") { return persisted.prompt.some((part) => "content" in part && !!part.content.trim()) } @@ -669,7 +725,6 @@ export function createComposerEditor(input: { restoreFocus, onInput(value: string, prompt?: ComposerPersistedState["prompt"], cursor?: number) { cancelFocus() - resetCycle() if (prompt) draft.setPrompt(prompt, cursor) @@ -694,7 +749,6 @@ export function createComposerEditor(input: { if (input.view.draftOnly) return if (attachments?.pending().length) return - resetCycle() input.view.submit.onSubmit(options) dispatch({ type: "popover.close" }) }, @@ -702,20 +756,16 @@ export function createComposerEditor(input: { input.view.submit.onStop() }, addHistory(prompt: ComposerPersistedState["prompt"], mode: "normal" | "shell") { - resetCycle() input.history?.add(prompt, mode) }, resetHistory() { - resetCycle() - - if (state.popover.type === "history") dispatch({ type: "popover.close" }) + dispatch(HISTORY_RESET) }, onPaste(event: ClipboardEvent) { const clipboard = event.clipboardData const text = clipboard?.getData("text/plain") if (attachments && shouldHandlePasteAsAttachment(clipboard, !!input.attachments?.readClipboardImage)) { - resetCycle() void attachments.handlePaste(event) return @@ -779,7 +829,6 @@ export function createComposerEditor(input: { }, addAttachments(files: File[]) { if (!attachments) return - resetCycle() void attachments.addAttachments(files) restoreFocus() }, @@ -798,49 +847,3 @@ export function shouldHandlePasteAsAttachment(clipboard: DataTransfer | null, re return readClipboardImage } - -function canNavigateHistory(direction: "up" | "down", text: string, cursor: number, inHistory: boolean) { - const position = Math.max(0, Math.min(cursor, text.length)) - - if (inHistory) return position === 0 || position === text.length - - if (direction === "up") return position === 0 && text.length === 0 - - return position === text.length -} - -function editorCursor(editor: HTMLElement) { - const selection = window.getSelection() - - if (!selection?.rangeCount || !editor.contains(selection.anchorNode)) return editor.textContent?.length ?? 0 - const range = selection.getRangeAt(0).cloneRange() - range.selectNodeContents(editor) - range.setEnd(selection.anchorNode!, selection.anchorOffset) - - return range.toString().length -} - -function setEditorCursor(editor: HTMLElement | undefined, cursor: number) { - if (!editor) return - const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT) - let remaining = cursor - let node = walker.nextNode() - - while (node) { - const length = node.textContent?.length ?? 0 - - if (remaining <= length) { - const range = document.createRange() - range.setStart(node, remaining) - range.collapse(true) - const selection = window.getSelection() - selection?.removeAllRanges() - selection?.addRange(range) - - return - } - - remaining -= length - node = walker.nextNode() - } -} diff --git a/packages/app/src/composer/editor/machine.test.ts b/packages/app/src/composer/editor/machine.test.ts new file mode 100644 index 000000000000..0017db0cc494 --- /dev/null +++ b/packages/app/src/composer/editor/machine.test.ts @@ -0,0 +1,47 @@ +import { expect, test } from "bun:test" +import { + INITIAL_EDITOR_SYNC_STATE, + INPUT_PARSED, + INPUT_PARSED_BLANK, + storeChanged, + transitionEditorSync, + type EditorSyncEvent, + type EditorSyncTransition, +} from "./machine" + +function run(events: EditorSyncEvent[]) { + return events.reduce((step, event) => transitionEditorSync(step.state, event), { + state: INITIAL_EDITOR_SYNC_STATE, + render: false, + }) +} + +test("typing `!` renders the shell-mode clear that arrives in the same flush as the keystroke", () => { + // The DOM shows `!` while the store holds the cleared prompt. + expect(run([INPUT_PARSED, storeChanged(false, false)]).render).toBe(true) +}) + +test("an input the store never echoed does not swallow the next external update", () => { + const typed = run([INPUT_PARSED]) + expect(typed.render).toBe(false) + expect(transitionEditorSync(typed.state, storeChanged(false, false)).render).toBe(true) +}) + +test("the echo of a keystroke and an attachment edit leave the DOM alone", () => { + const echoed = run([INPUT_PARSED, storeChanged(true, false)]) + expect(echoed).toEqual({ state: INITIAL_EDITOR_SYNC_STATE, render: false }) + expect(transitionEditorSync(echoed.state, storeChanged(true, false))).toBe(echoed) +}) + +test("a blank echo keeps the user's line breaks once, and a later blank update renders", () => { + const blank = run([INPUT_PARSED_BLANK]) + expect(blank.state.status).toBe("local-blank") + + const echoed = transitionEditorSync(blank.state, storeChanged(false, true)) + expect(echoed).toEqual({ state: INITIAL_EDITOR_SYNC_STATE, render: false }) + expect(transitionEditorSync(echoed.state, storeChanged(false, true)).render).toBe(true) +}) + +test("typing text after a blank input returns to rendering every difference", () => { + expect(run([INPUT_PARSED_BLANK, INPUT_PARSED, storeChanged(false, true)]).render).toBe(true) +}) diff --git a/packages/app/src/composer/editor/machine.ts b/packages/app/src/composer/editor/machine.ts new file mode 100644 index 000000000000..56b6cb7ce00d --- /dev/null +++ b/packages/app/src/composer/editor/machine.ts @@ -0,0 +1,63 @@ +/** + * Whether a store change must render the prompt into the editable DOM. Runs on every keystroke, so states, events + * and results are frozen singletons. + * - `synced`: a store change renders whenever its inline parts differ from what the DOM shows. + * - `local-blank`: the user's input left only line breaks or zero-width spaces, which the parser reads as an empty + * prompt. The store's empty echo of that input keeps them, so Shift+Enter on an empty prompt and deleting its last + * character keep their line and native undo; any later empty update renders. + */ +export type EditorSyncState = { readonly status: "synced" } | { readonly status: "local-blank" } + +export type EditorSyncEvent = + /** The user edited the DOM; `blank` when the parser normalized what is left to an empty prompt. */ + | { readonly type: "input.parsed"; readonly blank: boolean } + /** + * The store's prompt changed. `matches` when the DOM already shows its inline parts; `blank` when both the DOM and + * the prompt are empty apart from line breaks and zero-width spaces. + */ + | { readonly type: "store.changed"; readonly matches: boolean; readonly blank: boolean } + +export type EditorSyncTransition = { + readonly state: EditorSyncState + readonly render: boolean +} + +const SYNCED: EditorSyncState = Object.freeze({ status: "synced" }) + +const LOCAL_BLANK: EditorSyncState = Object.freeze({ status: "local-blank" }) + +export const INITIAL_EDITOR_SYNC_STATE: EditorSyncState = SYNCED + +export const INPUT_PARSED = Object.freeze({ type: "input.parsed", blank: false }) satisfies EditorSyncEvent + +export const INPUT_PARSED_BLANK = Object.freeze({ type: "input.parsed", blank: true }) satisfies EditorSyncEvent + +const STORE_MATCHES = Object.freeze({ type: "store.changed", matches: true, blank: false }) satisfies EditorSyncEvent + +const STORE_BLANK = Object.freeze({ type: "store.changed", matches: false, blank: true }) satisfies EditorSyncEvent + +const STORE_DIFFERS = Object.freeze({ type: "store.changed", matches: false, blank: false }) satisfies EditorSyncEvent + +const STAY_SYNCED: EditorSyncTransition = Object.freeze({ state: SYNCED, render: false }) + +const STAY_LOCAL_BLANK: EditorSyncTransition = Object.freeze({ state: LOCAL_BLANK, render: false }) + +const RENDER: EditorSyncTransition = Object.freeze({ state: SYNCED, render: true }) + +/** The reused `store.changed` event for one comparison of the store's prompt with the DOM. */ +export function storeChanged(matches: boolean, blank: boolean): EditorSyncEvent { + if (matches) return STORE_MATCHES + + return blank ? STORE_BLANK : STORE_DIFFERS +} + +export function transitionEditorSync(state: EditorSyncState, event: EditorSyncEvent): EditorSyncTransition { + if (event.type === "input.parsed") return event.blank ? STAY_LOCAL_BLANK : STAY_SYNCED + + if (event.matches) return STAY_SYNCED + + // The blank echo of the user's own input, consumed once. + if (state.status === "local-blank" && event.blank) return STAY_SYNCED + + return RENDER +} diff --git a/packages/app/src/composer/editor/mention-search-machine.test.ts b/packages/app/src/composer/editor/mention-search-machine.test.ts new file mode 100644 index 000000000000..d8a39be8c6f3 --- /dev/null +++ b/packages/app/src/composer/editor/mention-search-machine.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, test } from "bun:test" +import type { ComposerSuggestion } from "../types" +import { + INITIAL_MENTION_SEARCH_STATE, + MENTION_FILE_DEBOUNCE_MS, + MENTION_SEARCH_TIMEOUT_MS, + isMentionFileStale, + selectMentionFiles, + selectMentionSessionsPending, + transitionMentionSearch, + type MentionSearchEvent, + type MentionSearchState, + type MentionSearchTransition, +} from "./mention-search-machine" + +const plan: ComposerSuggestion = { id: "file:re/plan.md", kind: "file", label: "re/plan.md", path: "re/plan.md" } + +function replay(events: MentionSearchEvent[], state: MentionSearchState = INITIAL_MENTION_SEARCH_STATE) { + const initial: MentionSearchTransition = { state, effects: [] } + + return events.reduce((result, event) => transitionMentionSearch(result.state, event), initial) +} + +function changed(query: string, hasSessions = true): MentionSearchEvent { + return { type: "context.changed", query, hasSessions } +} + +describe("transitionMentionSearch", () => { + test("reopening @ on a word searched before waits for a fresh session search", () => { + const reopened = replay([ + changed("auth"), + { type: "session.settled", attempt: 2 }, + { type: "context.closed" }, + changed("auth "), + ]) + + expect(reopened.effects).toEqual([ + { type: "session.search", attempt: 3, word: "auth", timeoutMs: MENTION_SEARCH_TIMEOUT_MS }, + ]) + expect(selectMentionSessionsPending(reopened.state, "auth ", true)).toBe(true) + expect( + selectMentionSessionsPending( + transitionMentionSearch(reopened.state, { type: "session.settled", attempt: 3 }).state, + "auth ", + true, + ), + ).toBe(false) + }) + + test("closing @ aborts its pending file and session searches", () => { + const loading = replay([changed("re"), { type: "file.debounce.fired", attempt: 1 }]) + + expect(loading.effects).toEqual([ + { type: "file.search", attempt: 1, query: "re", timeoutMs: MENTION_SEARCH_TIMEOUT_MS }, + ]) + expect(transitionMentionSearch(loading.state, { type: "context.closed" })).toEqual({ + state: { status: "closed", issued: 2 }, + effects: [ + { type: "file.abort", attempt: 1 }, + { type: "session.abort", attempt: 2 }, + ], + }) + }) + + test("a failed or timed-out file search clears the previous query's rows", () => { + const typed = replay([ + changed("re", false), + { type: "file.debounce.fired", attempt: 1 }, + { type: "file.resolved", attempt: 1, items: [plan] }, + changed("rez", false), + ]) + + expect(typed.effects).toEqual([{ type: "file.debounce", attempt: 2, delayMs: MENTION_FILE_DEBOUNCE_MS }]) + expect(selectMentionFiles(typed.state)).toEqual([plan]) + expect(isMentionFileStale(typed.state, "rez")).toBe(true) + + for (const type of ["file.failed", "file.timed-out"] as const) { + const settled = replay( + [ + { type: "file.debounce.fired", attempt: 2 }, + { type, attempt: 2 }, + ], + typed.state, + ) + + expect(selectMentionFiles(settled.state)).toEqual([]) + expect(isMentionFileStale(settled.state, "rez")).toBe(false) + expect(settled.effects).toEqual([{ type: "file.abort", attempt: 2 }]) + } + }) + + test("refining a title keeps the in-flight session search and drops file search", () => { + const first = replay([changed("auth")]) + const refined = transitionMentionSearch(first.state, changed("auth token")) + + expect(refined.effects).toEqual([{ type: "file.abort", attempt: 1 }]) + expect(refined.state).toMatchObject({ files: { status: "idle" }, sessions: { status: "loading", attempt: 2 } }) + expect(transitionMentionSearch(refined.state, changed("auth token")).state).toBe(refined.state) + }) + + test("ignores stale results and everything after dispose", () => { + const first = replay([changed("re", false), changed("res", false)]) + + expect(transitionMentionSearch(first.state, { type: "file.debounce.fired", attempt: 1 }).state).toBe(first.state) + + const disposed = transitionMentionSearch(first.state, { type: "disposed" }) + + expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "file.abort", attempt: 2 }] }) + expect(transitionMentionSearch(disposed.state, changed("re")).state).toBe(disposed.state) + }) +}) diff --git a/packages/app/src/composer/editor/mention-search-machine.ts b/packages/app/src/composer/editor/mention-search-machine.ts new file mode 100644 index 000000000000..2a6177af4b51 --- /dev/null +++ b/packages/app/src/composer/editor/mention-search-machine.ts @@ -0,0 +1,226 @@ +import type { ComposerSuggestion } from "../types" + +export const MENTION_FILE_DEBOUNCE_MS = 150 + +// A search that never answers settles as empty, so the menu cannot wait on it forever. +export const MENTION_SEARCH_TIMEOUT_MS = 10_000 + +/** + * The file search behind an open `@` menu. While the next query is `debouncing` or `loading`, the previous query's + * rows stay listed (`settledQuery`, `items`) so the menu keeps its height, but they cannot be picked. + */ +export type MentionFileSearchState = + | { readonly status: "idle" } + | { + readonly status: "debouncing" | "loading" + readonly attempt: number + readonly settledQuery: string | undefined + readonly items: readonly ComposerSuggestion[] + } + /** A failed or timed-out search settles with no rows. */ + | { readonly status: "settled"; readonly settledQuery: string; readonly items: readonly ComposerSuggestion[] } + +/** The server-side session search for the query's first word; titles then match the whole query locally. */ +export type MentionSessionSearchState = + | { readonly status: "disabled" } + | { readonly status: "loading"; readonly attempt: number; readonly word: string } + | { readonly status: "settled"; readonly word: string } + +/** + * The searches an `@` menu runs while it is open. + * - `closed`: no menu; closing aborts every search, so reopening on the same word searches again. + * - `active`: the menu shows `query`. + * - `disposed`: the composer unmounted; late results and timers are ignored. + */ +export type MentionSearchState = + | { readonly status: "closed"; readonly issued: number } + | { + readonly status: "active" + readonly issued: number + readonly query: string + readonly files: MentionFileSearchState + readonly sessions: MentionSessionSearchState + } + | { readonly status: "disposed" } + +export type MentionSearchEvent = + | { readonly type: "context.changed"; readonly query: string; readonly hasSessions: boolean } + | { readonly type: "context.closed" } + | { readonly type: "file.debounce.fired"; readonly attempt: number } + | { readonly type: "file.resolved"; readonly attempt: number; readonly items: readonly ComposerSuggestion[] } + | { readonly type: "file.failed"; readonly attempt: number } + | { readonly type: "file.timed-out"; readonly attempt: number } + | { readonly type: "session.settled"; readonly attempt: number } + | { readonly type: "session.timed-out"; readonly attempt: number } + | { readonly type: "disposed" } + +/** `file.abort` and `session.abort` also release a settled attempt's timer; aborting a settled request does nothing. */ +export type MentionSearchEffect = + | { readonly type: "file.debounce"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "file.search"; readonly attempt: number; readonly query: string; readonly timeoutMs: number } + | { readonly type: "file.abort"; readonly attempt: number } + | { readonly type: "session.search"; readonly attempt: number; readonly word: string; readonly timeoutMs: number } + | { readonly type: "session.abort"; readonly attempt: number } + +export type MentionSearchTransition = { + readonly state: MentionSearchState + readonly effects: readonly MentionSearchEffect[] +} + +export const INITIAL_MENTION_SEARCH_STATE: MentionSearchState = Object.freeze({ status: "closed", issued: 0 }) + +const DISPOSED: MentionSearchState = Object.freeze({ status: "disposed" }) + +const IDLE_FILES: MentionFileSearchState = Object.freeze({ status: "idle" }) + +const DISABLED_SESSIONS: MentionSessionSearchState = Object.freeze({ status: "disabled" }) + +const NO_EFFECTS: readonly MentionSearchEffect[] = Object.freeze([]) + +const NO_SUGGESTIONS: readonly ComposerSuggestion[] = Object.freeze([]) + +export function transitionMentionSearch(state: MentionSearchState, event: MentionSearchEvent): MentionSearchTransition { + if (state.status === "disposed") return stay(state) + + if (event.type === "disposed") + return { state: DISPOSED, effects: state.status === "active" ? abortSearches(state) : NO_EFFECTS } + + if (event.type === "context.changed") return change(state, event.query, event.hasSessions) + + if (state.status === "closed") return stay(state) + + if (event.type === "context.closed") + return { state: { status: "closed", issued: state.issued }, effects: abortSearches(state) } + + if (event.type === "session.settled" || event.type === "session.timed-out") { + if (state.sessions.status !== "loading" || state.sessions.attempt !== event.attempt) return stay(state) + + return { + state: { ...state, sessions: { status: "settled", word: state.sessions.word } }, + effects: [{ type: "session.abort", attempt: event.attempt }], + } + } + + const files = state.files + + if (event.type === "file.debounce.fired") { + if (files.status !== "debouncing" || files.attempt !== event.attempt) return stay(state) + + return { + state: { ...state, files: { ...files, status: "loading" } }, + effects: [ + { type: "file.search", attempt: event.attempt, query: state.query, timeoutMs: MENTION_SEARCH_TIMEOUT_MS }, + ], + } + } + + if (files.status !== "loading" || files.attempt !== event.attempt) return stay(state) + + return { + state: { + ...state, + files: { + status: "settled", + settledQuery: state.query, + items: event.type === "file.resolved" ? event.items : NO_SUGGESTIONS, + }, + }, + effects: [{ type: "file.abort", attempt: event.attempt }], + } +} + +/** The file rows to list: the current query's, or the previous query's while the next search runs. */ +export function selectMentionFiles(state: MentionSearchState) { + return state.status === "active" && state.files.status !== "idle" ? state.files.items : NO_SUGGESTIONS +} + +/** Whether listed file rows belong to an earlier query, so the keyboard cannot highlight or pick them. */ +export function isMentionFileStale(state: MentionSearchState, query: string) { + return state.status !== "active" || state.files.status === "idle" || state.files.settledQuery !== query +} + +/** Whether the session search for this query has yet to settle, so the menu must not close as empty yet. */ +export function selectMentionSessionsPending(state: MentionSearchState, query: string, hasSessions: boolean) { + if (!hasSessions || state.status === "disposed") return false + + if (state.status === "closed") return true + + if (state.sessions.status === "disabled") return false + + if (state.sessions.word !== mentionSearchWord(query)) return true + + return state.sessions.status === "loading" +} + +/** The server narrows sessions by the first word. */ +export function mentionSearchWord(query: string) { + return query.toLowerCase().split(" ")[0] ?? "" +} + +function change( + state: Exclude, + query: string, + hasSessions: boolean, +): MentionSearchTransition { + const active = state.status === "active" ? state : undefined + + if (active?.query === query && (active.sessions.status !== "disabled") === hasSessions) return stay(state) + const effects: MentionSearchEffect[] = [] + const issued = { value: state.issued } + const files = active?.query === query ? active.files : nextFiles(active?.files ?? IDLE_FILES, query, issued, effects) + const previous = active?.sessions ?? DISABLED_SESSIONS + const word = mentionSearchWord(query) + + const keep = hasSessions && previous.status !== "disabled" && previous.word === word + + if (!keep && previous.status === "loading") effects.push({ type: "session.abort", attempt: previous.attempt }) + + const sessions = keep ? previous : hasSessions ? startSessions(word, issued, effects) : DISABLED_SESSIONS + + return { state: { status: "active", issued: issued.value, query, files, sessions }, effects } +} + +function nextFiles( + previous: MentionFileSearchState, + query: string, + issued: { value: number }, + effects: MentionSearchEffect[], +): MentionFileSearchState { + if (previous.status === "debouncing" || previous.status === "loading") + effects.push({ type: "file.abort", attempt: previous.attempt }) + + // Only paths are searched: an empty query lists recent files, and a space means prose or a session title. + if (!query.trim() || /\s/.test(query)) return IDLE_FILES + const attempt = ++issued.value + effects.push({ type: "file.debounce", attempt, delayMs: MENTION_FILE_DEBOUNCE_MS }) + + return previous.status === "idle" + ? { status: "debouncing", attempt, settledQuery: undefined, items: NO_SUGGESTIONS } + : { status: "debouncing", attempt, settledQuery: previous.settledQuery, items: previous.items } +} + +function startSessions( + word: string, + issued: { value: number }, + effects: MentionSearchEffect[], +): MentionSessionSearchState { + const attempt = ++issued.value + effects.push({ type: "session.search", attempt, word, timeoutMs: MENTION_SEARCH_TIMEOUT_MS }) + + return { status: "loading", attempt, word } +} + +function abortSearches(state: Extract) { + const files: readonly MentionSearchEffect[] = + state.files.status === "debouncing" || state.files.status === "loading" + ? [{ type: "file.abort", attempt: state.files.attempt }] + : NO_EFFECTS + + return state.sessions.status === "loading" + ? [...files, { type: "session.abort" as const, attempt: state.sessions.attempt }] + : files +} + +function stay(state: MentionSearchState): MentionSearchTransition { + return { state, effects: NO_EFFECTS } +} diff --git a/packages/app/src/composer/editor/quote-comment.tsx b/packages/app/src/composer/editor/quote-comment.tsx index 0068fd54f1c2..fc806a61635f 100644 --- a/packages/app/src/composer/editor/quote-comment.tsx +++ b/packages/app/src/composer/editor/quote-comment.tsx @@ -8,6 +8,7 @@ import { MenuScroll } from "@opencode/ui/menu-scroll" import { useLanguage } from "@/runtime/i18n/language" import type { ComposerQuoteAnchor } from "@opencode/plugin/gui" import type { ComposerDelivery } from "../adapter" +import type { QuoteCommentView } from "../quote-comment-machine" const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform) @@ -25,28 +26,28 @@ export function QuoteCommentEditor(props: { anchor: HTMLElement source?: ComposerQuoteAnchor text: string + /** The saved comment. */ comment: string + view: QuoteCommentView mention: (query: string) => Promise + onInput: (draft: string) => void onSubmit: (comment: string) => void onClose: (focus?: boolean) => void send?: { available: boolean delivery: ComposerDelivery | undefined - onSubmit: (comment: string) => Promise + onSubmit: (comment: string) => void } }) { const language = useLanguage() const [state, setState] = createStore({ - draft: props.comment, rect: bounds(props.anchor), viewport: window.innerWidth, viewportHeight: window.innerHeight, revision: 0, height: 0, openingHeight: 0, - sending: false, - failed: false, }) const width = () => Math.min(WIDTH, state.viewport - GAP * 2) @@ -64,8 +65,6 @@ export function QuoteCommentEditor(props: { let frame: number | undefined - let mounted = true - const schedule = () => { if (frame !== undefined) return frame = requestAnimationFrame(() => { @@ -80,8 +79,6 @@ export function QuoteCommentEditor(props: { } onCleanup(() => { - mounted = false - if (frame !== undefined) cancelAnimationFrame(frame) }) @@ -93,7 +90,7 @@ export function QuoteCommentEditor(props: { if (target instanceof Node && (element?.contains(target) || props.anchor.contains(target))) return - if (!state.sending && state.draft.trim() === props.comment.trim()) props.onClose() + if (props.view.canDismissOutside) props.onClose() }) const left = () => Math.min(Math.max(source()?.left ?? state.rect.left, GAP), state.viewport - width() - GAP) @@ -118,16 +115,7 @@ export function QuoteCommentEditor(props: { label: language.t(sendLabels[send.delivery ?? "send"]), keys: [IS_MAC ? "⌘" : language.t("common.key.ctrl"), "⏎"], disabled: !send.available, - onSubmit: async (comment: string) => { - setState({ sending: true, failed: false }) - - const sent = await send.onSubmit(comment) - - if (!mounted) return - setState({ sending: false, failed: !sent }) - - if (sent) props.onClose() - }, + onSubmit: send.onSubmit, } }) @@ -163,17 +151,17 @@ export function QuoteCommentEditor(props: { setState("draft", value)} + value={props.view.draft} + onInput={props.onInput} onCancel={() => props.onClose(true)} onSubmit={props.onSubmit} - submitting={state.sending} + submitting={props.view.sending} alternateSubmit={alternateSubmit()} placeholder={language.t("session.quote.optionalCommentPlaceholder")} submitLabel={language.t( props.comment.trim() ? "common.save" - : state.draft.trim() + : props.view.draft.trim() ? "session.quote.addComment" : "session.quote.done", )} @@ -181,7 +169,7 @@ export function QuoteCommentEditor(props: { mention={{ items: props.mention }} selection={{props.text}} /> - +
` (`editor/editor.tsx`). @@ -606,7 +573,7 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? category: language.t("command.category.file"), keybind: "mod+u", editable: true, - disabled: controller.state.mode !== "normal", + disabled: mode() !== "normal", onSelect: () => controller.attach(), }, { @@ -614,21 +581,20 @@ export function createComposerModel(adapter: ComposerAdapter, options?: { queue? title: language.t("command.prompt.mode.toggle"), category: language.t("command.category.session"), keybind: "mod+shift+x", - onSelect: () => - void controller.dispatch({ type: controller.state.mode === "normal" ? "mode.shell" : "mode.normal" }), + onSelect: () => void controller.dispatch({ type: mode() === "normal" ? "mode.shell" : "mode.normal" }), }, { id: "prompt.mode.shell", title: language.t("command.prompt.mode.shell"), category: language.t("command.category.session"), - disabled: controller.state.mode === "shell", + disabled: mode() === "shell", onSelect: () => void controller.dispatch({ type: "mode.shell" }), }, { id: "prompt.mode.normal", title: language.t("command.prompt.mode.normal"), category: language.t("command.category.session"), - disabled: controller.state.mode === "normal", + disabled: mode() === "normal", onSelect: () => void controller.dispatch({ type: "mode.normal" }), }, ]) @@ -655,33 +621,11 @@ function openComment( item: { path: string; commentID?: string; commentOrigin?: "review" | "file" }, links: Links, session: MountedSession | undefined, - files: ReturnType, comments: ReturnType, ) { if (!item.commentID) return - const focus = { file: item.path, id: item.commentID } - comments.setActive(focus) - - const queueFocus = (attempts = 6) => { - requestAnimationFrame(() => { - comments.setFocus({ ...focus }) - - if (attempts <= 0) return - requestAnimationFrame(() => { - const current = comments.focus() - - if (current?.file === focus.file && current.id === focus.id) queueFocus(attempts - 1) - }) - }) - } - // The plugin that owns the comment's origin reveals it (the review diff or a file tab), keeping the conversation. + // It opens first, so a preview it replaces unmounts before the request, which then waits for the view to answer. links.open({ href: item.path, origin: item.commentOrigin, exact: true, background: true, session }) - - if (item.commentOrigin === "review") return queueFocus() - void Promise.resolve(files.load(item.path)).finally(() => queueFocus()) -} - -function firstWord(query: string) { - return query.toLowerCase().split(" ")[0] ?? "" + comments.open({ file: item.path, id: item.commentID }) } diff --git a/packages/app/src/composer/prompt-status-machine.test.ts b/packages/app/src/composer/prompt-status-machine.test.ts new file mode 100644 index 000000000000..75daa03b78d7 --- /dev/null +++ b/packages/app/src/composer/prompt-status-machine.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test } from "bun:test" +import { + SERVER_PROMPT_STATUS, + transitionPromptStatus, + type PromptStatusEvent, + type PromptStatusState, + type PromptStatusTransition, +} from "./prompt-status-machine" + +function replay(events: PromptStatusEvent[], state: PromptStatusState = SERVER_PROMPT_STATUS) { + const initial: PromptStatusTransition = { state, effects: [] } + + return events.reduce((result, event) => { + const next = transitionPromptStatus(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, initial) +} + +describe("transitionPromptStatus", () => { + test("a prompt that fails after a newer one went out leaves the newer prompt's turn running", () => { + const result = replay([ + { type: "dispatched", id: "msg_first", working: false }, + // The first prompt's optimistic status shows the Session as running when the second goes out. + { type: "dispatched", id: "msg_second", working: true }, + { type: "failed", id: "msg_first" }, + ]) + + expect(result.state).toEqual({ type: "optimistic", latest: "msg_second" }) + expect(result.effects).toEqual([{ type: "status.set", status: "running" }]) + + // The newest prompt owns the optimistic status, so its own failure still puts the Session back to idle. + expect(transitionPromptStatus(result.state, { type: "failed", id: "msg_second" })).toEqual({ + state: SERVER_PROMPT_STATUS, + effects: [{ type: "status.set", status: "idle" }], + }) + }) + + test("a prompt to an idle Session shows it running until the prompt fails", () => { + expect( + replay([ + { type: "dispatched", id: "msg_first", working: false }, + { type: "failed", id: "msg_first" }, + ]), + ).toEqual({ + state: SERVER_PROMPT_STATUS, + effects: [ + { type: "status.set", status: "running" }, + { type: "status.set", status: "idle" }, + ], + }) + }) + + test("once any prompt is admitted, a failure leaves the status to the server", () => { + const admitted = replay([ + { type: "dispatched", id: "msg_first", working: false }, + { type: "dispatched", id: "msg_second", working: true }, + { type: "admitted" }, + ]) + + expect(admitted.state).toBe(SERVER_PROMPT_STATUS) + expect(transitionPromptStatus(admitted.state, { type: "failed", id: "msg_second" })).toEqual({ + state: admitted.state, + effects: [], + }) + }) + + test("a prompt to a Session the server already reports running never touches its status", () => { + const result = replay([ + { type: "dispatched", id: "msg_first", working: true }, + { type: "failed", id: "msg_first" }, + ]) + + expect(result).toEqual({ state: SERVER_PROMPT_STATUS, effects: [] }) + }) +}) diff --git a/packages/app/src/composer/prompt-status-machine.ts b/packages/app/src/composer/prompt-status-machine.ts new file mode 100644 index 000000000000..289bfed1d651 --- /dev/null +++ b/packages/app/src/composer/prompt-status-machine.ts @@ -0,0 +1,48 @@ +/** + * Who owns a Session's busy status while this client's prompts to it are in flight. + * - `server`: the server's `session.execution.*` events own the status. + * - `optimistic`: a prompt dispatched to an idle Session marked it running before the server said so, and no prompt + * has been admitted since. `latest` is the newest prompt dispatched to the Session; only its failure puts the status + * back to idle, so an older prompt that fails cannot hide the turn a newer prompt started. + */ +export type PromptStatusState = { readonly type: "server" } | { readonly type: "optimistic"; readonly latest: string } + +export type PromptStatusEvent = + /** `working` is whether the Session already showed as running when the prompt went out. */ + | { readonly type: "dispatched"; readonly id: string; readonly working: boolean } + /** The server holds a prompt, so its events report the status from now on. */ + | { readonly type: "admitted" } + | { readonly type: "failed"; readonly id: string } + +export type PromptStatusEffect = { readonly type: "status.set"; readonly status: "running" | "idle" } + +export type PromptStatusTransition = { + readonly state: PromptStatusState + readonly effects: readonly PromptStatusEffect[] +} + +export const SERVER_PROMPT_STATUS: PromptStatusState = Object.freeze({ type: "server" }) + +const NO_EFFECTS: readonly PromptStatusEffect[] = Object.freeze([]) + +export function transitionPromptStatus(state: PromptStatusState, event: PromptStatusEvent): PromptStatusTransition { + if (event.type === "dispatched") { + if (!event.working) + return { + state: { type: "optimistic", latest: event.id }, + effects: [{ type: "status.set", status: "running" }], + } + + if (state.type === "server") return { state, effects: NO_EFFECTS } + + return { state: { type: "optimistic", latest: event.id }, effects: NO_EFFECTS } + } + + if (state.type === "server") return { state, effects: NO_EFFECTS } + + if (event.type === "admitted") return { state: SERVER_PROMPT_STATUS, effects: NO_EFFECTS } + + if (event.id !== state.latest) return { state, effects: NO_EFFECTS } + + return { state: SERVER_PROMPT_STATUS, effects: [{ type: "status.set", status: "idle" }] } +} diff --git a/packages/app/src/composer/quote-comment-machine.test.ts b/packages/app/src/composer/quote-comment-machine.test.ts new file mode 100644 index 000000000000..8c1583d791a7 --- /dev/null +++ b/packages/app/src/composer/quote-comment-machine.test.ts @@ -0,0 +1,154 @@ +import { afterEach, describe, expect, jest, test } from "bun:test" +import { createRoot } from "solid-js" +import { createMemoryComposerState } from "./state" +import { + INITIAL_QUOTE_COMMENT_STATE, + createQuoteCommentController, + selectQuoteCommentKey, + selectQuoteCommentView, + transitionQuoteComment, + type QuoteCommentEvent, + type QuoteCommentState, + type QuoteCommentTransition, +} from "./quote-comment-machine" + +const key = "quote:c=1" + +function replay(events: QuoteCommentEvent[], state: QuoteCommentState = INITIAL_QUOTE_COMMENT_STATE) { + const initial: QuoteCommentTransition = { state, effects: [] } + + return events.reduce((result, event) => { + const next = transitionQuoteComment(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, initial) +} + +afterEach(() => { + jest.useRealTimers() +}) + +describe("transitionQuoteComment", () => { + test("closes the editor when its quote leaves the draft, so restoring the quote does not reopen it", () => { + const result = replay([ + { type: "opened", key }, + { type: "retained", keys: ["file:a.ts"] }, + ]) + + expect(result.state).toEqual({ status: "closed", issued: 0 }) + expect(selectQuoteCommentKey(result.state)).toBeUndefined() + expect(replay([{ type: "retained", keys: [key] }], result.state).state).toBe(result.state) + }) + + test("a send that fails settles to failed and keeps the draft, and one that goes through closes", () => { + const sending = replay([ + { type: "opened", key }, + { type: "send.requested", draft: "note" }, + ]) + + expect(sending.state).toMatchObject({ status: "sending", attempt: 1, key, draft: "note" }) + expect(sending.effects).toEqual([{ type: "send.run", attempt: 1, key, draft: "note" }]) + + const failed = transitionQuoteComment(sending.state, { type: "send.settled", attempt: 1, sent: false }) + + expect(failed).toEqual({ + state: { status: "failed", issued: 1, key, draft: "note", anchor: undefined }, + effects: [], + }) + expect(selectQuoteCommentView(failed.state, key, "")).toMatchObject({ draft: "note", failed: true }) + expect(transitionQuoteComment(sending.state, { type: "send.settled", attempt: 1, sent: true }).state).toEqual({ + status: "closed", + issued: 1, + }) + }) + + test("ignores chip toggles, edits, a second send and a stale result while a send is in flight", () => { + const sending = replay([ + { type: "opened", key }, + { type: "send.requested", draft: "note" }, + ]).state + + for (const event of [ + { type: "closed" }, + { type: "opened", key: "quote:c=2" }, + { type: "draft.changed", draft: "other" }, + { type: "send.requested", draft: "note" }, + { type: "send.settled", attempt: 0, sent: false }, + ] satisfies QuoteCommentEvent[]) + expect(transitionQuoteComment(sending, event)).toEqual({ state: sending, effects: [] }) + }) + + test("ignores a late send result once the quote left, and an edit clears a failure", () => { + const closed = replay([ + { type: "opened", key }, + { type: "send.requested", draft: "note" }, + { type: "retained", keys: [] }, + ]) + + expect(transitionQuoteComment(closed.state, { type: "send.settled", attempt: 1, sent: false }).state).toBe( + closed.state, + ) + + const failed = replay([ + { type: "opened", key }, + { type: "send.requested", draft: "note" }, + { type: "send.settled", attempt: 1, sent: false }, + { type: "draft.changed", draft: "fixed" }, + ]) + + expect(failed.state).toEqual({ status: "open", issued: 1, key, draft: "fixed", anchor: undefined }) + }) + + test("disposing during a send ignores its late result and later events", () => { + const disposed = replay([{ type: "opened", key }, { type: "send.requested", draft: "note" }, { type: "disposed" }]) + + expect(disposed.state).toEqual({ status: "disposed" }) + expect(transitionQuoteComment(disposed.state, { type: "send.settled", attempt: 1, sent: false }).state).toBe( + disposed.state, + ) + expect(transitionQuoteComment(disposed.state, { type: "opened", key }).state).toBe(disposed.state) + }) +}) + +describe("createQuoteCommentController", () => { + test("a rejected send fails, and a slow one keeps sending until it goes through", async () => { + jest.useFakeTimers() + const controller = createQuoteCommentController() + + controller.set(key) + controller.send("note", () => Promise.reject(new Error("offline"))) + expect(controller.state().status).toBe("sending") + await Promise.resolve() + await Promise.resolve() + expect(controller.state()).toMatchObject({ status: "failed", draft: "note" }) + + // The request layer gives up on a silent server after a minute and the prompt send retries once, so a send that + // the composer still runs must not show as failed: the user would retry it while the first one may still land. + const slow = Promise.withResolvers() + controller.send("note", () => slow.promise) + jest.advanceTimersByTime(5 * 60_000) + expect(controller.state()).toMatchObject({ status: "sending", draft: "note" }) + slow.resolve(true) + await Promise.resolve() + await Promise.resolve() + expect(controller.state()).toEqual({ status: "closed", issued: 2 }) + }) + + test("removing a quote from the composer closes its editor and highlight before a failed send restores it", () => { + createRoot((dispose) => { + const composer = createMemoryComposerState() + const quote = { type: "quote" as const, text: "passage", commentID: "1" } + + composer.context.add(quote) + composer.quoteSource.add(key, [{ partID: "part", revealID: "message", start: 0, end: 7, text: "passage" }]) + composer.quoteComment.set(key) + expect(composer.quoteSource.state.pending).toBe(key) + + composer.context.remove(key) + composer.context.add(quote) + expect(composer.quoteComment.key()).toBeUndefined() + expect(composer.quoteSource.state.pending).toBeUndefined() + dispose() + }) + }) +}) diff --git a/packages/app/src/composer/quote-comment-machine.ts b/packages/app/src/composer/quote-comment-machine.ts new file mode 100644 index 000000000000..ed2cbc4f404d --- /dev/null +++ b/packages/app/src/composer/quote-comment-machine.ts @@ -0,0 +1,211 @@ +import { createSignal, getOwner, onCleanup, untrack } from "solid-js" +import type { ComposerQuoteAnchor } from "@opencode/plugin/gui" +import type { QuoteSource } from "./quote-source" + +/** + * The quote whose comment editor is open, and its send. + * - `closed`: no editor is open. + * - `open`: the editor shows `key`; `draft` stays `undefined` until the user edits, so the saved comment shows. + * - `sending`: a direct send of `draft` is in flight; the editor stays open and ignores chip toggles and edits. + * It ends only when the composer's submit settles, which the request layer bounds. A timeout of its own would + * report a failure while the composer still sends, and a retry then could post the quote twice. + * - `failed`: the send did not go through; the editor keeps the draft and shows an alert until the next edit. + * - `disposed`: the composer state was evicted; late results are ignored. + */ +export type QuoteCommentState = + | { readonly status: "closed"; readonly issued: number } + | { + readonly status: "open" + readonly issued: number + readonly key: string + readonly draft: string | undefined + readonly anchor: ComposerQuoteAnchor | undefined + } + | { + readonly status: "sending" + readonly issued: number + readonly attempt: number + readonly key: string + readonly draft: string + readonly anchor: ComposerQuoteAnchor | undefined + } + | { + readonly status: "failed" + readonly issued: number + readonly key: string + readonly draft: string + readonly anchor: ComposerQuoteAnchor | undefined + } + | { readonly status: "disposed" } + +export type QuoteCommentEvent = + | { readonly type: "opened"; readonly key: string; readonly anchor?: ComposerQuoteAnchor } + | { readonly type: "closed" } + | { readonly type: "draft.changed"; readonly draft: string } + | { readonly type: "send.requested"; readonly draft: string } + | { readonly type: "send.settled"; readonly attempt: number; readonly sent: boolean } + /** The context items still in the draft; an editor whose quote is gone closes. */ + | { readonly type: "retained"; readonly keys: readonly string[] } + | { readonly type: "disposed" } + +export type QuoteCommentEffect = { + readonly type: "send.run" + readonly attempt: number + readonly key: string + readonly draft: string +} + +export type QuoteCommentTransition = { + readonly state: QuoteCommentState + readonly effects: readonly QuoteCommentEffect[] +} + +export type QuoteCommentView = { + readonly draft: string + readonly sending: boolean + readonly failed: boolean + /** A pointer down outside closes the editor only when nothing would be lost. */ + readonly canDismissOutside: boolean +} + +export const INITIAL_QUOTE_COMMENT_STATE: QuoteCommentState = Object.freeze({ status: "closed", issued: 0 }) + +const NO_EFFECTS: readonly QuoteCommentEffect[] = Object.freeze([]) + +export function transitionQuoteComment(state: QuoteCommentState, event: QuoteCommentEvent): QuoteCommentTransition { + if (state.status === "disposed") return stay(state) + + if (event.type === "disposed") return { state: { status: "disposed" }, effects: NO_EFFECTS } + + if (event.type === "retained") { + if (state.status === "closed" || event.keys.includes(state.key)) return stay(state) + + return { state: { status: "closed", issued: state.issued }, effects: NO_EFFECTS } + } + + if (state.status === "sending") { + if (event.type !== "send.settled" || event.attempt !== state.attempt) return stay(state) + + if (event.sent) return { state: { status: "closed", issued: state.issued }, effects: NO_EFFECTS } + + return { + state: { status: "failed", issued: state.issued, key: state.key, draft: state.draft, anchor: state.anchor }, + effects: NO_EFFECTS, + } + } + + if (event.type === "opened") { + if (state.status !== "closed" && state.key === event.key) { + if (state.anchor === event.anchor) return stay(state) + + return { state: { ...state, anchor: event.anchor }, effects: NO_EFFECTS } + } + + return { + state: { status: "open", issued: state.issued, key: event.key, draft: undefined, anchor: event.anchor }, + effects: NO_EFFECTS, + } + } + + if (state.status === "closed") return stay(state) + + if (event.type === "closed") return { state: { status: "closed", issued: state.issued }, effects: NO_EFFECTS } + + if (event.type === "draft.changed") { + if (state.status === "open" && state.draft === event.draft) return stay(state) + + return { + state: { status: "open", issued: state.issued, key: state.key, draft: event.draft, anchor: state.anchor }, + effects: NO_EFFECTS, + } + } + + if (event.type === "send.requested") { + const attempt = state.issued + 1 + + return { + state: { status: "sending", issued: attempt, attempt, key: state.key, draft: event.draft, anchor: state.anchor }, + effects: [{ type: "send.run", attempt, key: state.key, draft: event.draft }], + } + } + + return stay(state) +} + +/** The quote whose editor is open, or `undefined`. */ +export function selectQuoteCommentKey(state: QuoteCommentState) { + return state.status === "closed" || state.status === "disposed" ? undefined : state.key +} + +export function selectQuoteCommentAnchor(state: QuoteCommentState) { + return state.status === "closed" || state.status === "disposed" ? undefined : state.anchor +} + +/** The quote whose timeline source stays highlighted: the open editor's, when it has a source. */ +export function selectQuoteHighlightKey( + key: string | undefined, + sources: Readonly>, +) { + return key && sources[key]?.length ? key : undefined +} + +export function selectQuoteCommentView(state: QuoteCommentState, key: string, saved: string): QuoteCommentView { + const current = state.status !== "closed" && state.status !== "disposed" && state.key === key ? state : undefined + const draft = current?.draft ?? saved + const sending = current?.status === "sending" + + return { + draft, + sending, + failed: current?.status === "failed", + canDismissOutside: !sending && draft.trim() === saved.trim(), + } +} + +export type QuoteCommentController = ReturnType + +export function createQuoteCommentController() { + const [state, setState] = createSignal(INITIAL_QUOTE_COMMENT_STATE) + // Handed from `send` to the `send.run` effect it causes in the same dispatch. + let submit: ((key: string, comment: string) => Promise) | undefined + + const dispatch = (event: QuoteCommentEvent) => { + const previous = untrack(state) + const next = transitionQuoteComment(previous, event) + + if (next.state !== previous) setState(next.state) + next.effects.forEach(run) + } + + const run = (effect: QuoteCommentEffect) => { + const send = submit + submit = undefined + + if (!send) return dispatch({ type: "send.settled", attempt: effect.attempt, sent: false }) + void Promise.try(() => send(effect.key, effect.draft)).then( + (sent) => dispatch({ type: "send.settled", attempt: effect.attempt, sent }), + () => dispatch({ type: "send.settled", attempt: effect.attempt, sent: false }), + ) + } + + if (getOwner()) onCleanup(() => dispatch({ type: "disposed" })) + + return { + state, + key: () => selectQuoteCommentKey(state()), + anchor: () => selectQuoteCommentAnchor(state()), + set: (key?: string, anchor?: ComposerQuoteAnchor) => + dispatch(key ? { type: "opened", key, anchor } : { type: "closed" }), + retain: (keys: readonly string[]) => dispatch({ type: "retained", keys }), + setDraft: (draft: string) => dispatch({ type: "draft.changed", draft }), + send: (draft: string, send: (key: string, comment: string) => Promise) => { + submit = send + dispatch({ type: "send.requested", draft }) + submit = undefined + }, + } +} + +function stay(state: QuoteCommentState): QuoteCommentTransition { + return { state, effects: NO_EFFECTS } +} diff --git a/packages/app/src/composer/quote-source.ts b/packages/app/src/composer/quote-source.ts index 44403bbecf1e..5325a06bf7e9 100644 --- a/packages/app/src/composer/quote-source.ts +++ b/packages/app/src/composer/quote-source.ts @@ -1,23 +1,34 @@ import { createStore } from "solid-js/store" +import { selectQuoteHighlightKey } from "./quote-comment-machine" import type { ComposerStore, TimelineQuoteSource } from "./schema" /** App-only source coordinates, persisted with drafts but never included in requests. */ export type QuoteSource = TimelineQuoteSource -export function createComposerQuoteSource(draft?: { - get: () => ComposerStore["quoteSources"] - set: (key: string, source: QuoteSource | undefined) => void -}) { +export function createComposerQuoteSource( + draft?: { + get: () => ComposerStore["quoteSources"] + set: (key: string, source: QuoteSource | undefined) => void + }, + quoteComment?: { + /** The quote whose comment editor is open. */ + key: () => string | undefined + retain: (keys: readonly string[]) => void + }, +) { const [sources, setSources] = createStore>({}) - const [state, setState] = createStore<{ + const [state] = createStore<{ sources: Record /** The quote whose open comment editor keeps its source highlighted. */ - pending?: string + pending: string | undefined }>({ get sources() { return draft?.get() ?? sources }, + get pending() { + return selectQuoteHighlightKey(quoteComment?.key(), draft?.get() ?? sources) + }, }) const setSource = (key: string, source: QuoteSource | undefined) => @@ -26,14 +37,12 @@ export function createComposerQuoteSource(draft?: { return { state, add: (key: string, source: QuoteSource) => setSource(key, source), - pend: (key: string) => setState("pending", key), - settle: () => setState("pending", undefined), retain: (keys: string[]) => { Object.keys(state.sources).forEach((key) => { if (!keys.includes(key)) setSource(key, undefined) }) - if (state.pending && !keys.includes(state.pending)) setState("pending", undefined) + quoteComment?.retain(keys) }, } } diff --git a/packages/app/src/composer/reload-machine.ts b/packages/app/src/composer/reload-machine.ts new file mode 100644 index 000000000000..639daea86172 --- /dev/null +++ b/packages/app/src/composer/reload-machine.ts @@ -0,0 +1,51 @@ +/** + * `/reload`: one server-wide configuration reload at a time. The request queue already ends a reload whose server + * stops answering, and the reply carries no body, so `reloading` always settles. + */ +export type ConfigReloadState = + | { readonly status: "idle"; readonly issued: number } + | { readonly status: "reloading"; readonly attempt: number } + +export type ConfigReloadEvent = + | { readonly type: "reload.requested" } + | { readonly type: "reload.succeeded"; readonly attempt: number } + | { readonly type: "reload.failed"; readonly attempt: number; readonly cause: unknown } + +export type ConfigReloadEffect = + | { readonly type: "reload.run"; readonly attempt: number } + | { readonly type: "toast.pending.show" } + | { readonly type: "toast.pending.dismiss" } + | { readonly type: "toast.succeeded" } + | { readonly type: "toast.failed"; readonly cause: unknown } + +export type ConfigReloadTransition = { + readonly state: ConfigReloadState + readonly effects: readonly ConfigReloadEffect[] +} + +export function createConfigReloadState(): ConfigReloadState { + return { status: "idle", issued: 0 } +} + +export function transitionConfigReload(state: ConfigReloadState, event: ConfigReloadEvent): ConfigReloadTransition { + if (event.type === "reload.requested") { + // A second `/reload` while one runs joins it: the server is already rebuilding every location. + if (state.status === "reloading") return { state, effects: [] } + const attempt = state.issued + 1 + + return { + state: { status: "reloading", attempt }, + effects: [{ type: "toast.pending.show" }, { type: "reload.run", attempt }], + } + } + + if (state.status !== "reloading" || state.attempt !== event.attempt) return { state, effects: [] } + + return { + state: { status: "idle", issued: state.attempt }, + effects: [ + { type: "toast.pending.dismiss" }, + event.type === "reload.succeeded" ? { type: "toast.succeeded" } : { type: "toast.failed", cause: event.cause }, + ], + } +} diff --git a/packages/app/src/composer/retry.test.ts b/packages/app/src/composer/retry.test.ts new file mode 100644 index 000000000000..7bad382ff56b --- /dev/null +++ b/packages/app/src/composer/retry.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, test } from "bun:test" +import { SessionMessage } from "@opencode/schema/session-message" +import { claimRetry, retryFingerprint, type ComposerRetryPayload } from "./retry" +import { contextItemKey, durableNote, type ContextItem, type ImageAttachmentPart } from "./schema" + +const note = { + type: "note" as const, + origin: "browser", + label: "button#save", + icon: "select-element", + subject: 'the "button#save" element', + href: "tab_1", + live: { subject: 'the "button#save" element (browser ref @e42)', href: "tab_1#e42" }, + comment: "Rename this", + commentID: "note", +} + +const image: ImageAttachmentPart = { + type: "image", + id: "shot", + filename: "shot.png", + mime: "image/png", + blob: { id: "media:abc", url: "blob:resolved" }, +} + +const keyed = (items: ContextItem[]) => items.map((item) => ({ ...item, key: contextItemKey(item) })) + +const text = (content: string) => ({ type: "text" as const, content, start: 0, end: content.length }) + +const payload: ComposerRetryPayload = { + mode: "normal", + delivery: "steer", + selection: { agent: "build", model: { providerID: "anthropic", modelID: "claude" }, variant: "high" }, + prompt: [text("first"), image], + context: keyed([note, { type: "file", path: "src/app.ts", comment: "Check this", commentID: "c1" }]), +} + +const id = SessionMessage.ID.create() + +const fresh = SessionMessage.ID.create() + +const armed = { id, fingerprint: retryFingerprint(payload) } + +describe("composer retry", () => { + test("resends an unchanged payload under the failed prompt's ID", () => { + expect(claimRetry(armed, payload, fresh)).toBe(id) + expect(claimRetry(undefined, payload, fresh)).toBe(fresh) + }) + + test.each<{ name: string; next: ComposerRetryPayload }>([ + // The server keeps the first payload under an ID, so each of these would silently drop the change. + { + name: "a note whose live subject changed", + next: { ...payload, context: keyed([{ ...note, live: { subject: "the button (browser ref @e7)" } }]) }, + }, + { name: "a note that lost its live subject on reload", next: { ...payload, context: keyed([durableNote(note)]) } }, + { name: "another delivery", next: { ...payload, delivery: "queue" } }, + { name: "a queue edit merged into the prompt", next: { ...payload, prompt: [text("first\n\nsecond"), image] } }, + { name: "another agent", next: { ...payload, selection: { ...payload.selection, agent: "plan" } } }, + { + name: "another model", + next: { ...payload, selection: { ...payload.selection, model: { providerID: "openai", modelID: "gpt" } } }, + }, + { name: "another variant", next: { ...payload, selection: { ...payload.selection, variant: undefined } } }, + { + name: "another mention", + next: { + ...payload, + prompt: [text("first "), { type: "agent", name: "review", content: "@review", start: 6, end: 13 }, image], + }, + }, + { + name: "another path attachment", + next: { + ...payload, + prompt: [...payload.prompt, { type: "path", id: "log", filename: "log.txt", mime: "text/plain", path: "/log" }], + }, + }, + { + name: "an edited line comment", + next: { + ...payload, + context: keyed([note, { type: "file", path: "src/app.ts", comment: "Changed", commentID: "c1" }]), + }, + }, + { + name: "an edited quote comment", + next: { + ...payload, + context: keyed([...payload.context, { type: "quote", text: "x", comment: "y", commentID: "q" }]), + }, + }, + { + name: "another image", + next: { ...payload, prompt: [text("first"), { ...image, blob: { id: "media:def", url: "" } }] }, + }, + { name: "a renamed image", next: { ...payload, prompt: [text("first"), { ...image, filename: "other.png" }] } }, + ])("sends $name under a new ID", (row) => { + expect(claimRetry(armed, row.next, fresh)).toBe(fresh) + }) + + test("an image reloaded from the draft store matches the one that failed", () => { + const reloaded = { ...payload, prompt: [text("first"), { ...image, blob: { id: "media:abc", url: "" } }] } + + expect(claimRetry(armed, reloaded, fresh)).toBe(id) + }) +}) diff --git a/packages/app/src/composer/retry.ts b/packages/app/src/composer/retry.ts new file mode 100644 index 000000000000..53c80cbfb120 --- /dev/null +++ b/packages/app/src/composer/retry.ts @@ -0,0 +1,63 @@ +import { checksum } from "@opencode/util/encode" +import type { SessionMessage } from "@opencode/schema/session-message" +import type { ComposerDelivery, ComposerSelection } from "./adapter" +import { buildPromptRequest } from "./request" +import type { ContextItem, Prompt } from "./schema" + +/** The admission ID of a prompt whose send failed, kept to resend exactly the payload it carried. */ +export type ComposerRetry = { readonly id: SessionMessage.ID; readonly fingerprint: string } + +export type ComposerRetryPayload = { + readonly mode: "normal" | "shell" + readonly delivery: ComposerDelivery + readonly selection: ComposerSelection + readonly prompt: Prompt + readonly context: readonly (ContextItem & { key: string })[] +} + +/** + * The server keeps the first payload admitted under an ID and ignores a retried one, so a failed prompt's ID may only + * be reused for the same request. This names that request: what the server receives, not how the draft stores it. + */ +export function retryFingerprint(payload: ComposerRetryPayload) { + const request = buildPromptRequest({ + prompt: payload.prompt, + context: [...payload.context], + // A blob ID names an image's bytes; its URL changes whenever a reload resolves the draft again. + images: payload.prompt.flatMap((part) => + part.type === "image" + ? [ + { + type: part.type, + id: part.id, + filename: part.filename, + sourcePath: part.sourcePath, + mime: part.mime, + dataUrl: part.blob.id, + }, + ] + : [], + ), + text: payload.prompt.map((part) => ("content" in part ? part.content : "")).join(""), + sessionDirectory: "", + }) + + const raw = JSON.stringify([ + payload.mode, + payload.delivery, + payload.selection.agent, + payload.selection.model.providerID, + payload.selection.model.modelID, + payload.selection.variant ?? null, + request, + ]) + + return `${raw.length}:${checksum(raw)}` +} + +/** The ID a send uses: the failed prompt's own when it resends that very payload, otherwise a fresh one. */ +export function claimRetry(retry: ComposerRetry | undefined, payload: ComposerRetryPayload, fresh: SessionMessage.ID) { + if (!retry) return fresh + + return retry.fingerprint === retryFingerprint(payload) ? retry.id : fresh +} diff --git a/packages/app/src/composer/schema.test.ts b/packages/app/src/composer/schema.test.ts index 8c999696db4c..dbb18c82f144 100644 --- a/packages/app/src/composer/schema.test.ts +++ b/packages/app/src/composer/schema.test.ts @@ -39,7 +39,8 @@ describe("composer persistence schemas", () => { cursor: -1, mode: "unknown", model: { providerID: 42, modelID: "model" }, - retry: { id: "bad", agent: "build", providerID: "provider", modelID: "model" }, + // A retry stored before fingerprints matched only the selection, so it cannot prove its payload. + retry: { id: "msg_retry", agent: "build", providerID: "provider", modelID: "model" }, context: { items: [ { type: "file", path: "src/app.ts", commentID: "note", key: "stale" }, @@ -158,7 +159,7 @@ describe("composer persistence schemas", () => { }, ], model: { providerID: "provider", modelID: "model", variant: null }, - retry: { id: "msg_retry", agent: "build", providerID: "provider", modelID: "model", variant: false }, + retry: { id: "msg_retry", fingerprint: "42:abc", agent: "build" }, }) expect(value.prompt.map((part) => part.type)).toEqual(["text", "agent", "skill", "file"]) @@ -171,12 +172,7 @@ describe("composer persistence schemas", () => { filename: "app.ts", }) expect(value.model?.variant).toBeNull() - expect(value.retry).toEqual({ - id: SessionMessage.ID.make("msg_retry"), - agent: "build", - providerID: "provider", - modelID: "model", - }) + expect(value.retry).toEqual({ id: SessionMessage.ID.make("msg_retry"), fingerprint: "42:abc" }) expect(decode(Schema.encodeSync(ComposerStore)(value))).toEqual(value) }) diff --git a/packages/app/src/composer/schema.ts b/packages/app/src/composer/schema.ts index 3ccd71bf56d5..0a670765e51f 100644 --- a/packages/app/src/composer/schema.ts +++ b/packages/app/src/composer/schema.ts @@ -366,15 +366,8 @@ export const ComposerStore = Persistence.struct({ ), model: Persistence.optional(PromptModel), mode: Persistence.optional(Schema.Literals(["normal", "shell"])), - retry: Persistence.optional( - Schema.Struct({ - id: SessionMessage.ID, - agent: Schema.String, - providerID: Schema.String, - modelID: Schema.String, - variant: Persistence.optional(Schema.String), - }), - ), + // A retry stored before it carried its payload's fingerprint cannot prove its payload, so it reads as none. + retry: Persistence.optional(Schema.Struct({ id: SessionMessage.ID, fingerprint: Schema.NonEmptyString })), context: Persistence.struct({ items: Persistence.array(ContextEntry) }), quoteSources: Persistence.optional(Persistence.record(Schema.UndefinedOr(TimelineQuoteSource))), }) diff --git a/packages/app/src/composer/selection.ts b/packages/app/src/composer/selection.ts index 2013ee5bbf72..623bb5f185b8 100644 --- a/packages/app/src/composer/selection.ts +++ b/packages/app/src/composer/selection.ts @@ -7,7 +7,15 @@ import { useProviders } from "@/providers/catalog/providers" import { useData } from "@/runtime/server/current" import { normalizeAgentList, normalizeProviderList } from "@/runtime/server/global-sync/utils" import { useModels } from "@/providers/models/models" -import { cycleModelVariant, getConfiguredAgentVariant, resolveModelVariant } from "@/providers/models/variant" +import { + cycleModelVariant, + durableVariantSelection, + getConfiguredAgentVariant, + INHERIT_VARIANT, + resolveModelVariant, + variantSelectionFrom, +} from "@/providers/models/variant" +import type { AgentChoices } from "@/providers/models/selection-machine" import { useComposerState } from "./persistence" import { useConfiguredModel } from "@/providers/models/configured" import { useGlobal } from "@/runtime/server/runtime" @@ -191,7 +199,12 @@ export function createComposerModelSelection(input: { const selection = { trackSessionCommit: local.model.trackSessionCommit, - remembered: () => Object.fromEntries(Object.entries(remembered).map(([name, model]) => [name, { model }])), + remembered: (): AgentChoices => + Object.fromEntries( + Object.entries(remembered).flatMap(([name, model]) => + model ? [[name, { providerID: model.providerID, modelID: model.modelID, variant: INHERIT_VARIANT }]] : [], + ), + ), ready: Object.assign(() => models.ready() && configuredModel.ready(), { promise: models.ready.promise }), key, current, @@ -247,18 +260,14 @@ export function createComposerModelSelection(input: { }) ) }, - selected() { - const model = prompt.model.current() - - return model && valid(model) ? model.variant : undefined - }, current(item?: ModelKey) { const model = item ? models.find(item) : current() const same = !item || (current()?.provider.id === item.providerID && current()?.id === item.modelID) + const prompted = prompt.model.current() return resolveModelVariant({ variants: Object.keys(model?.variants ?? {}), - selected: same ? this.selected() : undefined, + selected: same && prompted && valid(prompted) ? variantSelectionFrom(prompted.variant) : INHERIT_VARIANT, configured: this.configured(model), preferred: model ? models.variant.get({ providerID: model.provider.id, modelID: model.id }) : undefined, }) @@ -282,7 +291,7 @@ export function createComposerModelSelection(input: { this.set( cycleModelVariant({ variants, - selected: this.current() ?? null, + selected: durableVariantSelection(this.current()), configured: undefined, }), ) diff --git a/packages/app/src/composer/state.ts b/packages/app/src/composer/state.ts index e3a38b70d4a4..76602910b44d 100644 --- a/packages/app/src/composer/state.ts +++ b/packages/app/src/composer/state.ts @@ -1,11 +1,13 @@ -import { batch, untrack, type Accessor } from "solid-js" -import type { ComposerQuoteAnchor } from "@opencode/plugin/gui" -import { createStore, type SetStoreFunction } from "solid-js/store" +import { batch, getOwner, onCleanup, untrack, type Accessor } from "solid-js" +import { createStore, unwrap, type SetStoreFunction } from "solid-js/store" import { Persist, persisted } from "@/runtime/persistence/storage" import { ServerScope } from "@/runtime/server/scope" import type { Platform } from "@/runtime/platform/platform" import { clonePrompt } from "./prompt-parts" +import { uploads } from "./attachments/uploads" +import { createQuoteCommentController, type QuoteCommentController } from "./quote-comment-machine" import { createComposerQuoteSource } from "./quote-source" +import type { ComposerRetry } from "./retry" import { ComposerStore, DEFAULT_PROMPT, @@ -52,7 +54,7 @@ function createComposerActions(setStore: SetStoreFunction) { return { set(prompt: Prompt, cursorPosition?: number) { batch(() => { - setStore({ prompt: clonePrompt(prompt), retry: undefined }) + setStore("prompt", clonePrompt(prompt)) // An omitted cursor keeps the current one. if (cursorPosition !== undefined) setStore("cursor", cursorPosition) @@ -103,7 +105,8 @@ export interface ComposerStateValue { } readonly retry: { readonly current: () => ComposerStore["retry"] - readonly set: (retry: NonNullable) => void + readonly set: (retry: ComposerRetry) => void + readonly clear: () => void } readonly context: { readonly items: () => ComposerStore["context"]["items"] @@ -114,11 +117,7 @@ export interface ComposerStateValue { replace(items: ContextItem[]): void replaceComments(items: ContextItem[]): void } - readonly quoteComment: { - readonly key: Accessor - readonly anchor: Accessor - readonly set: (key?: string, anchor?: ComposerQuoteAnchor) => void - } + readonly quoteComment: QuoteCommentController readonly quoteSource: ReturnType readonly set: (prompt: Prompt, cursorPosition?: number) => void readonly reset: () => void @@ -128,18 +127,20 @@ export interface ComposerStateValue { function createComposerStateValue(store: ComposerStore, setStore: SetStoreFunction): ComposerStateValue { const actions = createComposerActions(setStore) // The quote whose comment editor is open, by key; a request made before the composer shows waits for it. - const [quoteComment, setQuoteComment] = createStore<{ key?: string; anchor?: ComposerQuoteAnchor }>({}) + const quoteComment = createQuoteCommentController() - const quoteSource = createComposerQuoteSource({ - get: () => store.quoteSources, - set: (key, source) => setStore("quoteSources", (sources) => ({ ...sources, [key]: source })), - }) + const quoteSource = createComposerQuoteSource( + { + get: () => store.quoteSources, + set: (key, source) => setStore("quoteSources", (sources) => ({ ...sources, [key]: source })), + }, + quoteComment, + ) - const retainQuoteSources = () => quoteSource.retain(store.context.items.map((item) => item.key)) + // Uploads outlive the composer view that started them, but not the draft they write into. + if (getOwner()) onCleanup(() => uploads.cancelScope(unwrap(store))) - const clearRetry = () => { - if (untrack(() => store.retry) !== undefined) setStore("retry", undefined) - } + const retainQuoteSources = () => quoteSource.retain(store.context.items.map((item) => item.key)) const value = { store: [() => store, setStore] satisfies [Accessor, SetStoreFunction], @@ -147,21 +148,21 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti cursor: () => store.cursor, model: { current: () => store.model, - set: (model: PromptModel | undefined) => { - setStore("model", model) - clearRetry() - }, + set: (model: PromptModel | undefined) => setStore("model", model), }, mode: { current: () => store.mode ?? "normal", set: (mode: "normal" | "shell") => { - if (untrack(() => store.mode === mode && store.retry === undefined)) return - setStore({ mode, retry: undefined }) + if (untrack(() => (store.mode ?? "normal") === mode)) return + setStore("mode", mode) }, }, retry: { current: () => store.retry, - set: (retry: NonNullable) => setStore("retry", retry), + set: (retry: ComposerRetry) => setStore("retry", { id: retry.id, fingerprint: retry.fingerprint }), + clear: () => { + if (untrack(() => store.retry) !== undefined) setStore("retry", undefined) + }, }, context: { items: () => store.context.items, @@ -170,18 +171,15 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti if (store.context.items.find((x) => x.key === key)) return setStore("context", "items", (items) => [...items, { key, ...item }]) - clearRetry() }, remove(key: string) { setStore("context", "items", (items) => items.filter((x) => x.key !== key)) retainQuoteSources() - clearRetry() }, /** Removes the file comment, note, or quote with this commentID. */ removeComment(commentID: string) { setStore("context", "items", (items) => items.filter((item) => item.commentID !== commentID)) retainQuoteSources() - clearRetry() }, /** Edits the file comment, note, or quote with this commentID; only file comments carry a preview. */ updateComment(commentID: string, next: { readonly comment?: string; readonly preview?: string }) { @@ -199,7 +197,6 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti return { ...value, key: contextItemKey(value) } }, ) - clearRetry() }, /** Replaces every item, as restoring a sent prompt replaces the whole draft. */ replace(items: ContextItem[]) { @@ -212,7 +209,6 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti })), ) retainQuoteSources() - clearRetry() }, replaceComments(items: ContextItem[]) { setStore("context", "items", (current) => [ @@ -220,24 +216,9 @@ function createComposerStateValue(store: ComposerStore, setStore: SetStoreFuncti ...items.map((item) => ({ ...item, key: contextItemKey(item) })), ]) retainQuoteSources() - clearRetry() - }, - }, - quoteComment: { - key: () => quoteComment.key, - anchor: () => quoteComment.anchor, - set: (key?: string, anchor?: ComposerQuoteAnchor) => { - setQuoteComment({ key, anchor: key ? anchor : undefined }) - - if (key && quoteSource.state.sources[key]) { - quoteSource.pend(key) - - return - } - - quoteSource.settle() }, }, + quoteComment, quoteSource, set: (prompt: Prompt, cursorPosition?: number) => actions.set(prompt, cursorPosition), reset: () => actions.reset(), diff --git a/packages/app/src/composer/submit.test.ts b/packages/app/src/composer/submit.test.ts index dbf57bab4631..4fe39a751852 100644 --- a/packages/app/src/composer/submit.test.ts +++ b/packages/app/src/composer/submit.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test" +import { describe, expect, jest, test } from "bun:test" import type { ModelSelection } from "@/providers/models/selection" import type { SessionMessageHandoff } from "@/session/handoff" import { Skill } from "@opencode/schema/skill" @@ -10,6 +10,7 @@ import type { NewSessionComposerAdapter, } from "./adapter" import { createMemoryComposerState, type Prompt } from "./state" +import { composerSubmitView } from "./machine" import { createComposerSubmit } from "./submit" import { createSteerBackground } from "@/session/requests/steer-background" import { setMediaBlobLoader } from "@/runtime/persistence/drafts" @@ -35,7 +36,6 @@ const selection = { setVisibility() {}, variant: { configured: () => undefined, - selected: () => "balanced", current: () => "balanced", list: () => ["balanced"], set() {}, @@ -100,13 +100,14 @@ function submitInput( removeFromHistory: (prompt) => history.push(`remove:${prompt.map((part) => ("content" in part ? part.content : part.type)).join("")}`), resetHistory() {}, - setMode() {}, closePopover() {}, notify, comments: { capture: () => [], clear() {}, restore() {} }, }) } +const sessions = { count: 0 } + function session(input: { calls: string[] prompt?: (value: Parameters[0]) => Promise @@ -121,10 +122,11 @@ function session(input: { background?: ComposerSession["background"] }): ComposerSession { return { - id: "session-1", + // Unique per test: what this client knows about a session outlives the test that sent to it. + id: `session-${++sessions.count}`, background: input.background, directory: "C:/repo", - handoff: input.handoff ?? { set() {}, clear() {} }, + handoff: input.handoff ?? { set() {}, hold() {}, settle() {}, clear() {} }, current: input.current ?? (() => undefined), admitted: input.admitted ?? (() => false), api: { @@ -234,7 +236,10 @@ describe("Composer submission", () => { const calls: string[] = [] const submission = submitInput({ - ...active(state, session({ calls, handoff: { set: (handoff) => handoffs.push(handoff), clear() {} } })), + ...active( + state, + session({ calls, handoff: { set: (handoff) => handoffs.push(handoff), hold() {}, settle() {}, clear() {} } }), + ), beforeSubmit: () => calls.push("keep-preview"), }) @@ -358,6 +363,204 @@ describe("Composer submission", () => { expect(calls.filter((call) => call === "send")).toHaveLength(2) }) + test("a quote send keeps sending while the composer sends it, and fails only once the composer can retry", async () => { + const state = createMemoryComposerState().capture() + state.context.add({ type: "quote", text: "Selected passage", commentID: "selected" }) + const release = Promise.withResolvers() + const failed = Promise.withResolvers() + + const submission = submitInput(active(state, session({ calls: [], prompt: () => release.promise })), { + missingSelection() {}, + unqueueable() {}, + failed: () => failed.resolve(), + }) + + jest.useFakeTimers() + state.quoteComment.set("quote:c=selected") + state.quoteComment.send("note", submission.submitQuote) + // A silent server holds a prompt for a minute per attempt; the send has not failed until the composer says so. + jest.advanceTimersByTime(5 * 60_000) + jest.useRealTimers() + expect(state.quoteComment.state()).toMatchObject({ status: "sending", draft: "note" }) + expect(composerSubmitView(submission.state()).canSubmit).toBe(false) + + release.reject(new Error("offline")) + await failed.promise + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(state.quoteComment.state()).toMatchObject({ status: "failed", draft: "note" }) + expect(composerSubmitView(submission.state()).canSubmit).toBe(true) + }) + + test("a prompt that fails after a newer one went out leaves the Session running", async () => { + const state = createMemoryComposerState({ prompt: "first" }).capture() + const statuses: ("idle" | "running")[] = [] + const first = Promise.withResolvers() + const second = Promise.withResolvers() + const failed = { count: 0, settled: Promise.withResolvers() } + + const target = session({ + calls: [], + statuses, + prompt: async (value) => { + if (value.text === "first") return first.promise + await second.promise + }, + }) + + const submission = submitInput( + { ...active(state, target), working: () => statuses.at(-1) === "running" }, + { + missingSelection() {}, + unqueueable() {}, + failed: () => { + failed.count++ + failed.settled.resolve() + }, + }, + ) + + await submission.submit(new Event("submit")) + state.set([{ type: "text", content: "second", start: 0, end: 6 }]) + await submission.submit(new Event("submit")) + first.reject(new Error("offline")) + await failed.settled.promise + // The second prompt's turn may already run; only the server's events may end it. + expect(statuses).toEqual(["running"]) + + failed.settled = Promise.withResolvers() + second.reject(new Error("offline")) + await failed.settled.promise + expect(failed.count).toBe(2) + expect(statuses).toEqual(["running", "idle"]) + }) + + test("resends a failed prompt under its ID only while what it sends is unchanged", async () => { + const state = createMemoryComposerState({ prompt: "ship it" }).capture() + + const note = { + type: "note" as const, + origin: "browser", + label: "button#save", + icon: "select-element", + subject: 'the "button#save" element', + live: { subject: 'the "button#save" element (browser ref @e42)' }, + comment: "Rename this", + commentID: "note", + } + + state.context.add(note) + const sent: string[] = [] + const run = { fail: true, queued: false, settled: Promise.withResolvers() } + + const submission = submitInput( + active( + state, + session({ + calls: [], + prompt: async (value) => { + sent.push(value.id ?? "") + + if (run.fail) throw new Error("offline") + run.settled.resolve() + }, + }), + ), + { missingSelection() {}, unqueueable() {}, failed: () => run.settled.resolve() }, + "normal", + undefined, + undefined, + undefined, + () => (run.queued ? "queue" : "steer"), + ) + + const send = async () => { + run.settled = Promise.withResolvers() + sent.length = 0 + await submission.submit(new Event("submit")) + await run.settled.promise + + return sent[0] + } + + const first = await send() + expect(state.retry.current()).toMatchObject({ id: first }) + expect(await send()).toBe(first) + + // The browser plugin re-picked the element, so the note now names another ref. + state.context.replaceComments([{ ...note, live: { subject: 'the "button#save" element (browser ref @e7)' } }]) + const edited = await send() + expect(edited).not.toBe(first) + + run.queued = true + const queued = await send() + expect(queued).not.toBe(edited) + + run.fail = false + expect(await send()).toBe(queued) + expect(state.retry.current()).toBeUndefined() + }) + + test("an unedited resend after a failed send keeps its ID and its file order", async () => { + const state = createMemoryComposerState({ prompt: "review these" }).capture() + state.context.add({ type: "file", path: "src/a.ts" }) + state.context.add({ type: "file", path: "src/b.ts", comment: "Check this", commentID: "b" }) + const keys = state.context.items().map((item) => item.key) + const sent: string[] = [] + const failed = { settled: Promise.withResolvers() } + + const submission = submitInput( + active( + state, + session({ + calls: [], + prompt: async (value) => { + sent.push(value.id ?? "") + throw new Error("offline") + }, + }), + ), + { missingSelection() {}, unqueueable() {}, failed: () => failed.settled.resolve() }, + ) + + const send = async () => { + failed.settled = Promise.withResolvers() + sent.length = 0 + await submission.submit(new Event("submit")) + await failed.settled.promise + + return sent[0] + } + + const first = await send() + // Restoring used to list the commented file first, so the resend fingerprinted differently and took a new ID. + expect(state.context.items().map((item) => item.key)).toEqual(keys) + expect(await send()).toBe(first) + }) + + test("a failed server command restores its draft without a retry ID, which it never sent", async () => { + const state = createMemoryComposerState({ prompt: "/review" }).capture() + const failed = Promise.withResolvers() + + await submitInput( + active( + state, + session({ + calls: [], + command: async () => { + throw new Error("offline") + }, + }), + ), + { missingSelection() {}, unqueueable() {}, failed: () => failed.resolve() }, + "normal", + () => [{ name: "review" }], + ).submit(new Event("submit")) + await failed.promise + + expect(text(state)).toBe("/review") + expect(state.retry.current()).toBeUndefined() + }) + test("applies the selection and runs a client argument command without admitting it to the session", async () => { const state = createMemoryComposerState().capture() @@ -473,7 +676,7 @@ describe("Composer submission", () => { const target = session({ calls, - handoff: { set: (value) => handoffs.push(value), clear() {} }, + handoff: { set: (value) => handoffs.push(value), hold() {}, settle() {}, clear() {} }, prompt: async (value) => admitted.resolve(value), }) @@ -504,7 +707,7 @@ describe("Composer submission", () => { const target = session({ calls: [], statuses, - handoff: { set: (handoff) => handoffs.push(handoff), clear() {} }, + handoff: { set: (handoff) => handoffs.push(handoff), hold() {}, settle() {}, clear() {} }, switchModel: async () => committed.promise, }) @@ -701,9 +904,10 @@ describe("Composer submission", () => { expect(calls).toEqual([...submitted, ...submitted]) expect(statuses).toEqual(["running", "idle", "running", "idle"]) expect(state.current()).toEqual(prompt) + // In the order it was sent, so the resend's request matches the first. expect(state.context.items()).toMatchObject([ - note, { type: "file", path: "notes.md", description: "the failing version" }, + note, ]) // The caret returns after the mention text; attachments take no caret positions. expect(state.cursor()).toBe(17) @@ -1018,7 +1222,7 @@ describe("Composer submission", () => { const target = session({ calls: [], - handoff: { set: handedOff.resolve, clear() {} }, + handoff: { set: handedOff.resolve, hold() {}, settle() {}, clear() {} }, prompt: async () => admitted.resolve(), }) @@ -1046,6 +1250,42 @@ describe("Composer submission", () => { }) }) + test.each([ + { case: "is admitted", fails: false, admitted: false, result: "settle" }, + { case: "loses its response after admission", fails: true, admitted: true, result: "settle" }, + { case: "fails", fails: true, admitted: false, result: "clear" }, + ])("a steer's handoff waits for its echo or ends when its send $case", async (row) => { + const state = createMemoryComposerState({ prompt: "steer" }).capture() + const handoff: string[] = [] + const ended = Promise.withResolvers() + + const target = session({ + calls: [], + admitted: () => row.admitted, + handoff: { + set: (value) => handoff.push(`set:${value.message.id}`), + hold: (value) => handoff.push(`hold:${value.message.id}`), + settle: (id) => { + handoff.push(`settle:${id}`) + ended.resolve() + }, + clear: (id) => { + handoff.push(`clear:${id}`) + ended.resolve() + }, + }, + prompt: async () => { + if (row.fails) throw new Error("response lost") + }, + }) + + await submitInput(active(state, target)).submit(new Event("submit")) + await ended.promise + + expect(handoff).toHaveLength(2) + expect(handoff[1]).toBe(handoff[0]!.replace("set:", `${row.result}:`)) + }) + test("forwards structured mentions to custom commands", async () => { const state = createMemoryComposerState().capture() state.set([ diff --git a/packages/app/src/composer/submit.ts b/packages/app/src/composer/submit.ts index 155b6e09c578..e1cb1f7810c8 100644 --- a/packages/app/src/composer/submit.ts +++ b/packages/app/src/composer/submit.ts @@ -3,7 +3,7 @@ import type { SessionMessageUser } from "@opencode/client/promise" import { createEffect, createSignal, onCleanup, untrack, type Accessor } from "solid-js" import type { PromptComment } from "./comment-note" import type { PromptHistoryComment } from "./history/entry" -import { isCommentItem, type ContextItem, type Prompt } from "./state" +import { isCommentItem, type ContextItem, type ImageAttachmentPart, type Prompt } from "./state" import { appendPrompt, clonePrompt, isAttachment, promptLength, serializePrompt } from "./prompt-parts" import type { ComposerAdapter, @@ -25,12 +25,24 @@ import { type ComposerSubmitEffect, type ComposerSubmitEvent, type PromptSend, + type SubmissionKind, type SubmitSnapshot, } from "./machine" +import { retryFingerprint } from "./retry" +import { + SERVER_PROMPT_STATUS, + transitionPromptStatus, + type PromptStatusEvent, + type PromptStatusState, +} from "./prompt-status-machine" // The model each session was last switched to from this client, by session ID. const switched = new Map() +// The optimistic busy status of each session, by session ID. Module-wide, because a new session's first prompt and +// the follow-ups sent from its own composer go through different submit machines. A session left out is `server`. +const statuses = new Map() + type ComposerSubmitInput = { adapter: ComposerAdapter mode: Accessor<"normal" | "shell"> @@ -40,7 +52,6 @@ type ComposerSubmitInput = { addToHistory: (prompt: Prompt, mode: "normal" | "shell") => void removeFromHistory: (prompt: Prompt, mode: "normal" | "shell", comments: PromptHistoryComment[]) => void resetHistory: () => void - setMode: (mode: "normal" | "shell") => void closePopover: () => void delivery?: (alternate: boolean) => ComposerDelivery clientCommand?: (text: string) => (() => void | Promise) | undefined @@ -83,6 +94,39 @@ export function createComposerSubmit(input: ComposerSubmitInput) { if (effect.type === "submit.retry") return dispatch({ type: "submit", snapshot: snapshot(input, effect.alternate), done: effect.done }) + if (effect.type === "hold.show") { + input.adapter.beforeSubmit?.() + effect.session.handoff.hold({ + message: handoffMessage({ + id: effect.snapshot.id, + prompt: effect.snapshot.draft.prompt, + context: effect.snapshot.draft.context, + images: effect.snapshot.draft.prompt.filter((part): part is ImageAttachmentPart => part.type === "image"), + }), + }) + input.addToHistory(effect.snapshot.draft.prompt, effect.snapshot.mode) + input.resetHistory() + + return dispatch({ + type: "hold.cleared", + attempt: effect.attempt, + cleared: clearComposer(input, effect.snapshot.draft, "prompt").cleared, + }) + } + + if (effect.type === "hold.cancel") { + effect.session.handoff.clear(effect.snapshot.id) + + if (!effect.cleared) return + restoreDraft( + input, + { draft: effect.snapshot.draft, mode: effect.snapshot.mode, comments: effect.snapshot.comments }, + afterHold(effect.snapshot.draft, effect.cleared), + ) + + return + } + if (effect.type === "command.run") { input.adapter.beforeSubmit?.() void runClientCommand(input, effect.prompt, effect.run).then( @@ -187,17 +231,25 @@ export function createComposerSubmit(input: ComposerSubmitInput) { clearSubmission(input, effect) } - // A held send goes through once the Location's agents and models load, and ends if the draft changes first. + // A held send goes through once the Location's agents and models load. One still in the composer ends if the draft + // changes first; a shown one already left it. createEffect(() => { const current = state() if (current.type !== "held") return - if (JSON.stringify(input.adapter.state.current()) !== current.draft) + if (!current.shown && JSON.stringify(input.adapter.state.current()) !== current.snapshot.serialized) return untrack(() => dispatch({ type: "hold.changed", attempt: current.attempt })) if (!input.adapter.controls().model.loading) - untrack(() => dispatch({ type: "hold.loaded", attempt: current.attempt })) + untrack(() => + dispatch({ + type: "hold.loaded", + attempt: current.attempt, + selection: currentSelection(input), + commands: input.commands(), + }), + ) }) onCleanup(() => dispatch({ type: "unmounted" })) @@ -280,6 +332,7 @@ function snapshot(input: ComposerSubmitInput, alternate: boolean): SubmitSnapsho commands: input.commands(), clientCommand: mode === "normal" ? input.clientCommand?.(text) : undefined, comments: input.comments.capture(), + session: input.adapter.kind === "active-session" ? input.adapter.session() : undefined, } } @@ -318,59 +371,84 @@ async function startSession( return started && { ...started, images } } -// The composer clears its captured draft once the Session's composer is ready; then the send settles. +// The composer clears its captured draft once the Session's composer is ready; then the send settles. A shown hold +// cleared it already, and the composer may hold a new draft since. function clearSubmission( input: ComposerSubmitInput, effect: Extract, ) { - const target = effect.draft.target + const held = effect.cleared + const clear = held ? undefined : clearComposer(input, effect.draft, effect.kind.type) + + // A held prompt cleared the composer at Enter, so what it goes back to is read only once the send fails. + const restore = () => { + const back = clear ?? (held && afterHold(effect.draft, held)) + + return !!back && restoreSubmission(input, effect, back) + } + + if (effect.prompt) return void effect.prompt.settled(restore) + + if (effect.kind.type === "shell") + return void sendShell(effect.session, effect.value).catch((error) => + failSubmission(input, effect.session, "shell", error, restore), + ) + + if (effect.kind.type === "command") + void sendCommand( + effect.session, + effect.value, + effect.kind.command, + input.adapter.controls().model.selection.trackSessionCommit, + ).catch((error) => failSubmission(input, effect.session, "command", error, restore, effect.value.id)) +} + +// Returns the cleared composer, which a failed send restores only while it is unchanged, and any follow-up already +// typed into a promoted new-session composer. +function clearComposer(input: ComposerSubmitInput, draft: CapturedDraft, kind: SubmissionKind["type"]) { + const target = draft.target input.adapter.submitted() - if (effect.kind.type === "prompt") { + if (kind === "prompt") { // Like the TUI, sent context goes with the prompt rather than riding along on the next one. - effect.draft.context.forEach((item) => target.context.remove(item.key)) + draft.context.forEach((item) => target.context.remove(item.key)) input.comments.clear() } - if (effect.draft.initial !== target) effect.draft.initial.reset() + if (draft.initial !== target) draft.initial.reset() // A preparing session may already have an unsent follow-up in its promoted composer. const following = - effect.draft.initial !== target && - effect.draft.preserveDraft && + draft.initial !== target && + draft.preserveDraft && target.current().some((part) => isAttachment(part) || part.content.length > 0) ? clonePrompt(target.current()) : undefined if (!following) target.reset() const cleared = target.current() + // The ID went with this send; a failure arms it again for this payload when it restores the draft. + target.retry.clear() target.mode.set("normal") - input.setMode("normal") input.closePopover() if (window.matchMedia("(max-width: 767px)").matches) input.editor()?.blur() - const restore = () => restoreSubmission(input, effect, cleared, following) - if (effect.prompt) return void effect.prompt.settled(restore) + return { cleared, following, edited: !!following } satisfies ClearedComposer +} - if (effect.kind.type === "shell") - return void sendShell(effect.session, effect.value).catch((error) => - failSubmission(input, effect.session, "shell", error, restore), - ) +// A held prompt left the composer before it was sent, so a draft typed since follows it back rather than keeping it out. +function afterHold(draft: CapturedDraft, cleared: Prompt): ClearedComposer { + const current = draft.target.current() + const edited = current !== cleared + const typed = edited && current.some((part) => isAttachment(part) || part.content.length > 0) - if (effect.kind.type === "command") - void sendCommand( - effect.session, - effect.value, - effect.kind.command, - input.adapter.controls().model.selection.trackSessionCommit, - ).catch((error) => failSubmission(input, effect.session, "command", error, restore, effect.value.id)) + return { cleared: current, following: typed ? clonePrompt(current) : undefined, edited } } function clearClientCommand(input: ComposerSubmitInput, prompt: Prompt) { input.adapter.state.set([{ type: "text", content: "", start: 0, end: 0 }, ...prompt.filter(isAttachment)], 0) input.adapter.state.mode.set("normal") - input.setMode("normal") input.closePopover() } @@ -386,7 +464,10 @@ function submissionText(prompt: Prompt) { return prompt.map((part) => ("content" in part ? part.content : "")).join("") } -function handoffMessage(value: ComposerSubmission): SessionMessageUser { +// A held prompt has no agent or model until its Location's catalog loads. +function handoffMessage( + value: Pick & { selection?: ComposerSelection }, +): SessionMessageUser { const text = submissionText(serializePrompt(value.prompt)) return { @@ -422,8 +503,7 @@ function handoffMessage(value: ComposerSubmission): SessionMessageUser { }, ] }), - agent: value.selection.agent, - model: selectionModel(value.selection), + ...(value.selection && { agent: value.selection.agent, model: selectionModel(value.selection) }), }, time: { created: Date.now() }, } @@ -457,26 +537,33 @@ function dispatchPrompt(input: ComposerSubmitInput, session: ComposerSession, va }, }, }) - const optimisticBusy = !input.adapter.working() + const working = input.adapter.working() - const background = value.delivery === "steer" && !optimisticBusy ? session.background?.() : undefined + const background = value.delivery === "steer" && working ? session.background?.() : undefined - if (optimisticBusy) session.data.session.setStatus(session.id, "running") + updateStatus(session, { type: "dispatched", id: value.id, working }) const sending = sendPrompt(session, value, input.adapter.controls().model.selection.trackSessionCommit).then( () => ({ ok: true as const }), (error) => ({ ok: false as const, error }), ) + // Settled here rather than when the composer settles, which an aborted promotion never reaches. + void sending.then((result) => { + const admitted = result.ok || session.admitted(value.id) + updateStatus(session, admitted ? { type: "admitted" } : { type: "failed", id: value.id }) + + if (value.delivery !== "steer") return + + if (admitted) return session.handoff.settle(value.id) + session.handoff.clear(value.id) + }) + return { // The composer settles after clearing its captured draft; a quote settles before removing only its context. settled: (restore) => sending.then((result) => { - const admitted = - result.ok || - failSubmission(input, session, "prompt", result.error, restore, value.id, () => { - if (optimisticBusy) session.data.session.setStatus(session.id, "idle") - }) + const admitted = result.ok || failSubmission(input, session, "prompt", result.error, restore, value.id) if (!admitted) return false @@ -488,24 +575,66 @@ function dispatchPrompt(input: ComposerSubmitInput, session: ComposerSession, va } } +function updateStatus(session: ComposerSession, event: PromptStatusEvent) { + const result = transitionPromptStatus(statuses.get(session.id) ?? SERVER_PROMPT_STATUS, event) + + if (result.state.type === "server") statuses.delete(session.id) + + if (result.state.type === "optimistic") statuses.set(session.id, result.state) + result.effects.forEach((effect) => session.data.session.setStatus(session.id, effect.status)) +} + +/** + * The composer a restore goes back to: the prompt it was cleared to, a follow-up typed into it since, and whether it + * was edited since, which keeps the comments added meanwhile. + */ +type ClearedComposer = { cleared: Prompt; following: Prompt | undefined; edited: boolean } + // Puts a failed submission back, unless the composer changed since it cleared: then the edit is the user's. function restoreSubmission( input: ComposerSubmitInput, - submission: { draft: CapturedDraft; value: ComposerSubmission; comments: PromptHistoryComment[] }, - cleared: Prompt, - following: Prompt | undefined, + submission: { + draft: CapturedDraft + value: ComposerSubmission + kind: SubmissionKind + comments: PromptHistoryComment[] + }, + back: ClearedComposer, ) { - const target = submission.draft.target const value = submission.value - if (target.current() !== cleared) return false + if (!restoreDraft(input, { ...submission, mode: value.mode }, back)) return false + + // Only a prompt was admitted under its ID. A recovered follow-up changes the payload, so it needs a new one. + if (submission.kind.type === "prompt" && !back.following) + submission.draft.target.retry.set({ id: value.id, fingerprint: retryFingerprint(value) }) + + return true +} + +// Puts a cleared draft back, unless the composer changed since it cleared: then the edit is the user's. +function restoreDraft( + input: ComposerSubmitInput, + submission: { draft: CapturedDraft; mode: "normal" | "shell"; comments: PromptHistoryComment[] }, + back: ClearedComposer, +) { + const target = submission.draft.target + const following = back.following + + if (target.current() !== back.cleared) return false + const kept = back.edited ? input.comments.capture() : [] const prompt = following ? appendPrompt(submission.draft.prompt, following) : submission.draft.prompt // The prompt is back in the composer; its history entry would only keep attachments referenced. - input.removeFromHistory(value.prompt, value.mode, submission.comments) + input.removeFromHistory(submission.draft.prompt, submission.mode, submission.comments) target.set(prompt, promptLength(prompt)) - target.mode.set(value.mode) - target.context.replaceComments( - submission.draft.context.filter(isCommentItem).map((item): ContextItem => { + target.mode.set(submission.mode) + const sent = new Set(submission.draft.context.map((item) => item.key)) + + // In the order it was sent: an unedited resend must send the same request, which the retry ID's fingerprint names. + // Files listed since the send stay after it. Comments the draft gained since are replaced, as before, unless they + // were added to a draft typed since, which keeps them. + target.context.replace([ + ...submission.draft.context.map((item): ContextItem => { if (item.type === "quote") return { type: "quote", @@ -538,43 +667,27 @@ function restoreSubmission( commentID: item.commentID, commentOrigin: item.commentOrigin, preview: item.preview, + name: item.name, + description: item.description, } }), - ) + ...target.context.items().filter((item) => (back.edited || !isCommentItem(item)) && !sent.has(item.key)), + ]) submission.draft.sources.forEach((item) => target.quoteSource.add(item.key, item.source)) - submission.draft.context.forEach((item) => { - if (item.type === "file" && !item.comment?.trim()) - target.context.add({ - type: "file", - path: item.path, - selection: item.selection, - name: item.name, - description: item.description, - }) - }) - - // A recovered follow-up changes the payload, so it must use a new admission ID. - if (value.mode === "normal" && !following) { - target.retry.set({ - id: value.id, - agent: value.selection.agent, - providerID: value.selection.model.providerID, - modelID: value.selection.model.modelID, - variant: value.selection.variant, - }) - } if (target !== input.adapter.state) return true - input.comments.restore(submission.comments) - input.setMode(value.mode) + input.comments.restore([ + ...submission.comments, + ...kept.filter((item) => !submission.comments.some((comment) => comment.id === item.id)), + ]) input.closePopover() requestAnimationFrame(() => { const editor = input.editor() if (!editor) return editor.focus() - setCursorPosition(editor, promptLength(value.prompt)) + setCursorPosition(editor, promptLength(submission.draft.prompt)) input.queueScroll() }) @@ -731,12 +844,8 @@ function failSubmission( error: unknown, restore: () => boolean, messageID?: string, - rollback?: () => void, ) { if (messageID && session.admitted(messageID)) return true - - if (messageID) session.handoff.clear(messageID) - rollback?.() restore() input.notify.failed(kind, error) diff --git a/packages/app/src/composer/suggestions/machine.test.ts b/packages/app/src/composer/suggestions/machine.test.ts index 3663461dafc5..cdae4d6b2ffc 100644 --- a/packages/app/src/composer/suggestions/machine.test.ts +++ b/packages/app/src/composer/suggestions/machine.test.ts @@ -1,11 +1,13 @@ import { expect, test } from "bun:test" -import type { ComposerPersistedState, ComposerSuggestion } from "../types" +import type { ComposerHistoryEntry, ComposerPersistedState, ComposerSuggestion } from "../types" import { + composerHistoryPreviewHeight, createComposerInteractionState, transitionComposer, type ComposerInteractionCommand, type ComposerInteractionEvent, type ComposerInteractionState, + type ComposerSavedDraft, } from "./machine" const command: ComposerSuggestion = { id: "review", kind: "command", label: "/review" } @@ -40,7 +42,6 @@ test.each<{ draft?: ComposerPersistedState popover?: ComposerInteractionState["popover"] focus?: ComposerInteractionState["focus"] - mode?: ComposerInteractionState["mode"] command?: ComposerInteractionCommand handled?: true }>([ @@ -51,6 +52,68 @@ test.each<{ ...menu, command: { type: "focus.command-search" }, }, + { + name: "closes inline commands on a second press and takes back the slash it typed", + from: { popover: { type: "command-inline", query: "" } }, + event: { type: "commands.open" }, + draft: persisted("/"), + popover: { type: "closed" }, + command: { type: "draft.setText", value: "" }, + }, + { + name: "closes inline commands on a second press and keeps a typed query", + from: { popover: { type: "command-inline", query: "re" } }, + event: { type: "commands.open" }, + draft: persisted("/re"), + popover: { type: "closed" }, + command: { type: "focus.editor" }, + }, + { + name: "closes the command menu on a second press", + from: menu, + event: { type: "commands.open" }, + draft: persisted("existing text"), + popover: { type: "closed" }, + focus: "editor", + }, + { + name: "closes the command menu when its empty search is backspaced", + from: menu, + event: key("Backspace"), + draft: persisted("existing text"), + popover: { type: "closed" }, + command: { type: "focus.editor" }, + handled: true, + }, + { + name: "keeps the command menu while its search has a query to delete", + from: { popover: { type: "command-menu", query: "re" }, focus: "command-search" }, + event: key("Backspace"), + draft: persisted("existing text"), + popover: { type: "command-menu", query: "re" }, + }, + { + name: "closes the command menu when the editor is typed in", + from: menu, + event: { type: "input.changed", value: "" }, + popover: { type: "closed" }, + }, + { + name: "closes context on a second press and takes back the @ it typed", + from: { popover: { type: "context", query: "" } }, + event: { type: "context.open" }, + draft: persisted("see @"), + popover: { type: "closed" }, + command: { type: "draft.removeTextBefore", value: "@" }, + }, + { + name: "closes context on a second press and keeps a typed query", + from: { popover: { type: "context", query: "sr" } }, + event: { type: "context.open" }, + draft: persisted("see @sr"), + popover: { type: "closed" }, + command: { type: "focus.editor" }, + }, { name: "opens inline commands when slash is the entire prompt", event: { type: "input.changed", value: "/re" }, @@ -103,21 +166,20 @@ test.each<{ name: "enters shell mode from an initial exclamation mark", event: { type: "input.changed", value: "!", persist: false }, draft: persisted("!"), - mode: "shell", - command: { type: "draft.setText", value: "" }, + command: { type: "draft.setMode", mode: "shell" }, }, { name: "leaves shell mode with escape", - from: { mode: "shell" }, event: key("Escape"), - mode: "normal", + draft: { ...persisted(), mode: "shell" }, + command: { type: "draft.setMode", mode: "normal" }, handled: true, }, { name: "leaves shell mode with backspace when empty", - from: { mode: "shell" }, event: key("Backspace", { empty: true }), - mode: "normal", + draft: { ...persisted(), mode: "shell" }, + command: { type: "draft.setMode", mode: "normal" }, handled: true, }, { @@ -179,8 +241,180 @@ test.each<{ if (row.focus) expect(result.state.focus).toBe(row.focus) - if (row.mode) expect(result.state.mode).toBe(row.mode) - if (row.command) expect(result.commands).toContainEqual(row.command) expect(result.handled).toBe(row.handled ?? false) }) + +const shot = { type: "path" as const, id: "shot", filename: "shot.png", mime: "image/png", path: "/tmp/shot.png" } + +const other = { type: "path" as const, id: "other", filename: "other.png", mime: "image/png", path: "/tmp/other.png" } + +// An empty-text draft with an attachment and a line comment (the host's history metadata). +const written: ComposerSavedDraft = { entry: { prompt: [...persisted().prompt, shot], metadata: ["c1"] }, cursor: 0 } + +const entries: ComposerHistoryEntry[] = [ + { prompt: [...persisted().prompt, other] }, + { prompt: persisted("older").prompt }, +] + +function step(direction: "up" | "down", text = "", cursor = 0): ComposerInteractionEvent { + return { type: "history.step", direction, text, cursor, entries, capture: () => written } +} + +function browsing(index: number): ComposerInteractionState { + return { ...createComposerInteractionState(), popover: { type: "browsing", index, saved: written }, focus: "editor" } +} + +function history(height?: number): ComposerInteractionState { + return { + ...createComposerInteractionState(), + popover: { type: "history", query: "", activeID: "history:0", saved: written, height }, + focus: "history-search", + } +} + +test("searching history from a recalled entry still cancels back to the draft the user wrote", () => { + const recalled = transitionComposer(createComposerInteractionState(), step("up"), persisted()) + expect(recalled.state.popover).toEqual({ type: "browsing", index: 0, saved: written }) + expect(recalled.commands).toEqual([{ type: "history.apply", entry: entries[0], cursor: 0 }]) + + // Shift+ArrowUp captures what the composer shows now: the recalled entry, not the draft. + const shown: ComposerSavedDraft = { entry: entries[0]!, cursor: 0 } + + const opened = transitionComposer( + recalled.state, + { type: "history.open", id: "history:0", saved: shown }, + persisted(), + ) + + expect(opened.handled).toBe(true) + expect(opened.state.popover).toMatchObject({ type: "history", saved: written }) + + const cancelled = transitionComposer(opened.state, key("Escape"), persisted()) + expect(cancelled.state.popover).toEqual({ type: "closed" }) + expect(cancelled.commands).toEqual([{ type: "history.restore", draft: written, focus: true }]) +}) + +test("a pointer outside a history preview or switching to shell restores the draft", () => { + const dismissed = transitionComposer(history(), { type: "popover.dismiss" }, persisted()) + expect(dismissed.state).toMatchObject({ popover: { type: "closed" }, focus: "external" }) + expect(dismissed.commands).toEqual([{ type: "history.restore", draft: written, focus: false }]) + + const shell = transitionComposer(history(), { type: "mode.shell" }, persisted()) + expect(shell.state.popover).toEqual({ type: "closed" }) + expect(shell.commands).toEqual([ + { type: "history.restore", draft: written, focus: false }, + { type: "draft.setMode", mode: "shell" }, + ]) + + // Nothing is open to dismiss while browsing; the recalled entry stays. + const idle = browsing(0) + expect(transitionComposer(idle, { type: "popover.dismiss" }, persisted()).state).toBe(idle) +}) + +test("the preview height lives exactly as long as the history list", () => { + const opened = transitionComposer( + createComposerInteractionState(), + { type: "history.open", id: "history:0", saved: written, height: 142 }, + persisted(), + ) + + expect(composerHistoryPreviewHeight(opened.state)).toBe(142) + + const select: ComposerInteractionEvent = { + type: "popover.select", + item: { id: "history:1", kind: "history", label: "older", history: entries[1] }, + } + + const exits: ComposerInteractionEvent[] = [ + key("Escape"), + key("Tab"), + select, + { type: "popover.dismiss" }, + { type: "history.reset" }, + ] + + for (const event of exits) + expect(composerHistoryPreviewHeight(transitionComposer(history(142), event, persisted()).state)).toBeUndefined() + + expect(transitionComposer(history(142), select, persisted()).commands).toEqual([ + { type: "history.apply", entry: entries[1] }, + ]) +}) + +test("plain arrows browse history within its bounds and back to the written draft", () => { + const oldest = browsing(1) + const clamped = transitionComposer(oldest, step("up"), persisted("older")) + expect(clamped.state).toBe(oldest) + expect(clamped.handled).toBe(false) + + const newer = transitionComposer(oldest, step("down", "older", 5), persisted("older")) + expect(newer.state.popover).toEqual({ type: "browsing", index: 0, saved: written }) + expect(newer.commands).toEqual([{ type: "history.apply", entry: entries[0] }]) + + const back = transitionComposer(browsing(0), step("down"), persisted()) + expect(back.state.popover).toEqual({ type: "closed" }) + expect(back.commands).toEqual([{ type: "history.restore", draft: written, focus: true }]) + + // The caret must sit at an edge of a recalled entry, and at the start of an empty draft to begin. + expect(transitionComposer(oldest, step("down", "older", 2), persisted("older")).state).toBe(oldest) + const typed = createComposerInteractionState() + expect(transitionComposer(typed, step("up", "draft", 0), persisted("draft")).state).toBe(typed) + expect(transitionComposer(typed, step("down"), persisted()).state).toBe(typed) +}) + +test("editing a recalled entry makes it the draft", () => { + const typed = transitionComposer( + browsing(0), + { type: "input.changed", value: "edit", persist: false }, + persisted("edit"), + ) + + expect(typed.state.popover).toEqual({ type: "closed" }) + expect(typed.commands).toEqual([]) + + expect(transitionComposer(browsing(0), { type: "draft.edited" }, persisted()).state.popover).toEqual({ + type: "closed", + }) + + const idle = createComposerInteractionState() + expect(transitionComposer(idle, { type: "draft.edited" }, persisted()).state).toBe(idle) +}) + +test("typing with nothing open keeps the same state and asks for nothing", () => { + const idle: ComposerInteractionState = { ...createComposerInteractionState(), focus: "editor" } + const typed = transitionComposer(idle, { type: "input.changed", value: "hello", persist: false }, persisted("hello")) + expect(typed.state).toBe(idle) + expect(typed.commands).toEqual([]) + expect(transitionComposer(idle, key("a"), persisted("hello")).state).toBe(idle) +}) + +test("the draft's mode is the only mode, and an outside change ends browsing", () => { + const shell: ComposerPersistedState = { ...persisted(), mode: "shell" } + expect(transitionComposer(createComposerInteractionState(), { type: "mode.shell" }, shell).commands).toEqual([]) + + const left = transitionComposer(browsing(0), { type: "mode.normal" }, shell) + expect(left.state.popover).toEqual({ type: "closed" }) + expect(left.commands).toEqual([{ type: "draft.setMode", mode: "normal" }]) + + const escaped = transitionComposer(browsing(0), key("Escape"), shell) + expect(escaped.state.popover).toEqual({ type: "closed" }) + expect(escaped.commands).toEqual([{ type: "draft.setMode", mode: "normal" }]) + + // A queue edit or a send writes the mode and the draft together, so nothing is restored over them. + for (const state of [browsing(0), history()]) { + const synced = transitionComposer(state, { type: "mode.synced", mode: "shell" }, shell) + expect(synced.state.popover).toEqual({ type: "closed" }) + expect(synced.commands).toEqual([]) + } + + const context: ComposerInteractionState = { + ...createComposerInteractionState(), + popover: { type: "context", query: "" }, + } + + expect(transitionComposer(context, { type: "mode.synced", mode: "normal" }, persisted()).state).toBe(context) + expect(transitionComposer(context, { type: "mode.synced", mode: "shell" }, shell).state.popover).toEqual({ + type: "closed", + }) +}) diff --git a/packages/app/src/composer/suggestions/machine.ts b/packages/app/src/composer/suggestions/machine.ts index 617845935596..9d2028b8bb45 100644 --- a/packages/app/src/composer/suggestions/machine.ts +++ b/packages/app/src/composer/suggestions/machine.ts @@ -1,62 +1,133 @@ -import type { ComposerPersistedState, ComposerSuggestion } from "../types" +import type { ComposerHistoryEntry, ComposerPersistedState, ComposerSuggestion } from "../types" import { isAttachment } from "../prompt-parts" +export type ComposerMode = "normal" | "shell" + +/** The draft history replaced, put back when the user browses past the newest entry or cancels a preview. */ +export type ComposerSavedDraft = { + readonly entry: ComposerHistoryEntry + readonly cursor: number | undefined +} + +export type ComposerPopoverState = + | { readonly type: "closed" } + // Plain arrows recall history entries into the draft, with no list open. + | { readonly type: "browsing"; readonly index: number; readonly saved: ComposerSavedDraft } + | { readonly type: "context"; readonly query: string; readonly activeID?: string; readonly chosen?: boolean } + | { readonly type: "command-inline"; readonly query: string; readonly activeID?: string; readonly chosen?: boolean } + | { readonly type: "command-menu"; readonly query: string; readonly activeID?: string; readonly chosen?: boolean } + | { + readonly type: "history" + readonly query: string + readonly activeID?: string + readonly chosen?: boolean + readonly saved: ComposerSavedDraft + /** The composer's height when the list opened, held while previews of other sizes replace the draft. */ + readonly height?: number + } + +type OpenPopover = Exclude + +// The draft's `mode` is the only record of the composer mode; the machine reads it and asks for changes. export type ComposerInteractionState = { - mode: "normal" | "shell" - popover: - | { type: "closed" } - | { type: "context"; query: string; activeID?: string; chosen?: boolean } - | { type: "command-inline"; query: string; activeID?: string; chosen?: boolean } - | { type: "command-menu"; query: string; activeID?: string; chosen?: boolean } - | { type: "history"; query: string; activeID?: string; chosen?: boolean } - drag: "idle" | "active" - focus: "editor" | "command-search" | "history-search" | "external" - activeContextID?: string + readonly popover: ComposerPopoverState + readonly drag: "idle" | "active" + readonly focus: "editor" | "command-search" | "history-search" | "external" + readonly activeContextID?: string } export type ComposerInteractionEvent = - | { type: "input.changed"; value: string; persist?: boolean } - | { type: "commands.open" } - | { type: "context.open" } - | { type: "history.open"; id: string } - | { type: "popover.query"; value: string } - | { type: "popover.results"; ids: string[] } - | { type: "popover.active"; id: string } - | { type: "popover.close" } - | { type: "popover.select"; item: ComposerSuggestion } - | { type: "key.down"; key: string; ctrl: boolean; composing: boolean; ids: string[]; empty?: boolean } - | { type: "mode.shell" } - | { type: "mode.normal" } - | { type: "drag.enter" } - | { type: "drag.leave" } - | { type: "focus.editor" } - | { type: "focus.external" } - | { type: "context.active"; id: string } + | { readonly type: "input.changed"; readonly value: string; readonly persist?: boolean } + /** The draft changed outside typing (an attachment or a comment); recalled history becomes the draft. */ + | { readonly type: "draft.edited" } + | { readonly type: "commands.open" } + | { readonly type: "context.open" } + | { readonly type: "history.open"; readonly id: string; readonly saved: ComposerSavedDraft; readonly height?: number } + | { + readonly type: "history.step" + readonly direction: "up" | "down" + readonly text: string + readonly cursor: number + readonly entries: readonly ComposerHistoryEntry[] + /** Read only when browsing starts, so other arrow presses copy nothing. */ + readonly capture: () => ComposerSavedDraft + } + /** Ends browsing or a preview without putting the draft back: a send or another draft replaced it. */ + | { readonly type: "history.reset" } + | { readonly type: "popover.query"; readonly value: string } + | { readonly type: "popover.results"; readonly ids: readonly string[] } + | { readonly type: "popover.active"; readonly id: string } + | { readonly type: "popover.close" } + /** A pointer or focus outside the list; a history preview puts the draft back. */ + | { readonly type: "popover.dismiss" } + | { readonly type: "popover.select"; readonly item: ComposerSuggestion } + | { + readonly type: "key.down" + readonly key: string + readonly ctrl: boolean + readonly composing: boolean + readonly ids: readonly string[] + readonly empty?: boolean + } + | { readonly type: "mode.shell" } + | { readonly type: "mode.normal" } + /** Something other than this machine wrote the draft's mode: hydration, a queue edit or a send. */ + | { readonly type: "mode.synced"; readonly mode: ComposerMode } + | { readonly type: "drag.enter" } + | { readonly type: "drag.leave" } + | { readonly type: "focus.editor" } + | { readonly type: "focus.external" } + | { readonly type: "context.active"; readonly id: string } export type ComposerInteractionCommand = - | { type: "draft.setText"; value: string } - | { type: "draft.addText"; value: string } - | { type: "mention.add"; item: ComposerSuggestion; range?: { start: number; end: number } } - | { type: "popover.filter"; popover: "command" | "context"; query: string } - | { type: "suggestion.select"; id: string } - | { type: "focus.editor" } - | { type: "focus.command-search" } - | { type: "history.preview"; id: string } - | { type: "history.restore" } + | { readonly type: "draft.setMode"; readonly mode: ComposerMode } + | { readonly type: "draft.setText"; readonly value: string } + | { readonly type: "draft.addText"; readonly value: string } + | { readonly type: "draft.removeTextBefore"; readonly value: string } + | { readonly type: "mention.add"; readonly item: ComposerSuggestion; readonly range?: { start: number; end: number } } + | { readonly type: "popover.filter"; readonly popover: "command" | "context"; readonly query: string } + | { readonly type: "suggestion.select"; readonly id: string } + | { readonly type: "focus.editor" } + | { readonly type: "focus.command-search" } + | { readonly type: "history.preview"; readonly id: string } + | { readonly type: "history.apply"; readonly entry: ComposerHistoryEntry; readonly cursor?: number } + | { readonly type: "history.restore"; readonly draft: ComposerSavedDraft; readonly focus: boolean } export type ComposerEditorTransition = { - state: ComposerInteractionState - commands: ComposerInteractionCommand[] - handled: boolean + readonly state: ComposerInteractionState + readonly commands: readonly ComposerInteractionCommand[] + readonly handled: boolean } +const CLOSED: ComposerPopoverState = Object.freeze({ type: "closed" }) + +const NO_COMMANDS: readonly ComposerInteractionCommand[] = Object.freeze([]) + +const SHELL: ComposerInteractionCommand = Object.freeze({ type: "draft.setMode", mode: "shell" }) + +const NORMAL: ComposerInteractionCommand = Object.freeze({ type: "draft.setMode", mode: "normal" }) + export function createComposerInteractionState(): ComposerInteractionState { - return { - mode: "normal", - popover: { type: "closed" }, - drag: "idle", - focus: "external", - } + return { popover: CLOSED, drag: "idle", focus: "external" } +} + +export function selectComposerMode(persisted: Pick): ComposerMode { + return persisted.mode ?? "normal" +} + +/** Whether a suggestion list shows; browsing history shows none. */ +export function isComposerPopoverOpen( + state: ComposerInteractionState, +): state is ComposerInteractionState & { popover: OpenPopover } { + return state.popover.type !== "closed" && state.popover.type !== "browsing" +} + +export function composerPopoverActiveID(state: ComposerInteractionState) { + return isComposerPopoverOpen(state) ? state.popover.activeID : undefined +} + +export function composerHistoryPreviewHeight(state: ComposerInteractionState) { + return state.popover.type === "history" ? state.popover.height : undefined } export function transitionComposer( @@ -64,16 +135,32 @@ export function transitionComposer( event: ComposerInteractionEvent, persisted: ComposerPersistedState, ): ComposerEditorTransition { - if (event.type === "input.changed") return inputChanged(state, event.value, event.persist !== false, persisted.cursor) + if (event.type === "input.changed") return inputChanged(state, event.value, event.persist !== false, persisted) + + if (event.type === "draft.edited") + return state.popover.type === "browsing" ? changed({ ...state, popover: CLOSED }) : unchanged(state) if (event.type === "commands.open") return openCommands(state, persisted) if (event.type === "context.open") return openContext(state) - if (event.type === "history.open") - return changed({ ...state, popover: { type: "history", query: "", activeID: event.id }, focus: "history-search" }, [ - { type: "history.preview", id: event.id }, - ]) + if (event.type === "history.open") return openHistory(state, event) + + if (event.type === "history.step") return stepHistory(state, event) + + if (event.type === "history.reset" || event.type === "popover.close") + return state.popover.type === "closed" ? unchanged(state) : changed({ ...state, popover: CLOSED }) + + if (event.type === "popover.dismiss") { + if (state.popover.type === "history") + return changed({ ...state, popover: CLOSED, focus: "external" }, [ + { type: "history.restore", draft: state.popover.saved, focus: false }, + ]) + + if (!isComposerPopoverOpen(state)) return unchanged(state) + + return changed({ ...state, popover: CLOSED, focus: "external" }) + } if (event.type === "popover.query") return queryChanged(state, event.value) @@ -81,75 +168,97 @@ export function transitionComposer( if (event.type === "popover.active") return activeChanged(state, event.id) - if (event.type === "popover.close") return changed({ ...state, popover: { type: "closed" } }) - if (event.type === "popover.select") return suggestionSelected(state, event.item, persisted) - if (event.type === "key.down") return keyDown(state, event) + if (event.type === "key.down") return keyDown(state, event, selectComposerMode(persisted)) + + if (event.type === "mode.shell") return enterShell(state, selectComposerMode(persisted)) + + if (event.type === "mode.normal") return leaveShell(state, selectComposerMode(persisted)) - if (event.type === "mode.shell") return changed({ ...state, mode: "shell", popover: { type: "closed" } }) + // A recalled entry or preview belongs to the other mode's history, and the draft's new owner replaced it. + if (event.type === "mode.synced") { + if (state.popover.type === "closed") return unchanged(state) + + if (event.mode === "normal" && isComposerPopoverOpen(state) && state.popover.type !== "history") + return unchanged(state) - if (event.type === "mode.normal") return changed({ ...state, mode: "normal" }) + return changed({ ...state, popover: CLOSED }) + } - if (event.type === "drag.enter") return changed({ ...state, drag: "active" }) + if (event.type === "drag.enter") + return state.drag === "active" ? unchanged(state) : changed({ ...state, drag: "active" }) - if (event.type === "drag.leave") return changed({ ...state, drag: "idle" }) + if (event.type === "drag.leave") return state.drag === "idle" ? unchanged(state) : changed({ ...state, drag: "idle" }) - if (event.type === "focus.editor") return changed({ ...state, focus: "editor" }) + if (event.type === "focus.editor") + return state.focus === "editor" ? unchanged(state) : changed({ ...state, focus: "editor" }) if (event.type === "context.active") { return changed({ ...state, activeContextID: state.activeContextID === event.id ? undefined : event.id }) } - return changed({ ...state, focus: "external" }) + return state.focus === "external" ? unchanged(state) : changed({ ...state, focus: "external" }) } function inputChanged( state: ComposerInteractionState, value: string, persist: boolean, - cursor: number | undefined, + persisted: ComposerPersistedState, ): ComposerEditorTransition { - const setText: ComposerInteractionCommand[] = persist ? [{ type: "draft.setText", value }] : [] - - if (state.mode === "normal" && value === "!") { - return changed({ ...state, mode: "shell", popover: { type: "closed" }, focus: "editor" }, [ - { type: "draft.setText", value: "" }, - ]) + if (selectComposerMode(persisted) === "normal" && value === "!") { + return changed({ ...state, popover: CLOSED, focus: "editor" }, [SHELL, { type: "draft.setText", value: "" }]) } // An open mention keeps single spaces so multi-word session titles stay searchable. - const context = value - .slice(0, cursor ?? value.length) - .match(state.popover.type === "context" ? /(?:^|\s)@((?:[^\s@]+(?: [^\s@]+)* ?)?)$/ : /(?:^|\s)@([^\s@]*)$/) + const context = value.includes("@") + ? value + .slice(0, persisted.cursor ?? value.length) + .match(state.popover.type === "context" ? /(?:^|\s)@((?:[^\s@]+(?: [^\s@]+)* ?)?)$/ : /(?:^|\s)@([^\s@]*)$/) + : null if (context) { const query = context[1] ?? "" return changed({ ...state, popover: { type: "context", query }, focus: "editor" }, [ - ...setText, + ...(persist ? [{ type: "draft.setText" as const, value }] : []), { type: "popover.filter", popover: "context", query }, ]) } - const command = value.match(/^\/(\S*)$/) + const command = value.startsWith("/") ? value.match(/^\/(\S*)$/) : null if (command) { const query = command[1] ?? "" return changed({ ...state, popover: { type: "command-inline", query }, focus: "editor" }, [ - ...setText, + ...(persist ? [{ type: "draft.setText" as const, value }] : []), { type: "popover.filter", popover: "command", query }, ]) } - return changed( - { ...state, popover: state.popover.type === "command-menu" ? state.popover : { type: "closed" }, focus: "editor" }, - setText, - ) + const commands = persist ? [{ type: "draft.setText" as const, value }] : NO_COMMANDS + + // Typing is the hot path: plain text in a composer with nothing open changes nothing here. + if (state.popover.type === "closed" && state.focus === "editor") return unchanged(state, false, commands) + + // Typing in the editor leaves the command menu, whose own search field takes its input, and makes recalled history + // the draft. + return changed({ ...state, popover: CLOSED, focus: "editor" }, commands) } function openCommands(state: ComposerInteractionState, persisted: ComposerPersistedState): ComposerEditorTransition { + // A second press closes the commands, taking back the slash the first one typed. + if (state.popover.type === "command-inline" || state.popover.type === "command-menu") { + const typed = state.popover.type === "command-inline" && promptText(persisted) === "/" + + return changed({ ...state, popover: CLOSED, focus: "editor" }, [ + ...(typed ? [{ type: "draft.setText" as const, value: "" }] : []), + { type: "focus.editor" }, + ]) + } + if (!populated(persisted)) { return changed({ ...state, popover: { type: "command-inline", query: "" }, focus: "editor" }, [ { type: "draft.addText", value: "/" }, @@ -165,6 +274,14 @@ function openCommands(state: ComposerInteractionState, persisted: ComposerPersis } function openContext(state: ComposerInteractionState): ComposerEditorTransition { + // A second press closes the context list, taking back the @ it typed when nothing follows it yet. + if (state.popover.type === "context") { + return changed({ ...state, popover: CLOSED, focus: "editor" }, [ + ...(state.popover.query ? [] : [{ type: "draft.removeTextBefore" as const, value: "@" }]), + { type: "focus.editor" }, + ]) + } + return changed({ ...state, popover: { type: "context", query: "" }, focus: "editor" }, [ { type: "draft.addText", value: "@" }, { type: "popover.filter", popover: "context", query: "" }, @@ -172,8 +289,73 @@ function openContext(state: ComposerInteractionState): ComposerEditorTransition ]) } +function openHistory( + state: ComposerInteractionState, + event: Extract, +): ComposerEditorTransition { + if (isComposerPopoverOpen(state)) return unchanged(state) + + return changed( + { + ...state, + popover: { + type: "history", + query: "", + activeID: event.id, + // Searching from a recalled entry still cancels back to the draft the user wrote, not the entry. + saved: state.popover.type === "browsing" ? state.popover.saved : event.saved, + height: event.height, + }, + focus: "history-search", + }, + [{ type: "history.preview", id: event.id }], + true, + ) +} + +function stepHistory( + state: ComposerInteractionState, + event: Extract, +): ComposerEditorTransition { + if (isComposerPopoverOpen(state)) return unchanged(state) + const browsing = state.popover.type === "browsing" ? state.popover : undefined + + if (!canNavigateHistory(event.direction, event.text, event.cursor, !!browsing)) return unchanged(state) + + if (event.direction === "up") { + const index = browsing ? browsing.index + 1 : 0 + const entry = event.entries[index] + + if (!entry) return unchanged(state) + + return changed( + { ...state, popover: { type: "browsing", index, saved: browsing?.saved ?? event.capture() }, focus: "editor" }, + [{ type: "history.apply", entry, cursor: 0 }], + true, + ) + } + + if (!browsing) return unchanged(state) + + if (browsing.index === 0) + return changed( + { ...state, popover: CLOSED, focus: "editor" }, + [{ type: "history.restore", draft: browsing.saved, focus: true }], + true, + ) + const entry = event.entries[browsing.index - 1] + + if (!entry) return unchanged(state) + + return changed( + { ...state, popover: { ...browsing, index: browsing.index - 1 }, focus: "editor" }, + [{ type: "history.apply", entry }], + true, + ) +} + function queryChanged(state: ComposerInteractionState, query: string): ComposerEditorTransition { - if (state.popover.type === "closed") return unchanged(state) + if (!isComposerPopoverOpen(state)) return unchanged(state) if (state.popover.type === "history") return changed({ ...state, popover: { ...state.popover, query, activeID: undefined, chosen: undefined } }) @@ -185,8 +367,8 @@ function queryChanged(state: ComposerInteractionState, query: string): ComposerE ]) } -function resultsChanged(state: ComposerInteractionState, ids: string[]): ComposerEditorTransition { - if (state.popover.type === "closed") return unchanged(state) +function resultsChanged(state: ComposerInteractionState, ids: readonly string[]): ComposerEditorTransition { + if (!isComposerPopoverOpen(state)) return unchanged(state) // Until the user picks a row, the highlight follows the first row as results arrive and reorder. const kept = @@ -200,17 +382,16 @@ function resultsChanged(state: ComposerInteractionState, ids: string[]): Compose return changed( { ...state, popover: { ...state.popover, activeID, chosen: kept && state.popover.chosen } }, - state.popover.type === "history" && activeID ? [{ type: "history.preview", id: activeID }] : [], + state.popover.type === "history" && activeID ? [{ type: "history.preview", id: activeID }] : NO_COMMANDS, ) } function activeChanged(state: ComposerInteractionState, id: string): ComposerEditorTransition { - if (state.popover.type === "closed" || (state.popover.activeID === id && state.popover.chosen)) - return unchanged(state) + if (!isComposerPopoverOpen(state) || (state.popover.activeID === id && state.popover.chosen)) return unchanged(state) return changed( { ...state, popover: { ...state.popover, activeID: id, chosen: true } }, - state.popover.type === "history" ? [{ type: "history.preview", id }] : [], + state.popover.type === "history" ? [{ type: "history.preview", id }] : NO_COMMANDS, ) } @@ -219,6 +400,16 @@ function suggestionSelected( item: ComposerSuggestion, persisted: ComposerPersistedState, ): ComposerEditorTransition { + if (item.kind === "history") { + if (state.popover.type !== "history" || !item.history) return unchanged(state) + + return changed( + { ...state, popover: CLOSED, focus: "editor" }, + [{ type: "history.apply", entry: item.history }], + true, + ) + } + const current = promptText(persisted) const commands: ComposerInteractionCommand[] = [] @@ -245,33 +436,43 @@ function suggestionSelected( commands.push({ type: "focus.editor" }) - return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, commands) + return changed({ ...state, popover: CLOSED, focus: "editor" }, commands) } function keyDown( state: ComposerInteractionState, event: Extract, + mode: ComposerMode, ): ComposerEditorTransition { if (state.popover.type === "history" && (event.key === "Escape" || (event.ctrl && event.key.toLowerCase() === "g"))) { - return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, [{ type: "history.restore" }], true) + return changed( + { ...state, popover: CLOSED, focus: "editor" }, + [{ type: "history.restore", draft: state.popover.saved, focus: true }], + true, + ) } - if (event.ctrl && event.key.toLowerCase() === "g") { - if (state.popover.type === "closed") return unchanged(state) + if (!isComposerPopoverOpen(state)) { + if (mode === "shell" && (event.key === "Escape" || (event.key === "Backspace" && event.empty))) { + return changed(state.popover.type === "closed" ? state : { ...state, popover: CLOSED }, [NORMAL], true) + } - return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, [{ type: "focus.editor" }], true) + return unchanged(state) } - if (state.popover.type === "closed") { - if (state.mode === "shell" && (event.key === "Escape" || (event.key === "Backspace" && event.empty))) { - return changed({ ...state, mode: "normal" }, [], true) - } + if (event.ctrl && event.key.toLowerCase() === "g") + return changed({ ...state, popover: CLOSED, focus: "editor" }, [{ type: "focus.editor" }], true) - return unchanged(state) + // Backspace on an empty search backs out of the command menu, as it closes inline commands by deleting their slash. + // iOS does not move the keyboard to the search field the menu focuses, so the key can arrive from the editor; it is + // handled there too, so backing out never also deletes from the draft. + if (event.key === "Backspace" && state.popover.type === "command-menu" && !state.popover.query) { + return changed({ ...state, popover: CLOSED, focus: "editor" }, [{ type: "focus.editor" }], true) } + // Tab keeps the previewed entry as the draft. if (event.key === "Escape" || (state.popover.type === "history" && event.key === "Tab")) { - return changed({ ...state, popover: { type: "closed" }, focus: "editor" }, [{ type: "focus.editor" }], true) + return changed({ ...state, popover: CLOSED, focus: "editor" }, [{ type: "focus.editor" }], true) } if (event.key === "Tab" || (event.key === "Enter" && !event.composing)) { @@ -304,11 +505,39 @@ function keyDown( return changed( { ...state, popover: { ...state.popover, activeID: event.ids[next], chosen: true } }, - state.popover.type === "history" ? [{ type: "history.preview", id: event.ids[next] }] : [], + state.popover.type === "history" ? [{ type: "history.preview", id: event.ids[next]! }] : NO_COMMANDS, true, ) } +function enterShell(state: ComposerInteractionState, mode: ComposerMode): ComposerEditorTransition { + if (mode === "shell" && state.popover.type === "closed") return unchanged(state) + + // A history preview is cancelled, not kept: its entry belongs to the prompt history. + return changed({ ...state, popover: CLOSED }, [ + ...(state.popover.type === "history" + ? [{ type: "history.restore" as const, draft: state.popover.saved, focus: false }] + : []), + ...(mode === "shell" ? [] : [SHELL]), + ]) +} + +function leaveShell(state: ComposerInteractionState, mode: ComposerMode): ComposerEditorTransition { + if (mode === "normal") return unchanged(state) + + return changed(state.popover.type === "browsing" ? { ...state, popover: CLOSED } : state, [NORMAL]) +} + +function canNavigateHistory(direction: "up" | "down", text: string, cursor: number, browsing: boolean) { + const position = Math.max(0, Math.min(cursor, text.length)) + + if (browsing) return position === 0 || position === text.length + + if (direction === "up") return position === 0 && text.length === 0 + + return position === text.length +} + function promptText(persisted: ComposerPersistedState) { return persisted.prompt.map((part) => (part.type === "text" ? part.content : "")).join("") } @@ -329,7 +558,7 @@ function replaceTrigger(value: string, trigger: "@" | "/", replacement: string) function changed( state: ComposerInteractionState, - commands: ComposerInteractionCommand[] = [], + commands: readonly ComposerInteractionCommand[] = NO_COMMANDS, handled = false, ): ComposerEditorTransition { return { state, commands, handled } @@ -338,7 +567,7 @@ function changed( function unchanged( state: ComposerInteractionState, handled = false, - commands: ComposerInteractionCommand[] = [], + commands: readonly ComposerInteractionCommand[] = NO_COMMANDS, ): ComposerEditorTransition { return { state, commands, handled } } diff --git a/packages/app/src/entry.tsx b/packages/app/src/entry.tsx index b9760dd88be1..969f506c1f6a 100644 --- a/packages/app/src/entry.tsx +++ b/packages/app/src/entry.tsx @@ -49,7 +49,8 @@ const clearAuthToken = () => { history.replaceState(null, "", location.pathname + (params.size ? `?${params}` : "") + location.hash) } -const web = createWebPlatform(pkg.version) +// package.json carries the last stable version on every channel, so the server's build passes its own release. +const web = createWebPlatform(import.meta.env.VITE_OPENCODE_VERSION ?? pkg.version) if (import.meta.env.PROD && "serviceWorker" in navigator) { window.addEventListener("load", () => void navigator.serviceWorker.register("/sw.js"), { once: true }) diff --git a/packages/app/src/env.d.ts b/packages/app/src/env.d.ts index b18fe121e715..afe80ccababe 100644 --- a/packages/app/src/env.d.ts +++ b/packages/app/src/env.d.ts @@ -3,6 +3,8 @@ interface ImportMetaEnv { readonly VITE_OPENCODE_SERVER_HOST: string readonly VITE_OPENCODE_SERVER_PORT: string readonly VITE_OPENCODE_CHANNEL?: "local" | "dev" | "beta" | "prod" + /** The release of the CLI whose server embeds this build. Absent in the hosted web app. */ + readonly VITE_OPENCODE_VERSION?: string readonly VITE_SENTRY_DSN?: string readonly VITE_SENTRY_ENVIRONMENT?: string diff --git a/packages/app/src/home/machine.test.ts b/packages/app/src/home/machine.test.ts new file mode 100644 index 000000000000..9adf7399bf05 --- /dev/null +++ b/packages/app/src/home/machine.test.ts @@ -0,0 +1,286 @@ +import { describe, expect, test } from "bun:test" +import { ServerConnection } from "@/runtime/server/registry" +import { + INITIAL_HOME_SELECTION_STATE, + selectHomeSelection, + transitionHomeSelection, + type HomeEnvSnapshot, + type HomeSelectionEvent, + type HomeSelectionState, + type HomeServerSnapshot, +} from "./machine" + +const SIDECAR = ServerConnection.Key.make("sidecar") + +const REMOTE = ServerConnection.Key.make("https://apollo.example.test") + +const REPO = { id: "proj_repo", worktree: "/srv/repo" } + +const API = { id: "proj_api", worktree: "C:/OpenCode/api" } + +const APP = { id: "proj_app", worktree: "C:/OpenCode/app" } + +const server = (key: ServerConnection.Key, input: Partial = {}): HomeServerSnapshot => ({ + key, + failed: false, + connected: true, + projectsReady: true, + usedProjects: [], + ...input, +}) + +const env = (input: Partial = {}): HomeEnvSnapshot => ({ + hydrated: true, + stored: {}, + servers: [server(SIDECAR)], + ...input, +}) + +const sync = (state: HomeSelectionState, snapshot: HomeEnvSnapshot) => + transitionHomeSelection(state, { type: "env.synced", env: snapshot }) + +const settle = (snapshot: HomeEnvSnapshot) => sync(INITIAL_HOME_SELECTION_STATE, snapshot).state + +describe("home selection machine", () => { + test("keeps a restored remote selection while the stored servers load, then verifies its project", () => { + const stored = { server: REMOTE, directory: "/srv/repo" } + + const loading = sync(INITIAL_HOME_SELECTION_STATE, env({ hydrated: false, stored })) + expect(loading.state.status).toBe("hydrating") + expect(loading.effects).toEqual([]) + // The fallback server shows without the remote server's directory. + expect(selectHomeSelection(loading.state)).toEqual({ server: SIDECAR }) + + const listed = sync( + loading.state, + env({ stored, servers: [server(SIDECAR), server(REMOTE, { projectsReady: false })] }), + ) + + expect(listed.state.status).toBe("verifying") + expect(listed.effects).toEqual([]) + expect(selectHomeSelection(listed.state)).toEqual(stored) + + const ready = sync( + listed.state, + env({ stored, servers: [server(SIDECAR), server(REMOTE, { usedProjects: [REPO] })] }), + ) + + expect(ready.state).toMatchObject({ status: "ready", server: REMOTE, project: REPO }) + expect(ready.effects).toEqual([{ type: "worktrees.list", attempt: 1, server: REMOTE, projectID: REPO.id }]) + }) + + test("writes nothing while the layout loads, so its stored selection is not overwritten", () => { + const early = sync( + INITIAL_HOME_SELECTION_STATE, + env({ hydrated: false, stored: { server: SIDECAR }, servers: [server(REMOTE)] }), + ) + + expect(early.state.status).toBe("hydrating") + expect(early.effects).toEqual([]) + expect(selectHomeSelection(early.state)).toEqual({ server: REMOTE }) + + const loaded = sync( + early.state, + env({ stored: { server: REMOTE, directory: "/srv/repo" }, servers: [server(REMOTE, { usedProjects: [REPO] })] }), + ) + + expect(loaded.state).toMatchObject({ status: "ready", server: REMOTE, project: REPO }) + expect(loaded.effects.map((effect) => effect.type)).toEqual(["worktrees.list"]) + }) + + test("always shows a listed server, and drops the directory of a server that is gone", () => { + expect(selectHomeSelection(settle(env({ hydrated: false })))).toEqual({ server: SIDECAR }) + + const gone = sync(INITIAL_HOME_SELECTION_STATE, env({ stored: { server: REMOTE, directory: "/srv/repo" } })) + expect(gone.state).toMatchObject({ status: "ready", server: SIDECAR, project: undefined }) + expect(gone.effects).toEqual([{ type: "selection.persist", selection: { server: SIDECAR } }]) + }) + + test("waits for legacy projects to migrate before it keeps or clears the directory", () => { + const stored = { server: SIDECAR, directory: API.worktree } + + const migrating = sync( + INITIAL_HOME_SELECTION_STATE, + env({ stored, servers: [server(SIDECAR, { projectsReady: false })] }), + ) + + expect(migrating.state.status).toBe("verifying") + expect(migrating.effects).toEqual([]) + + const migrated = sync(migrating.state, env({ stored, servers: [server(SIDECAR, { usedProjects: [API] })] })) + expect(migrated.state).toMatchObject({ status: "ready", project: API }) + expect(migrated.effects.map((effect) => effect.type)).toEqual(["worktrees.list"]) + }) + + test("stores a used project's own path for a directory written another way", () => { + const result = sync( + INITIAL_HOME_SELECTION_STATE, + env({ + stored: { server: SIDECAR, directory: "C:\\OpenCode\\app\\" }, + servers: [server(SIDECAR, { usedProjects: [APP] })], + }), + ) + + expect(selectHomeSelection(result.state)).toEqual({ server: SIDECAR, directory: APP.worktree }) + expect(result.effects).toEqual([ + { type: "selection.persist", selection: { server: SIDECAR, directory: APP.worktree } }, + { type: "worktrees.list", attempt: 1, server: SIDECAR, projectID: APP.id }, + ]) + }) + + test("lists the selected project's worktrees once per connected span and refreshes only the current one", () => { + const servers = () => [server(SIDECAR, { usedProjects: [{ ...API }, { ...APP }] })] + const stored = { server: SIDECAR, directory: API.worktree } + const listing = settle(env({ stored, servers: servers() })) + expect(listing.status === "ready" && listing.worktrees).toEqual({ + status: "listing", + attempt: 1, + server: SIDECAR, + projectID: API.id, + }) + + // A store update rebuilds every project object; the demand does not start again. + expect(sync(listing, env({ stored, servers: servers() }))).toEqual({ state: listing, effects: [] }) + expect(sync(listing, env({ stored, servers: servers() })).state).toBe(listing) + + const listed = transitionHomeSelection(listing, { type: "worktrees.listed", attempt: 1 }) + expect(listed.effects).toEqual([{ type: "worktrees.refresh", server: SIDECAR, projectID: API.id }]) + expect(sync(listed.state, env({ stored, servers: servers() })).state).toBe(listed.state) + + // Switching projects while a list runs drops its refresh. + const switched = transitionHomeSelection(listing, { + type: "project.toggled", + server: SIDECAR, + directory: APP.worktree, + }) + + expect(switched.effects).toEqual([ + { type: "selection.persist", selection: { server: SIDECAR, directory: APP.worktree } }, + { type: "worktrees.list", attempt: 2, server: SIDECAR, projectID: APP.id }, + ]) + const late = transitionHomeSelection(switched.state, { type: "worktrees.listed", attempt: 1 }) + expect(late.state).toBe(switched.state) + expect(late.effects).toEqual([]) + + // A disconnect drops the demand; the next connection lists again. + const offline = sync( + listed.state, + env({ stored, servers: [server(SIDECAR, { connected: false, usedProjects: [API] })] }), + ) + + expect(offline.state.status === "ready" && offline.state.worktrees).toEqual({ status: "idle" }) + expect(transitionHomeSelection(offline.state, { type: "worktrees.listed", attempt: 1 }).state).toBe(offline.state) + const online = sync(offline.state, env({ stored, servers: [server(SIDECAR, { usedProjects: [API] })] })) + expect(online.effects).toEqual([{ type: "worktrees.list", attempt: 2, server: SIDECAR, projectID: API.id }]) + }) + + test("a choice made while loading wins once everything loaded, and is written only then", () => { + const stored = { server: SIDECAR } + const loading = settle(env({ hydrated: false, stored, servers: [server(SIDECAR), server(REMOTE)] })) + const focused = transitionHomeSelection(loading, { type: "server.focused", server: REMOTE }) + expect(focused.state.status).toBe("hydrating") + expect(focused.effects).toEqual([]) + expect(selectHomeSelection(focused.state)).toEqual({ server: REMOTE }) + + const loaded = sync(focused.state, env({ stored, servers: [server(SIDECAR), server(REMOTE)] })) + expect(loaded.effects).toEqual([{ type: "selection.persist", selection: { server: REMOTE } }]) + }) + + test("keeps the directory while its server is signed out, and clears it only once the server lists projects", () => { + const stored = { server: SIDECAR, directory: API.worktree } + const ready = settle(env({ stored, servers: [server(SIDECAR, { connected: false, usedProjects: [API] })] })) + + const signedOut = sync( + ready, + env({ stored, servers: [server(SIDECAR, { connected: false, projectsReady: false })] }), + ) + + expect(signedOut.state.status).toBe("verifying") + expect(signedOut.effects).toEqual([]) + + const closed = sync(signedOut.state, env({ stored, servers: [server(SIDECAR, { connected: false })] })) + expect(closed.state).toMatchObject({ status: "ready", project: undefined }) + expect(closed.effects).toEqual([{ type: "selection.persist", selection: { server: SIDECAR } }]) + }) + + test("toggles a used project on a working server and ignores the rest", () => { + const servers = [ + server(SIDECAR, { connected: false, usedProjects: [API] }), + server(REMOTE, { failed: true, usedProjects: [REPO] }), + ] + + const ready = settle(env({ stored: { server: SIDECAR }, servers })) + + const toggle = (state: HomeSelectionState, target: ServerConnection.Key, directory: string) => + transitionHomeSelection(state, { type: "project.toggled", server: target, directory }) + + expect(toggle(ready, REMOTE, REPO.worktree).state).toBe(ready) + expect(toggle(ready, SIDECAR, "C:/OpenCode/unused").state).toBe(ready) + + const on = toggle(ready, SIDECAR, API.worktree) + expect(on.effects).toEqual([{ type: "selection.persist", selection: { server: SIDECAR, directory: API.worktree } }]) + const off = toggle(on.state, SIDECAR, "C:\\OpenCode\\api\\") + expect(off.effects).toEqual([{ type: "selection.persist", selection: { server: SIDECAR } }]) + }) + + test("an added project is selected unless the user chose something else first", () => { + const stored = { server: SIDECAR } + const ready = settle(env({ stored, servers: [server(SIDECAR, { connected: false }), server(REMOTE)] })) + const add: HomeSelectionEvent = { type: "project.add", server: SIDECAR, directories: [API.worktree] } + + expect(transitionHomeSelection(ready, { ...add, directories: [] }).state).toBe(ready) + + const adding = transitionHomeSelection(ready, add) + expect(adding.effects).toEqual([{ type: "project.add", attempt: 1, server: SIDECAR, directories: [API.worktree] }]) + + // The server reports the project before the result arrives, as the driver syncs it first. + const listed = sync( + adding.state, + env({ stored, servers: [server(SIDECAR, { connected: false, usedProjects: [API] }), server(REMOTE)] }), + ) + + const added = transitionHomeSelection(listed.state, { type: "project.added", attempt: 1, project: API }) + expect(added.state).toMatchObject({ status: "ready", server: SIDECAR, project: API, adding: undefined }) + expect(added.effects).toEqual([ + { type: "selection.persist", selection: { server: SIDECAR, directory: API.worktree } }, + ]) + + const moved = transitionHomeSelection(listed.state, { type: "server.focused", server: REMOTE }) + const stale = transitionHomeSelection(moved.state, { type: "project.added", attempt: 1, project: API }) + expect(stale.state).toBe(moved.state) + expect(stale.effects).toEqual([]) + + const failed = transitionHomeSelection(listed.state, { type: "project.added", attempt: 1, project: undefined }) + expect(failed.state).toMatchObject({ status: "ready", project: undefined, adding: undefined }) + expect(failed.effects).toEqual([]) + }) + + test("adopts a selection written elsewhere, and does not echo its own writes", () => { + const servers = [server(SIDECAR, { connected: false, usedProjects: [API] }), server(REMOTE)] + const first = sync(INITIAL_HOME_SELECTION_STATE, env({ stored: { server: REMOTE, directory: "/gone" }, servers })) + expect(first.effects).toEqual([{ type: "selection.persist", selection: { server: REMOTE } }]) + expect(sync(first.state, env({ stored: { server: REMOTE }, servers })).state).toBe(first.state) + + const shown = sync(first.state, env({ stored: { server: SIDECAR, directory: API.worktree }, servers })) + expect(shown.state).toMatchObject({ status: "ready", server: SIDECAR, project: API }) + expect(shown.effects).toEqual([]) + }) + + test("ignores everything once disposed", () => { + const listing = settle( + env({ + stored: { server: SIDECAR, directory: API.worktree }, + servers: [server(SIDECAR, { usedProjects: [API] })], + }), + ) + + const disposed = transitionHomeSelection(listing, { type: "disposed" }).state + expect(disposed.status).toBe("disposed") + expect(transitionHomeSelection(disposed, { type: "worktrees.listed", attempt: 1 })).toEqual({ + state: disposed, + effects: [], + }) + expect(transitionHomeSelection(disposed, { type: "project.added", attempt: 1, project: API }).state).toBe(disposed) + expect(sync(disposed, env()).state).toBe(disposed) + }) +}) diff --git a/packages/app/src/home/machine.ts b/packages/app/src/home/machine.ts new file mode 100644 index 000000000000..3f6999c4cb63 --- /dev/null +++ b/packages/app/src/home/machine.ts @@ -0,0 +1,344 @@ +import type { ServerConnection } from "@/runtime/server/registry" +import { toggleHomeProjectSelection } from "@/shell/layout/helpers" +import type { HomeProjectSelection } from "@/shell/state/layout" +import { pathKey } from "@/workspaces/path-key" + +export type HomeProjectItem = { + readonly id: string + readonly worktree: string +} + +export type HomeServerSnapshot = { + readonly key: ServerConnection.Key + readonly failed: boolean + readonly connected: boolean + /** The server's project list loaded, and the directories an older build listed for it are migrated. */ + readonly projectsReady: boolean + readonly usedProjects: readonly HomeProjectItem[] +} + +export type HomeEnvSnapshot = { + /** The stored layout, the stored servers and the servers plugins contribute have all loaded. */ + readonly hydrated: boolean + /** What `layout.home.selection` holds now. */ + readonly stored: HomeProjectSelection + /** The servers Home lists, in order. */ + readonly servers: readonly HomeServerSnapshot[] +} + +/** The worktree inventory demand of the selected project, once per connected server and project. */ +export type HomeWorktreeSync = + | { readonly status: "idle" } + | { + readonly status: "listing" + readonly attempt: number + readonly server: ServerConnection.Key + readonly projectID: string + } + | { readonly status: "listed"; readonly server: ServerConnection.Key; readonly projectID: string } + +type HomeSelectionBase = { + readonly issued: number + /** The selection storage holds, as last read or written. */ + readonly stored: HomeProjectSelection + readonly servers: readonly HomeServerSnapshot[] + /** A project add whose result selects the project, unless the user selects something else first. */ + readonly adding: { readonly attempt: number; readonly server: ServerConnection.Key } | undefined + readonly worktrees: HomeWorktreeSync +} + +/** + * Home's server and project selection: + * - `hydrating`: the layout or a server source has not loaded. Home shows the stored server when it is listed and the + * first server otherwise, and writes nothing. A selection the user makes meanwhile is `override`, which wins. + * - `verifying`: the server is listed, and the directory waits for that server's projects before it is kept or cleared. + * - `ready`: the server and its optional used project are checked against the loaded state. + * - `disposed`: Home unmounted; late results are ignored. + */ +export type HomeSelectionState = + | (HomeSelectionBase & { readonly status: "hydrating"; readonly override: HomeProjectSelection | undefined }) + | (HomeSelectionBase & { + readonly status: "verifying" + readonly server: ServerConnection.Key + readonly directory: string + }) + | (HomeSelectionBase & { + readonly status: "ready" + readonly server: ServerConnection.Key + readonly project: HomeProjectItem | undefined + }) + | { readonly status: "disposed" } + +export type HomeSelectionEvent = + | { readonly type: "env.synced"; readonly env: HomeEnvSnapshot } + | { readonly type: "server.focused"; readonly server: ServerConnection.Key } + | { readonly type: "project.toggled"; readonly server: ServerConnection.Key; readonly directory: string } + | { readonly type: "project.add"; readonly server: ServerConnection.Key; readonly directories: readonly string[] } + | { readonly type: "project.added"; readonly attempt: number; readonly project: HomeProjectItem | undefined } + | { readonly type: "worktrees.listed"; readonly attempt: number } + | { readonly type: "disposed" } + +export type HomeSelectionEffect = + | { readonly type: "selection.persist"; readonly selection: HomeProjectSelection } + | { + readonly type: "project.add" + readonly attempt: number + readonly server: ServerConnection.Key + readonly directories: readonly string[] + } + | { + readonly type: "worktrees.list" + readonly attempt: number + readonly server: ServerConnection.Key + readonly projectID: string + } + | { readonly type: "worktrees.refresh"; readonly server: ServerConnection.Key; readonly projectID: string } + +export type HomeSelectionTransition = { + readonly state: HomeSelectionState + readonly effects: readonly HomeSelectionEffect[] +} + +type LiveState = Exclude + +const IDLE: HomeWorktreeSync = Object.freeze({ status: "idle" }) + +const DISPOSED: HomeSelectionState = Object.freeze({ status: "disposed" }) + +const NONE: readonly HomeSelectionEffect[] = Object.freeze([]) + +export const INITIAL_HOME_SELECTION_STATE: HomeSelectionState = Object.freeze({ + status: "hydrating", + issued: 0, + stored: Object.freeze({}), + servers: Object.freeze([]), + adding: undefined, + worktrees: IDLE, + override: undefined, +}) + +export function transitionHomeSelection(state: HomeSelectionState, event: HomeSelectionEvent): HomeSelectionTransition { + if (state.status === "disposed") return { state, effects: NONE } + + if (event.type === "disposed") return { state: DISPOSED, effects: NONE } + + if (event.type === "env.synced") return synced(state, event.env) + + if (event.type === "server.focused") return choose(state, { server: event.server }) + + if (event.type === "project.toggled") { + const entry = state.servers.find((server) => server.key === event.server) + const project = entry && !entry.failed ? findProject(entry, event.directory) : undefined + + if (!entry || !project) return { state, effects: NONE } + + return choose(state, toggleHomeProjectSelection(selectHomeSelection(state), entry.key, project.worktree)) + } + + if (event.type === "project.add") { + if (event.directories.length === 0) return { state, effects: NONE } + const attempt = state.issued + 1 + + return { + state: { ...state, issued: attempt, adding: { attempt, server: event.server } }, + effects: [{ type: "project.add", attempt, server: event.server, directories: event.directories }], + } + } + + if (event.type === "project.added") { + if (state.adding?.attempt !== event.attempt) return { state, effects: NONE } + + if (!event.project) return { state: { ...state, adding: undefined }, effects: NONE } + + return choose(state, { server: state.adding.server, directory: event.project.worktree }) + } + + const sync = state.worktrees + + if (sync.status !== "listing" || sync.attempt !== event.attempt) return { state, effects: NONE } + + return { + state: { ...state, worktrees: { status: "listed", server: sync.server, projectID: sync.projectID } }, + effects: [{ type: "worktrees.refresh", server: sync.server, projectID: sync.projectID }], + } +} + +/** What Home shows as selected: always a listed server while there is one, and a used project's own path. */ +export function selectHomeSelection(state: HomeSelectionState): HomeProjectSelection { + if (state.status === "disposed") return {} + + if (state.status === "verifying") return { server: state.server, directory: state.directory } + + if (state.status === "ready") + return state.project ? { server: state.server, directory: state.project.worktree } : { server: state.server } + + const target = state.override ?? state.stored + const entry = state.servers.find((server) => server.key === target.server) + + if (!entry) return state.servers[0] ? { server: state.servers[0].key } : {} + + if (!target.directory) return { server: entry.key } + + return { server: entry.key, directory: findProject(entry, target.directory)?.worktree ?? target.directory } +} + +export function sameHomeSelection(a: HomeProjectSelection | undefined, b: HomeProjectSelection | undefined) { + return a?.server === b?.server && a?.directory === b?.directory +} + +function synced(state: LiveState, env: HomeEnvSnapshot): HomeSelectionTransition { + const servers = sameServers(state.servers, env.servers) ? state.servers : env.servers + + if (state.status === "hydrating") { + const next = { ...state, servers, stored: selection(env.stored.server, env.stored.directory) } + + // Until everything loaded, the stored server may be missing only because its source has not reported yet. + if (!env.hydrated) return finish(state, next, NONE) + + return place(state, next, state.override ?? next.stored) + } + + // Another part of the app wrote the selection, such as a session's "Show in Home". + const external = !sameHomeSelection(env.stored, state.stored) + + const next = { + ...state, + servers, + stored: external ? selection(env.stored.server, env.stored.directory) : state.stored, + adding: external ? undefined : state.adding, + } + + return place(state, next, external ? next.stored : selectHomeSelection(state)) +} + +// A selection the user made: it wins over a project add still running. +function choose(state: LiveState, target: HomeProjectSelection): HomeSelectionTransition { + if (state.status === "hydrating") + return finish(state, { ...state, adding: undefined, override: selection(target.server, target.directory) }, NONE) + + return place(state, { ...state, adding: undefined }, target) +} + +// Checks `target` against the listed servers and writes what storage does not hold yet. +function place(prev: LiveState, base: HomeSelectionBase, target: HomeProjectSelection): HomeSelectionTransition { + const fields = { + issued: base.issued, + stored: base.stored, + servers: base.servers, + adding: base.adding, + worktrees: base.worktrees, + } + + const entry = base.servers.find((server) => server.key === target.server) + const first = base.servers[0] + + // Home always lists a server; without one the selection stays as it is rather than being cleared. + if (!first) return finish(prev, { ...prev, ...fields }, NONE) + + const next: LiveState = (() => { + // The selected server is gone: its directory belonged to it, so only the first server is kept. + if (!entry) return { ...fields, status: "ready", server: first.key, project: undefined } + + if (!target.directory) return { ...fields, status: "ready", server: entry.key, project: undefined } + + if (!entry.projectsReady) return { ...fields, status: "verifying", server: entry.key, directory: target.directory } + + return { ...fields, status: "ready", server: entry.key, project: findProject(entry, target.directory) } + })() + + const persisted = selectHomeSelection(next) + + if (sameHomeSelection(persisted, base.stored)) return finish(prev, next, NONE) + + return finish(prev, { ...next, stored: persisted }, [{ type: "selection.persist", selection: persisted }]) +} + +// Starts the worktree demand when the selected used project changes or its server connects, and drops it otherwise. +function finish(prev: LiveState, next: LiveState, effects: readonly HomeSelectionEffect[]): HomeSelectionTransition { + const target = worktreeTarget(next) + const sync = next.worktrees + + const kept = target + ? sync.status !== "idle" && sync.server === target.server && sync.projectID === target.projectID + : sync.status === "idle" + + if (kept) + return effects.length === 0 && sameState(prev, next) ? { state: prev, effects: NONE } : { state: next, effects } + + if (!target) return { state: { ...next, worktrees: IDLE }, effects } + + const attempt = next.issued + 1 + + return { + state: { ...next, issued: attempt, worktrees: { status: "listing", attempt, ...target } }, + effects: [...effects, { type: "worktrees.list", attempt, ...target }], + } +} + +function worktreeTarget(state: LiveState) { + const current = selectHomeSelection(state) + const entry = state.servers.find((server) => server.key === current.server) + + if (!entry?.connected || !current.directory) return + const project = findProject(entry, current.directory) + + if (!project) return + + return { server: entry.key, projectID: project.id } +} + +function sameState(a: LiveState, b: LiveState) { + if ( + a.status !== b.status || + a.issued !== b.issued || + a.servers !== b.servers || + a.adding !== b.adding || + a.worktrees !== b.worktrees || + !sameHomeSelection(a.stored, b.stored) + ) + return false + + if (a.status === "hydrating" && b.status === "hydrating") + return a.override === b.override || (!!a.override && !!b.override && sameHomeSelection(a.override, b.override)) + + if (a.status === "verifying" && b.status === "verifying") return a.server === b.server && a.directory === b.directory + + if (a.status === "ready" && b.status === "ready") + return a.server === b.server && a.project?.id === b.project?.id && a.project?.worktree === b.project?.worktree + + return false +} + +function sameServers(a: readonly HomeServerSnapshot[], b: readonly HomeServerSnapshot[]) { + return ( + a.length === b.length && + a.every((item, index) => { + const other = b[index]! + + return ( + item.key === other.key && + item.failed === other.failed && + item.connected === other.connected && + item.projectsReady === other.projectsReady && + item.usedProjects.length === other.usedProjects.length && + item.usedProjects.every( + (project, at) => + project.id === other.usedProjects[at]!.id && project.worktree === other.usedProjects[at]!.worktree, + ) + ) + }) + ) +} + +function findProject(server: HomeServerSnapshot, directory: string) { + const key = pathKey(directory) + + return server.usedProjects.find((project) => pathKey(project.worktree) === key) +} + +// A new object every time: `layout.home.setSelection` reconciles it into the layout store. +function selection(server: ServerConnection.Key | undefined, directory: string | undefined): HomeProjectSelection { + if (!server) return {} + + return directory ? { server, directory } : { server } +} diff --git a/packages/app/src/home/model.ts b/packages/app/src/home/model.ts index 9f0dd8082c7f..1cd712a52574 100644 --- a/packages/app/src/home/model.ts +++ b/packages/app/src/home/model.ts @@ -1,76 +1,132 @@ import { useGlobal, useServerCtx } from "@/runtime/server/runtime" -import { type HomeProjectSelection, useLayout } from "@/shell/state/layout" +import { useLayout } from "@/shell/state/layout" import { ServerConnection, useServers } from "@/runtime/server/registry" import { isServerFailed } from "@/runtime/server/health-machine" +import { usePluginServers } from "@/runtime/plugin/servers" import { createProjectSessionActions } from "@/shell/tabs/project-sessions" -import { toggleHomeProjectSelection } from "@/shell/layout/helpers" -import { createEffect, createMemo } from "solid-js" +import { batch, createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js" import { pathKey } from "@/workspaces/path-key" import { addProjects } from "./projects/add" +import { + INITIAL_HOME_SELECTION_STATE, + sameHomeSelection, + selectHomeSelection, + transitionHomeSelection, + type HomeEnvSnapshot, + type HomeSelectionEffect, + type HomeSelectionEvent, +} from "./machine" export function createHomeController() { const layout = useLayout() const global = useGlobal() const servers = useServers() + const pluginServers = usePluginServers() const sessions = createProjectSessionActions() - const selection = layout.home.selection - const focusedServer = createMemo( - () => servers.visible.find((conn) => ServerConnection.key(conn) === selection().server) ?? servers.visible[0], + const env = createMemo( + (): HomeEnvSnapshot => ({ + hydrated: layout.ready() && servers.hydrated() && pluginServers.ready(), + stored: { server: layout.home.selection().server, directory: layout.home.selection().directory }, + servers: servers.visible.map((conn) => { + const key = ServerConnection.key(conn) + const ctx = global.serverCtx(key) + + return { + key, + failed: isServerFailed(global.servers.health[key]), + connected: ctx?.sdk.connection.status() === "connected", + projectsReady: !!ctx?.sync.project.ready() && servers.projects.forServer(key).legacy() === undefined, + usedProjects: (ctx?.projects.used() ?? []).map((project) => ({ id: project.id, worktree: project.worktree })), + } + }), + }), ) - const focusedServerCtx = useServerCtx(focusedServer) - const focusedSync = () => focusedServerCtx()?.sync - // Home lists the server's projects this client has used. - const projects = createMemo(() => focusedServerCtx()?.projects.used() ?? []) - const selectedProject = createMemo(() => projects().find((project) => project.worktree === selection().directory)) + // Seeded synchronously, so the first render already shows a listed server. + const initial = transitionHomeSelection(INITIAL_HOME_SELECTION_STATE, { type: "env.synced", env: untrack(env) }) + const [machine, setMachine] = createSignal(initial.state) - const newSessionProject = createMemo(() => selectedProject() ?? focusedServerCtx()?.projects.last() ?? projects()[0]) + const dispatch = (event: HomeSelectionEvent) => { + const result = transitionHomeSelection(untrack(machine), event) - createEffect(() => { - const list = servers.visible + if (result.state !== untrack(machine)) setMachine(result.state) + result.effects.forEach(run) + } - if (list.some((conn) => ServerConnection.key(conn) === selection().server)) return - const conn = list[0] + // A user action can follow a server change in the same update, before the effect below reports it. + const send = (event: HomeSelectionEvent) => + untrack(() => + batch(() => { + dispatch({ type: "env.synced", env: env() }) + dispatch(event) + }), + ) + + function run(effect: HomeSelectionEffect) { + if (effect.type === "selection.persist") return layout.home.setSelection(effect.selection) + + if (effect.type === "worktrees.refresh") + return void global.serverCtx(effect.server)?.sync.worktrees.refresh(effect.projectID) + + const ctx = global.serverCtx(effect.server) + + if (effect.type === "worktrees.list") { + // The inventory read never rejects; a failed read still asks the server to discover worktrees. + if (!ctx) return dispatch({ type: "worktrees.listed", attempt: effect.attempt }) + + return void ctx.sync.worktrees + .list(effect.projectID) + .then(() => dispatch({ type: "worktrees.listed", attempt: effect.attempt })) + } + + if (!ctx) return dispatch({ type: "project.added", attempt: effect.attempt, project: undefined }) + + void addProjects(ctx, [...effect.directories]).then( + (project) => + send({ + type: "project.added", + attempt: effect.attempt, + project: project && { id: project.id, worktree: project.worktree }, + }), + () => dispatch({ type: "project.added", attempt: effect.attempt, project: undefined }), + ) + } - if (conn) setSelection({ server: ServerConnection.key(conn) }) - }) - createEffect(() => { - const ctx = focusedServerCtx() - const id = selectedProject()?.id + initial.effects.forEach(run) - if (!ctx || !id || ctx.sdk.connection.status() !== "connected") return - // Selecting a project is the demand for its worktree inventory: the session filter spans its worktrees. - void ctx.sync.worktrees.list(id).then(() => ctx.sync.worktrees.refresh(id)) - }) createEffect(() => { - // The project list is empty until the server store hydrates and the server answers; clearing the restored - // selection against it would persist the loss. - if (!servers.hydrated()) return - const current = selection() - const directory = current.directory + const current = env() + untrack(() => dispatch({ type: "env.synced", env: current })) + }) - if (!directory) return - const conn = servers.visible.find((conn) => ServerConnection.key(conn) === current.server) + onCleanup(() => dispatch({ type: "disposed" })) - if (!conn) return - const ctx = global.serverCtx(ServerConnection.key(conn)) + const selection = createMemo(() => selectHomeSelection(machine()), undefined, { equals: sameHomeSelection }) - if (!ctx?.sync.project.ready()) return + const focusedServer = createMemo(() => { + const key = selection().server - if (ctx.projects.used().some((project) => pathKey(project.worktree) === pathKey(directory))) return - setSelection({ server: current.server }) + return key ? servers.visible.find((conn) => ServerConnection.key(conn) === key) : undefined }) - function setSelection(next: HomeProjectSelection) { - layout.home.setSelection(next) - } + const focusedServerCtx = useServerCtx(focusedServer) + const focusedSync = () => focusedServerCtx()?.sync + // Home lists the server's projects this client has used. + const projects = createMemo(() => focusedServerCtx()?.projects.used() ?? []) + + const selectedProject = createMemo(() => { + const directory = selection().directory + + return directory ? projects().find((project) => pathKey(project.worktree) === pathKey(directory)) : undefined + }) + + const newSessionProject = createMemo(() => selectedProject() ?? focusedServerCtx()?.projects.last() ?? projects()[0]) return { selection: { value: selection, - set: setSelection, - focusServer: (conn: ServerConnection.Any) => setSelection({ server: ServerConnection.key(conn) }), + focusServer: (conn: ServerConnection.Any) => send({ type: "server.focused", server: ServerConnection.key(conn) }), }, server: { list: () => servers.visible, @@ -86,29 +142,10 @@ export function createHomeController() { selected: selectedProject, newSession: newSessionProject, forServer: (conn: ServerConnection.Any) => global.serverCtx(ServerConnection.key(conn))?.projects.used() ?? [], - select: (conn: ServerConnection.Any, directory: string) => { - const key = ServerConnection.key(conn) - - if (isServerFailed(global.servers.health[key])) return - - if ( - !global - .serverCtx(key) - ?.projects.used() - .some((project) => project.worktree === directory) - ) - return - setSelection(toggleHomeProjectSelection(selection(), key, directory)) - }, - add: async (conn: ServerConnection.Any, directories: string[]) => { - const ctx = global.serverCtx(ServerConnection.key(conn)) - - if (!ctx) return - const project = await addProjects(ctx, directories) - - if (!project) return - setSelection({ server: ServerConnection.key(conn), directory: project.worktree }) - }, + select: (conn: ServerConnection.Any, directory: string) => + send({ type: "project.toggled", server: ServerConnection.key(conn), directory }), + add: (conn: ServerConnection.Any, directories: string[]) => + send({ type: "project.add", server: ServerConnection.key(conn), directories }), openNewSession: () => { const conn = focusedServer() const project = newSessionProject() diff --git a/packages/app/src/home/projects/actions.tsx b/packages/app/src/home/projects/actions.tsx index 91f1d4805b39..39b1e446c262 100644 --- a/packages/app/src/home/projects/actions.tsx +++ b/packages/app/src/home/projects/actions.tsx @@ -1,5 +1,8 @@ import { Schema } from "effect" +import { useLocation } from "@solidjs/router" +import { createSignal, onCleanup, untrack } from "solid-js" import { useDialog } from "@opencode/ui/context/dialog" +import { toaster } from "@opencode/ui/toast" import { useLanguage } from "@/runtime/i18n/language" import { usePlatform } from "@/runtime/platform/platform" import { ServerConnection } from "@/runtime/server/registry" @@ -10,11 +13,21 @@ import { errorMessage } from "@/shell/layout/helpers" import { showToast } from "@/shell/notifications/toast" import type { LocalProject } from "@/shell/state/layout" import { createProjectSessionActions } from "@/shell/tabs/project-sessions" +import { + INITIAL_PROJECT_IMPORT_STATE, + selectProjectImporting, + transitionProjectImport, + type ProjectImportEffect, + type ProjectImportEvent, + type ProjectImportTarget, +} from "./import-machine" import { useRevealProject } from "./reveal" export function createProjectActions() { const platform = usePlatform() + const location = useLocation() + const dialog = useDialog() const language = useLanguage() @@ -44,6 +57,102 @@ export function createProjectActions() { const directories = (project: LocalProject) => [project.worktree, ...(project.sandboxes ?? [])] + const currentPath = () => location.pathname + location.search + const [importState, setImportState] = createSignal(INITIAL_PROJECT_IMPORT_STATE) + let pendingToast: number | undefined + + const dispatchImport = (event: ProjectImportEvent) => { + const previous = untrack(importState) + const next = transitionProjectImport(previous, event) + + if (next.state !== previous) setImportState(next.state) + next.effects.forEach((effect) => + Promise.try(() => runImport(effect)).catch((cause: unknown) => console.error("[project.import]", cause)), + ) + } + + function runImport(effect: ProjectImportEffect) { + if (effect.type === "picker.open") { + // Keep only the file: the picker releases its read access once the callback returns, not after the upload. + let picked: File | undefined + + if (!platform.openAttachmentPickerDialog) + return dispatchImport({ type: "picker.closed", attempt: effect.attempt, file: undefined }) + void platform + .openAttachmentPickerDialog( + { title: language.t("command.session.import"), accept: ["application/json"], extensions: ["json"] }, + async (file) => { + picked = file + }, + ) + .then( + () => dispatchImport({ type: "picker.closed", attempt: effect.attempt, file: picked }), + (cause: unknown) => dispatchImport({ type: "picker.failed", attempt: effect.attempt, cause }), + ) + + return + } + + if (effect.type === "upload.start") { + void upload(effect.target, effect.file).then( + (session) => + dispatchImport({ + type: "import.succeeded", + attempt: effect.attempt, + target: effect.target, + session, + currentPath: untrack(currentPath), + }), + (cause: unknown) => dispatchImport({ type: "import.failed", attempt: effect.attempt, cause }), + ) + + return + } + + if (effect.type === "toast.pending.show") { + pendingToast = showToast({ + variant: "loading", + title: language.t("toast.session.import.pending"), + persistent: true, + }) + + return + } + + if (effect.type === "toast.pending.dismiss") { + if (pendingToast !== undefined) toaster.dismiss(pendingToast) + pendingToast = undefined + + return + } + + if (effect.type === "toast.failed") + return showToast({ + title: language.t("common.requestFailed"), + description: errorMessage(effect.cause, language.t("common.requestFailed")), + }) + + if (effect.type === "session.open") + return sessions.openProjectSession(effect.target.conn, effect.target.worktree, effect.session) + untrack(() => global.serverCtx(ServerConnection.key(effect.target.conn)))?.data.session.remember(effect.session) + } + + async function upload(target: ProjectImportTarget, file: File) { + const data = await Schema.decodeUnknownPromise(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)))( + await file.text(), + ) + + const ctx = untrack(() => global.serverCtx(ServerConnection.key(target.conn))) + + if (!ctx) throw new Error(language.t("common.requestFailed")) + const api = ctx.sdk.api.experimental.session + + // SAFETY: the import endpoint validates the transcript, including exports written by earlier releases. + return api.import({ ...data, location: { directory: target.worktree } } as Parameters[0]) + } + + onCleanup(() => dispatchImport({ type: "disposed" })) + return { authenticate, editServer, @@ -52,35 +161,12 @@ export function createProjectActions() { sessions.openProjectNewSession(conn, directory) }, canImportSession: !!platform.openAttachmentPickerDialog, + importingSession: () => selectProjectImporting(importState()), importSession(conn: ServerConnection.Any, project: LocalProject) { - if (!platform.openAttachmentPickerDialog) return - void platform - .openAttachmentPickerDialog( - { title: language.t("command.session.import"), accept: ["application/json"], extensions: ["json"] }, - async (file) => { - const data = await Schema.decodeUnknownPromise( - Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)), - )(await file.text()) - - const ctx = global.serverCtx(ServerConnection.key(conn)) - - if (!ctx) throw new Error(language.t("common.requestFailed")) - const api = ctx.sdk.api.experimental.session - - // SAFETY: the import endpoint validates the transcript, including exports written by earlier releases. - const imported = await api.import({ ...data, location: { directory: project.worktree } } as Parameters< - typeof api.import - >[0]) - - sessions.openProjectSession(conn, project.worktree, imported) - }, - ) - .catch((cause: unknown) => { - showToast({ - title: language.t("common.requestFailed"), - description: errorMessage(cause, language.t("common.requestFailed")), - }) - }) + dispatchImport({ + type: "import.requested", + target: { conn, worktree: project.worktree, originPath: currentPath() }, + }) }, edit(conn: ServerConnection.Any, project: LocalProject) { settings.openProject({ server: ServerConnection.key(conn), project: project.worktree }) diff --git a/packages/app/src/home/projects/controller.tsx b/packages/app/src/home/projects/controller.tsx index 7fbbe36bf423..3931c5d50179 100644 --- a/packages/app/src/home/projects/controller.tsx +++ b/packages/app/src/home/projects/controller.tsx @@ -43,7 +43,7 @@ export function createHomeProjectsController(home: HomeController) { server: conn, title: language.t("command.project.open"), multiple: true, - onSelect: (result) => void home.project.add(conn, homeProjectDirectories(result)), + onSelect: (result) => home.project.add(conn, homeProjectDirectories(result)), }) } @@ -84,6 +84,7 @@ export function createHomeProjectsController(home: HomeController) { add: home.project.add, openNewSession: actions.openNewSession, canImportSession: actions.canImportSession, + importingSession: actions.importingSession, importSession: actions.importSession, edit: actions.edit, hasUnread: actions.hasUnread, diff --git a/packages/app/src/home/projects/import-machine.test.ts b/packages/app/src/home/projects/import-machine.test.ts new file mode 100644 index 000000000000..f6b57d020b2c --- /dev/null +++ b/packages/app/src/home/projects/import-machine.test.ts @@ -0,0 +1,117 @@ +import { expect, test } from "bun:test" +import type { SessionInfo } from "@opencode/client/promise" +import type { ServerConnection } from "@/runtime/server/registry" +import { + INITIAL_PROJECT_IMPORT_STATE, + selectProjectImporting, + transitionProjectImport, + type ProjectImportEvent, + type ProjectImportTransition, +} from "./import-machine" + +const conn: ServerConnection.Any = { type: "sidecar", variant: "base", http: { url: "http://127.0.0.1:4096" } } + +const target = { conn, worktree: "/repo", originPath: "/" } + +const file = new File(["{}"], "transcript.json") + +/* oxlint-disable anti-slop/require-safety-comment-for-type-assertion -- the machine passes the session through untouched */ +const imported = { id: "ses_imported" } as SessionInfo + +function replay(events: ProjectImportEvent[]) { + return events.reduce((steps, event) => { + steps.push(transitionProjectImport(steps.at(-1)?.state ?? INITIAL_PROJECT_IMPORT_STATE, event)) + + return steps + }, []) +} + +const picked: ProjectImportEvent[] = [ + { type: "import.requested", target }, + { type: "picker.closed", attempt: 1, file }, +] + +test("an upload that lands after the user opened another session does not switch tabs", () => { + const [, uploading, moved] = replay([ + ...picked, + { type: "import.succeeded", attempt: 1, target, session: imported, currentPath: "/server/a/session/ses_other" }, + ]) + + const [, , stayed] = replay([ + ...picked, + { type: "import.succeeded", attempt: 1, target, session: imported, currentPath: "/" }, + ]) + + expect(uploading?.effects).toEqual([ + { type: "toast.pending.show" }, + { type: "upload.start", attempt: 1, target, file }, + ]) + expect(moved?.effects).toEqual([ + { type: "toast.pending.dismiss" }, + { type: "session.remember", target, session: imported }, + ]) + expect(stayed?.effects).toEqual([ + { type: "toast.pending.dismiss" }, + { type: "session.open", target, session: imported }, + ]) + expect(moved?.state).toEqual({ status: "idle", attempt: 1 }) +}) + +test("an upload that outlives Home still lands and reports, without taking over the window", () => { + const [, , disposed, succeeded] = replay([ + ...picked, + { type: "disposed" }, + { type: "import.succeeded", attempt: 1, target, session: imported, currentPath: "/" }, + ]) + + const [, , , failed] = replay([...picked, { type: "disposed" }, { type: "import.failed", attempt: 1, cause: "500" }]) + + expect(disposed?.effects).toEqual([]) + expect(succeeded?.state).toBe(disposed!.state) + expect(succeeded?.effects).toEqual([ + { type: "toast.pending.dismiss" }, + { type: "session.remember", target, session: imported }, + ]) + expect(failed?.effects).toEqual([{ type: "toast.pending.dismiss" }, { type: "toast.failed", cause: "500" }]) +}) + +test("Import session again while the picker is open or a transcript uploads starts nothing", () => { + const [picking, again, uploading, onceMore] = replay([ + { type: "import.requested", target }, + { type: "import.requested", target }, + { type: "picker.closed", attempt: 1, file }, + { type: "import.requested", target }, + ]) + + expect(picking?.effects).toEqual([{ type: "picker.open", attempt: 1 }]) + expect(selectProjectImporting(picking!.state)).toBe(true) + expect(again?.state).toBe(picking!.state) + expect(again?.effects).toEqual([]) + expect(selectProjectImporting(uploading!.state)).toBe(true) + expect(onceMore?.state).toBe(uploading!.state) + expect(onceMore?.effects).toEqual([]) +}) + +test("a cancelled picker is quiet, failures toast, and the next import starts a new attempt", () => { + const [, cancelled, retried, stale] = replay([ + { type: "import.requested", target }, + { type: "picker.closed", attempt: 1, file: undefined }, + { type: "import.requested", target }, + { type: "picker.closed", attempt: 1, file }, + ]) + + const [, pickerFailed] = replay([ + { type: "import.requested", target }, + { type: "picker.failed", attempt: 1, cause: "denied" }, + ]) + + const [, , uploadFailed] = replay([...picked, { type: "import.failed", attempt: 1, cause: "invalid" }]) + + expect(cancelled?.effects).toEqual([]) + expect(selectProjectImporting(cancelled!.state)).toBe(false) + expect(retried?.effects).toEqual([{ type: "picker.open", attempt: 2 }]) + expect(stale?.state).toBe(retried!.state) + expect(pickerFailed?.effects).toEqual([{ type: "toast.failed", cause: "denied" }]) + expect(uploadFailed?.effects).toEqual([{ type: "toast.pending.dismiss" }, { type: "toast.failed", cause: "invalid" }]) + expect(selectProjectImporting(uploadFailed!.state)).toBe(false) +}) diff --git a/packages/app/src/home/projects/import-machine.ts b/packages/app/src/home/projects/import-machine.ts new file mode 100644 index 000000000000..f357ba80a3ad --- /dev/null +++ b/packages/app/src/home/projects/import-machine.ts @@ -0,0 +1,133 @@ +import type { SessionInfo } from "@opencode/client/promise" +import type { ServerConnection } from "@/runtime/server/registry" + +/** Where the import was asked from: the imported session opens only while the user is still there. */ +export type ProjectImportTarget = { + readonly conn: ServerConnection.Any + readonly worktree: string + readonly originPath: string +} + +/** + * Importing a session transcript into a project: the file picker is open, or the transcript is uploading. One import at + * a time. An upload the owner outlives (`disposed`) still lands, and reports, without taking over the window. + */ +export type ProjectImportState = + | { readonly status: "idle"; readonly attempt: number } + | { readonly status: "picking"; readonly attempt: number; readonly target: ProjectImportTarget } + | { readonly status: "importing"; readonly attempt: number; readonly target: ProjectImportTarget } + | { readonly status: "disposed" } + +export type ProjectImportEvent = + | { readonly type: "import.requested"; readonly target: ProjectImportTarget } + /** `file`: undefined when the picker was cancelled. */ + | { readonly type: "picker.closed"; readonly attempt: number; readonly file: File | undefined } + | { readonly type: "picker.failed"; readonly attempt: number; readonly cause: unknown } + | { + readonly type: "import.succeeded" + readonly attempt: number + readonly target: ProjectImportTarget + readonly session: SessionInfo + readonly currentPath: string + } + | { readonly type: "import.failed"; readonly attempt: number; readonly cause: unknown } + | { readonly type: "disposed" } + +export type ProjectImportEffect = + | { readonly type: "picker.open"; readonly attempt: number } + | { + readonly type: "upload.start" + readonly attempt: number + readonly target: ProjectImportTarget + readonly file: File + } + | { readonly type: "toast.pending.show" } + | { readonly type: "toast.pending.dismiss" } + | { readonly type: "toast.failed"; readonly cause: unknown } + | { readonly type: "session.open"; readonly target: ProjectImportTarget; readonly session: SessionInfo } + /** The imported session joins the lists without switching tabs. */ + | { readonly type: "session.remember"; readonly target: ProjectImportTarget; readonly session: SessionInfo } + +export type ProjectImportTransition = { + readonly state: ProjectImportState + readonly effects: readonly ProjectImportEffect[] +} + +const NO_EFFECTS: readonly never[] = Object.freeze([]) + +const PENDING_DISMISS: ProjectImportEffect = Object.freeze({ type: "toast.pending.dismiss" }) + +export const INITIAL_PROJECT_IMPORT_STATE: ProjectImportState = Object.freeze({ status: "idle", attempt: 0 }) + +const DISPOSED: ProjectImportState = Object.freeze({ status: "disposed" }) + +export function transitionProjectImport(state: ProjectImportState, event: ProjectImportEvent): ProjectImportTransition { + if (state.status === "disposed") { + // Only an upload can outlive its owner, and only one runs at a time. + if (event.type === "import.succeeded") + return { + state, + effects: [PENDING_DISMISS, { type: "session.remember", target: event.target, session: event.session }], + } + + if (event.type === "import.failed") + return { state, effects: [PENDING_DISMISS, { type: "toast.failed", cause: event.cause }] } + + return { state, effects: NO_EFFECTS } + } + + if (event.type === "disposed") return { state: DISPOSED, effects: NO_EFFECTS } + + if (event.type === "import.requested") { + // A second Import session while the picker is open or a transcript uploads would run two imports. + if (state.status !== "idle") return { state, effects: NO_EFFECTS } + const attempt = state.attempt + 1 + + return { + state: { status: "picking", attempt, target: event.target }, + effects: [{ type: "picker.open", attempt }], + } + } + + if (state.status === "idle" || event.attempt !== state.attempt) return { state, effects: NO_EFFECTS } + + const idle: ProjectImportState = { status: "idle", attempt: state.attempt } + + if (state.status === "picking") { + if (event.type === "picker.failed") return { state: idle, effects: [{ type: "toast.failed", cause: event.cause }] } + + if (event.type !== "picker.closed") return { state, effects: NO_EFFECTS } + + if (!event.file) return { state: idle, effects: NO_EFFECTS } + + return { + state: { status: "importing", attempt: state.attempt, target: state.target }, + effects: [ + { type: "toast.pending.show" }, + { type: "upload.start", attempt: state.attempt, target: state.target, file: event.file }, + ], + } + } + + if (event.type === "import.failed") + return { state: idle, effects: [PENDING_DISMISS, { type: "toast.failed", cause: event.cause }] } + + if (event.type !== "import.succeeded") return { state, effects: NO_EFFECTS } + + // The user moved on while the transcript uploaded: the import must not pull them away. + return { + state: idle, + effects: [ + PENDING_DISMISS, + { + type: event.currentPath === state.target.originPath ? "session.open" : "session.remember", + target: state.target, + session: event.session, + }, + ], + } +} + +export function selectProjectImporting(state: ProjectImportState) { + return state.status === "picking" || state.status === "importing" +} diff --git a/packages/app/src/home/projects/menu.tsx b/packages/app/src/home/projects/menu.tsx index 632825868082..9f15ef30ca26 100644 --- a/packages/app/src/home/projects/menu.tsx +++ b/packages/app/src/home/projects/menu.tsx @@ -11,6 +11,7 @@ export function ProjectMenuItems(props: { project: LocalProject unread: boolean canImportSession: boolean + importingSession?: boolean canRevealProject: (server: ServerConnection.Any) => boolean onOpenProjectNewSession: (server: ServerConnection.Any, directory: string) => void onImportSession: (server: ServerConnection.Any, project: LocalProject) => void @@ -29,7 +30,10 @@ export function ProjectMenuItems(props: { {language.t("command.session.new")} - props.onImportSession(props.server, props.project)}> + props.onImportSession(props.server, props.project)} + > {language.t("command.session.import")} diff --git a/packages/app/src/home/projects/region.tsx b/packages/app/src/home/projects/region.tsx index 998063d37f30..7853e41a9fa7 100644 --- a/packages/app/src/home/projects/region.tsx +++ b/packages/app/src/home/projects/region.tsx @@ -33,6 +33,7 @@ export function HomeProjects(props: { onSelectProject={props.projects.project.select} onOpenProjectNewSession={props.projects.project.openNewSession} canImportSession={props.projects.project.canImportSession} + importingSession={props.projects.project.importingSession()} onImportSession={props.projects.project.importSession} onEditProject={props.projects.project.edit} onRevealProject={props.projects.project.reveal} diff --git a/packages/app/src/home/projects/view.tsx b/packages/app/src/home/projects/view.tsx index 80b4d0a3ea94..6c6c42f7ad46 100644 --- a/packages/app/src/home/projects/view.tsx +++ b/packages/app/src/home/projects/view.tsx @@ -72,6 +72,7 @@ export type HomeProjectsViewProps = { onSelectProject: (server: ServerConnection.Any, directory: string) => void onOpenProjectNewSession: (server: ServerConnection.Any, directory: string) => void canImportSession: boolean + importingSession?: boolean onImportSession: (server: ServerConnection.Any, project: LocalProject) => void onEditProject: (server: ServerConnection.Any, project: LocalProject) => void onRevealProject: (server: ServerConnection.Any, project: LocalProject) => void diff --git a/packages/app/src/home/sessions/controller.tsx b/packages/app/src/home/sessions/controller.tsx index 571beeeffd23..2babe18602d9 100644 --- a/packages/app/src/home/sessions/controller.tsx +++ b/packages/app/src/home/sessions/controller.tsx @@ -2,25 +2,55 @@ import type { SessionInfo } from "@opencode/client/promise" import { useDialog } from "@opencode/ui/context/dialog" import { Button } from "@opencode/ui/button" import { DialogFooter, DialogHeader, DialogTitleGroup, Dialog } from "@opencode/ui/dialog" -import { useQuery, useQueryClient } from "@tanstack/solid-query" -import { type Accessor, createEffect, createMemo, type JSX, startTransition, untrack } from "solid-js" +import { prefersReducedMotion } from "@opencode/ui/motion" +import { hashKey, onlineManager, useQueryClient } from "@tanstack/solid-query" +import { + type Accessor, + createEffect, + createMemo, + createSignal, + type JSX, + onCleanup, + startTransition, + untrack, +} from "solid-js" import { notifySessionTabsRemoved } from "@/shell/titlebar/session-events" import { useCommand } from "@/shell/commands/command" import { HOME_SESSION_LIMIT, mergeHomeSessionIndex, retainHomeSessions } from "@/home/sessions/index" import type { LocalProject } from "@/shell/state/layout" import { useLanguage } from "@/runtime/i18n/language" import { ServerConnection } from "@/runtime/server/registry" +import { useGlobal } from "@/runtime/server/runtime" import { sessionHasOpenTab, useTabs } from "@/shell/tabs/tabs" import { errorMessage } from "@/shell/layout/helpers" import { useSessionTabAvatarState } from "@/shell/layout/project-avatar-state" import { sessionTreeIDs } from "@/session/requests/session-request-tree" import { pathKey } from "@/workspaces/path-key" -import { fetchSessionExport, saveSessionExport, sessionExportFilename } from "@/session/commands/export" +import { createSessionExporter } from "@/session/commands/export-session" +import { + createSessionDeleteState, + selectSessionDeleteView, + SESSION_DELETE_TIMEOUT_MS, + transitionSessionDelete, + type SessionDeleteEffect, + type SessionDeleteEvent, +} from "@/session/delete-machine" import { usePlatform } from "@/runtime/platform/platform" import { sessionLabel, sessionTitle } from "@/session/title" import { showToast } from "@/shell/notifications/toast" import { archiveHomeSession } from "./archive" import { homeSessionsQuery } from "./queries" +import { + HOME_SESSIONS_STALE_MS, + INITIAL_HOME_SESSIONS_LOAD_STATE, + selectHomeSessionsListView, + selectHomeSessionsSearchLoading, + transitionHomeSessionsLoad, + type HomeSessionsLoadEffect, + type HomeSessionsLoadEvent, + type HomeSessionsTarget, + type HomeSessionsTimer, +} from "./load-machine" import type { HomeController } from "../model" import { buildHomeSessionRecords, homeProjectForSession, homeSessionLocation, type HomeSessionRecord } from "./records" @@ -41,6 +71,7 @@ export function createHomeSessionsController(home: HomeController) { const language = useLanguage() const platform = usePlatform() const queryClient = useQueryClient() + const global = useGlobal() const projectDirectories = createMemo(() => { const selected = home.selection.value().directory @@ -51,14 +82,151 @@ export function createHomeSessionsController(home: HomeController) { return project ? directories(project) : [selected] }) - const sessionLoad = useQuery(() => { - const ctx = home.server.focusedContext() - const conn = home.server.focused() + const [load, setLoad] = createSignal(INITIAL_HOME_SESSIONS_LOAD_STATE) + // Bumped when the shared index cache changes, so lists written by the sidebar, a rename or a delete show here. + const [cacheVersion, setCacheVersion] = createSignal(0) + const loadTimers: Partial>> = {} + + // Only a change of server or of its connection retargets the list. The cache is keyed by the connection itself. + const focus = createMemo( + () => { + const conn = home.server.focused() + + if (!conn) return + const key = ServerConnection.key(conn) + + return { conn, key, connection: homeSessionsConnection(conn, key) } + }, + undefined, + { equals: (a, b) => a?.conn === b?.conn && a?.connection === b?.connection }, + ) + + function homeSessionsConnection( + conn: ServerConnection.Any, + key: ServerConnection.Key, + ): HomeSessionsTarget["connection"] { + if (home.server.focusedContext()?.sdk.connection.status() === "connected") return "connected" + const health = home.server.health(conn) + + if (global.serverSignedOut(key) || health?.type === "unauthorized" || health?.type === "auth") return "auth" + + if (health?.type === "incompatible") return "incompatible" + + if (health?.type === "unreachable" || health?.type === "stopped") return "offline" + + return "connecting" + } + + function homeSessionsTarget(current = focus()): HomeSessionsTarget | undefined { + if (!current) return + const cache = queryClient.getQueryState(["home-sessions", current.conn]) + const cached = cache?.data !== undefined return { - ...homeSessionsQuery(conn, ctx), - enabled: !!ctx && ctx.sdk.connection.status() === "connected", + server: current.key, + connection: current.connection, + cached, + stale: !cached || cache.isInvalidated || Date.now() - cache.dataUpdatedAt >= HOME_SESSIONS_STALE_MS, } + } + + // Effects run untracked: a dispatch from an effect must not subscribe it to the machine or the server list. + const dispatchLoad = (event: HomeSessionsLoadEvent) => + untrack(() => { + const previous = load() + const next = transitionHomeSessionsLoad(previous, event) + + if (next.state !== previous) setLoad(next.state) + next.effects.forEach(runLoadEffect) + }) + + function runLoadEffect(effect: HomeSessionsLoadEffect) { + if (effect.type === "timer.start") { + clearTimeout(loadTimers[effect.timer]) + loadTimers[effect.timer] = setTimeout(() => dispatchLoad(effect.event), effect.delayMs) + + return + } + + if (effect.type === "timer.stop") { + clearTimeout(loadTimers[effect.timer]) + loadTimers[effect.timer] = undefined + + return + } + + // A probe that finds the server still away leaves the connection unchanged, so report the target again. + if (effect.type === "probe.servers") { + void global.servers.retry().then(() => dispatchLoad({ type: "context.changed", target: homeSessionsTarget() })) + + return + } + + const conn = home.server.list().find((item) => ServerConnection.key(item) === effect.server) + + if (effect.type === "fetch.cancel") { + if (conn) void queryClient.cancelQueries({ queryKey: ["home-sessions", conn], exact: true }) + + return + } + + const attempt = effect.attempt + const ctx = conn ? home.server.context(conn) : undefined + + if (!conn || !ctx) { + dispatchLoad({ type: "fetch.failed", attempt, message: language.t("common.requestFailed") }) + + return + } + + // Through the shared query, so a fetch the sidebar already started is joined and the result lands in its cache. + void queryClient.fetchQuery({ ...homeSessionsQuery(conn, ctx), staleTime: 0 }).then( + () => dispatchLoad({ type: "fetch.succeeded", attempt, reducedMotion: prefersReducedMotion() }), + (cause) => + dispatchLoad({ + type: "fetch.failed", + attempt, + message: errorMessage(cause, language.t("common.requestFailed")), + }), + ) + } + + createEffect(() => { + const current = focus() + untrack(() => dispatchLoad({ type: "context.changed", target: homeSessionsTarget(current) })) + }) + + // The query refetched on invalidation and on reconnect while stale; the machine keeps both. + onCleanup( + queryClient.getQueryCache().subscribe((event) => { + if (event.type !== "updated" || event.query.queryKey[0] !== "home-sessions") return + setCacheVersion((version) => version + 1) + + if (event.action.type !== "invalidate") return + const current = untrack(focus) + + if (current?.connection !== "connected" || event.query.queryHash !== hashKey(["home-sessions", current.conn])) + return + dispatchLoad({ type: "refresh", server: current.key }) + }), + ) + onCleanup( + onlineManager.subscribe((online) => { + const target = untrack(homeSessionsTarget) + + if (!online || target?.connection !== "connected" || !target.stale) return + dispatchLoad({ type: "refresh", server: target.server }) + }), + ) + onCleanup(() => dispatchLoad({ type: "disposed" })) + + const fetchedSessions = createMemo(() => { + // The machine settles after the cache write it reports, so a new phase always reads the new list. + cacheVersion() + load() + const conn = home.server.focused() + + return (conn && queryClient.getQueryData(["home-sessions", conn])) || [] }) const indexedSessions = createMemo(() => { @@ -68,9 +236,7 @@ export function createHomeSessionsController(home: HomeController) { if (!ctx || !conn) return [] return retainHomeSessions( - ctx.data.session.apply( - mergeHomeSessionIndex(sessionLoad.isPending ? [] : (sessionLoad.data?.() ?? []), ctx.data.session.list()), - ), + ctx.data.session.apply(mergeHomeSessionIndex(fetchedSessions(), ctx.data.session.list())), HOME_SESSION_LIMIT, Date.now(), ) @@ -166,7 +332,8 @@ export function createHomeSessionsController(home: HomeController) { }, ]) - const rename = async (server: ServerConnection.Key, session: SessionInfo, title: string) => { + // A save the caller cancelled still updates the list if the server took it. + const rename = async (server: ServerConnection.Key, session: SessionInfo, title: string, signal?: AbortSignal) => { const conn = home.server.list().find((item) => ServerConnection.key(item) === server) const ctx = conn ? home.server.context(conn) : undefined @@ -176,7 +343,7 @@ export function createHomeSessionsController(home: HomeController) { if (!next || next === sessionLabel(session)) return true return ctx.sdk.api.session - .update({ sessionID: session.id, title: next }) + .update({ sessionID: session.id, title: next }, { signal }) .then(() => { ctx.data.session.remember({ ...(ctx.data.session.get(session.id) ?? session), title: next }) // Rename advances time.updated server-side; re-sync the canonical @@ -190,6 +357,7 @@ export function createHomeSessionsController(home: HomeController) { return true }) .catch((cause) => { + if (signal?.aborted) return false showToast({ title: language.t("common.requestFailed"), description: errorMessage(cause, language.t("common.requestFailed")), @@ -199,78 +367,94 @@ export function createHomeSessionsController(home: HomeController) { }) } - const exportSession = async (server: ServerConnection.Key, session: SessionInfo) => { + const exporter = createSessionExporter() + + const serverContext = (server: ServerConnection.Key) => { const conn = home.server.list().find((item) => ServerConnection.key(item) === server) const ctx = conn ? home.server.context(conn) : undefined - if (!ctx) return + return conn && ctx ? { conn, ctx } : undefined + } - try { - const data = await fetchSessionExport({ sessionID: session.id, api: ctx.sdk.api }) - const filename = sessionExportFilename(data.info) + function DeleteDialog(props: { server: ServerConnection.Key; session: SessionInfo }) { + const name = () => sessionTitle(props.session.title) ?? language.t("command.session.new") + const [deleteState, setDeleteState] = createSignal(createSessionDeleteState(props.session.id)) + let timer: ReturnType | undefined - if (!(await saveSessionExport(filename, data, platform))) return - showToast({ - variant: "success", - icon: "circle-check", - title: language.t("toast.session.export.success.title"), - description: language.t("toast.session.export.success.description", { filename }), - }) - } catch (cause) { - showToast({ - variant: "error", - title: language.t("toast.session.export.failed.title"), - description: cause instanceof Error ? cause.message : language.t("toast.session.export.failed.description"), - }) + const dispatch = (event: SessionDeleteEvent) => { + const next = transitionSessionDelete(untrack(deleteState), event) + + if (next.state !== untrack(deleteState)) setDeleteState(next.state) + next.effects.forEach(run) } - } - const remove = async (server: ServerConnection.Key, session: SessionInfo) => { - const conn = home.server.list().find((item) => ServerConnection.key(item) === server) - const ctx = conn ? home.server.context(conn) : undefined + // Read when the user confirms, before the delete hides the session and its children from the list. + const deleteTarget = () => { + const ctx = serverContext(props.server)?.ctx - if (!conn || !ctx) return false - const ids = sessionTreeIDs(ctx.data.session.list(), session.id) - const rows = homeRowTops() - // session.deleted clears the local hide mutation before the refetch lands, - // so the cached index must drop the row now or it briefly reappears. - queryClient.setQueryData(["home-sessions", conn], (current) => - current?.filter((item) => item.id !== session.id), - ) - const request = ctx.data.session.remove(session.id) - animateHomeRowsUp(rows) + return ctx ? { removedIDs: sessionTreeIDs(ctx.data.session.list(), props.session.id) } : undefined + } - return request - .then(() => { + function run(effect: SessionDeleteEffect) { + if (effect.type === "delete.run") { + const target = serverContext(props.server) + + if (!target) return dispatch({ type: "delete.failed", attempt: effect.attempt, cause: undefined }) + const rows = homeRowTops() + // The data layer hides the session at once, keeps it hidden after session.deleted, and shows it again if the + // request fails, so the cached index drops it only once the server has. + const request = Promise.try(() => target.ctx.data.session.remove(effect.sessionID)) + animateHomeRowsUp(rows) + void request + .finally(() => void queryClient.invalidateQueries({ queryKey: ["home-sessions", target.conn], exact: true })) + .then( + () => dispatch({ type: "delete.succeeded", attempt: effect.attempt, target: effect.target }), + (cause: unknown) => dispatch({ type: "delete.failed", attempt: effect.attempt, cause }), + ) + + return + } + + if (effect.type === "dialog.close") return dialog.close() + + if (effect.type === "session.removed") { + const conn = serverContext(props.server)?.conn + + if (conn) + queryClient.setQueryData(["home-sessions", conn], (current) => + current?.filter((item) => !effect.target.removedIDs.includes(item.id)), + ) notifySessionTabsRemoved({ - server: ServerConnection.key(conn), - directory: session.location.directory, - sessionIDs: ids, + server: props.server, + directory: props.session.location.directory, + sessionIDs: [...effect.target.removedIDs], }) - return true - }) - .catch((cause) => { - showToast({ + return + } + + if (effect.type === "toast.delete-failed") + return showToast({ title: language.t("session.delete.failed.title"), - description: errorMessage(cause, language.t("session.delete.failed.title")), + description: + effect.cause === undefined + ? undefined + : errorMessage(effect.cause, language.t("session.delete.failed.title")), }) - return false - }) - .finally(() => { - void queryClient.invalidateQueries({ queryKey: ["home-sessions", conn], exact: true }) - }) - } + clearTimeout(timer) + timer = undefined - function DeleteDialog(props: { server: ServerConnection.Key; session: SessionInfo }) { - const name = () => sessionTitle(props.session.title) ?? language.t("command.session.new") - - const confirm = async () => { - dialog.close() - await remove(props.server, props.session) + if (effect.type === "timer.cancel") return + timer = setTimeout( + () => dispatch({ type: "delete.timed-out", attempt: effect.attempt }), + SESSION_DELETE_TIMEOUT_MS, + ) } + onCleanup(() => dispatch({ type: "disposed" })) + const busy = () => selectSessionDeleteView(deleteState()).busy + return ( @@ -280,10 +464,14 @@ export function createHomeSessionsController(home: HomeController) { /> - - @@ -298,7 +486,9 @@ export function createHomeSessionsController(home: HomeController) { data: { records, groups, - loading: () => sessionLoad.isPending, + listView: createMemo(() => selectHomeSessionsListView(load(), groups().length > 0)), + loading: () => selectHomeSessionsSearchLoading(load()), + retry: () => dispatchLoad({ type: "retry" }), searchRecords: allRecords, }, platform: { @@ -312,11 +502,11 @@ export function createHomeSessionsController(home: HomeController) { showProjectName: () => !home.project.selected(), server: () => home.selection.value().server, canCreate: () => !!home.project.newSession(), - lookup: async (sessionID: string) => { + lookup: async (sessionID: string, signal?: AbortSignal) => { const ctx = home.server.focusedContext() if (!ctx) return - const result = await ctx.sdk.api.session.get({ sessionID }) + const result = await ctx.sdk.api.session.get({ sessionID }, { signal }) if (result.time.archived) return @@ -370,7 +560,10 @@ export function createHomeSessionsController(home: HomeController) { }) }, rename, - export: exportSession, + export: (server: ServerConnection.Key, session: SessionInfo) => + exporter.export({ server, sessionID: session.id }), + exporting: (server: ServerConnection.Key, session: SessionInfo) => + exporter.exporting({ server, sessionID: session.id }), showDelete: (server: ServerConnection.Key, session: SessionInfo) => dialog.show(() => ), }, @@ -405,6 +598,7 @@ function animateHomeRowsUp(tops: Map) { document.querySelectorAll(HOME_ROW_SELECTOR).forEach((row) => { const before = tops.get(row.dataset.sessionId) const delta = before === undefined ? 0 : before - row.getBoundingClientRect().top + if (delta === 0) return row.animate([{ transform: `translateY(${delta}px)` }, { transform: "translateY(0)" }], { duration: 180, @@ -426,8 +620,10 @@ function groupSessions(records: HomeSessionRecord[], language: ReturnType localDay(new Date(record.session.time.updated ?? record.session.time.created)) + const todaySessions = records.filter((record) => day(record) === today) const yesterdaySessions = records.filter((record) => day(record) === yesterday) const olderSessions = records.filter((record) => day(record) !== today && day(record) !== yesterday) diff --git a/packages/app/src/home/sessions/load-machine.test.ts b/packages/app/src/home/sessions/load-machine.test.ts new file mode 100644 index 000000000000..997058c02ba5 --- /dev/null +++ b/packages/app/src/home/sessions/load-machine.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, test } from "bun:test" +import type { ServerConnection } from "@/runtime/server/registry" +import { + HOME_SESSIONS_CONNECT_TIMEOUT_MS, + HOME_SESSIONS_FETCH_TIMEOUT_MS, + INITIAL_HOME_SESSIONS_LOAD_STATE, + selectHomeSessionsListView, + selectHomeSessionsSearchLoading, + transitionHomeSessionsLoad, + type HomeSessionsLoadEffect, + type HomeSessionsLoadEvent, + type HomeSessionsLoadState, + type HomeSessionsTarget, +} from "./load-machine" + +// SAFETY: the brand only marks registry-built keys; these tests compare them as plain strings. +const A = "http:a" as ServerConnection.Key + +// SAFETY: as above. +const B = "http:b" as ServerConnection.Key + +const target = ( + connection: HomeSessionsTarget["connection"], + options: { server?: ServerConnection.Key; cached?: boolean; stale?: boolean } = {}, +): HomeSessionsLoadEvent => ({ + type: "context.changed", + target: { + server: options.server ?? A, + connection, + cached: options.cached ?? false, + stale: options.stale ?? !options.cached, + }, +}) + +function replay(events: HomeSessionsLoadEvent[], state = INITIAL_HOME_SESSIONS_LOAD_STATE) { + return events.reduce<{ state: HomeSessionsLoadState; effects: readonly HomeSessionsLoadEffect[] }>( + (step, event) => transitionHomeSessionsLoad(step.state, event), + { state, effects: [] }, + ) +} + +const view = (state: HomeSessionsLoadState, hasSessions = false) => selectHomeSessionsListView(state, hasSessions) + +describe("home sessions load machine", () => { + test("a server that cannot answer never shows placeholder rows or the search spinner", () => { + for (const reason of ["offline", "auth", "incompatible"] as const) { + const step = replay([target(reason), { type: "placeholder.due", since: 1 }]) + + expect(view(step.state)).toEqual({ status: "unavailable", reason }) + expect(selectHomeSessionsSearchLoading(step.state)).toBe(false) + expect(step.effects.some((effect) => effect.type === "fetch.start")).toBe(false) + } + + // Sessions the server's live store already holds still show. + expect(view(replay([target("offline")]).state, true)).toEqual({ status: "ready", revealing: false }) + }) + + test("a connect that never finishes ends as unreachable instead of loading forever", () => { + const connecting = replay([target("connecting")]) + expect(connecting.effects).toContainEqual({ + type: "timer.start", + timer: "deadline", + delayMs: HOME_SESSIONS_CONNECT_TIMEOUT_MS, + event: { type: "connect.timed-out", attempt: 1 }, + }) + expect(view(replay([{ type: "placeholder.due", since: 1 }], connecting.state).state)).toEqual({ + status: "loading", + skeleton: true, + }) + + const timedOut = replay([{ type: "connect.timed-out", attempt: 1 }], connecting.state) + expect(view(timedOut.state)).toEqual({ status: "unavailable", reason: "offline" }) + expect(selectHomeSessionsSearchLoading(timedOut.state)).toBe(false) + + // Try again probes the servers and waits for a connection again. + const retried = replay([{ type: "retry" }], timedOut.state) + expect(retried.state).toMatchObject({ status: "connecting", attempt: 2 }) + expect(retried.effects).toContainEqual({ type: "probe.servers" }) + }) + + test("a failed first load shows an error with Try again, not the empty state", () => { + const loading = replay([target("connected")]) + expect(loading.effects).toContainEqual({ type: "fetch.start", server: A, attempt: 1 }) + + const failed = replay([{ type: "fetch.failed", attempt: 1, message: "500" }], loading.state) + expect(view(failed.state)).toEqual({ status: "error", failure: { type: "rejected", message: "500" } }) + expect(selectHomeSessionsSearchLoading(failed.state)).toBe(false) + + // The server reporting itself connected again does not retry behind the user's back. + expect(transitionHomeSessionsLoad(failed.state, target("connected")).state).toBe(failed.state) + + const retried = replay([{ type: "retry" }], failed.state) + expect(retried.state).toMatchObject({ status: "loading", attempt: 2, skeleton: false }) + expect(retried.effects).toContainEqual({ type: "fetch.start", server: A, attempt: 2 }) + expect(view(replay([{ type: "fetch.succeeded", attempt: 2, reducedMotion: false }], retried.state).state)).toEqual({ + status: "ready", + revealing: false, + }) + }) + + test("a hung first load times out, cancels the request and shows the error", () => { + const loading = replay([target("connected")]) + expect(loading.effects).toContainEqual({ + type: "timer.start", + timer: "deadline", + delayMs: HOME_SESSIONS_FETCH_TIMEOUT_MS, + event: { type: "fetch.timed-out", attempt: 1 }, + }) + + const timedOut = replay([{ type: "fetch.timed-out", attempt: 1 }], loading.state) + expect(view(timedOut.state)).toEqual({ status: "error", failure: { type: "timeout" } }) + expect(timedOut.effects).toContainEqual({ type: "fetch.cancel", server: A }) + + // The cancelled request's rejection lands on an attempt the machine already left. + expect(transitionHomeSessionsLoad(timedOut.state, { type: "fetch.failed", attempt: 1, message: "x" }).state).toBe( + timedOut.state, + ) + }) + + test("placeholder rows appear only after the delay, fade out over the list, and never over an error", () => { + const fast = replay([target("connected"), { type: "fetch.succeeded", attempt: 1, reducedMotion: false }]) + expect(view(fast.state)).toEqual({ status: "ready", revealing: false }) + expect(fast.effects).toContainEqual({ type: "timer.stop", timer: "placeholder" }) + + const slow = replay([target("connected"), { type: "placeholder.due", since: 1 }]) + const revealed = replay([{ type: "fetch.succeeded", attempt: 1, reducedMotion: false }], slow.state) + expect(view(revealed.state)).toEqual({ status: "ready", revealing: true }) + expect(view(replay([{ type: "reveal.completed", attempt: 1 }], revealed.state).state)).toEqual({ + status: "ready", + revealing: false, + }) + expect(view(replay([{ type: "fetch.succeeded", attempt: 1, reducedMotion: true }], slow.state).state)).toEqual({ + status: "ready", + revealing: false, + }) + + expect(view(replay([{ type: "fetch.failed", attempt: 1, message: "x" }], slow.state).state).status).toBe("error") + + // Switching to a server with a cached list shows it at once, without fading placeholder rows over it. + const switched = replay([target("connected", { server: B, cached: true, stale: false })], slow.state) + expect(view(switched.state)).toEqual({ status: "ready", revealing: false }) + expect(switched.effects).toContainEqual({ type: "timer.stop", timer: "deadline" }) + }) + + test("placeholder rows shown while connecting stay up through the first fetch", () => { + const step = replay([target("connecting"), { type: "placeholder.due", since: 1 }, target("connected")]) + + expect(step.state).toMatchObject({ status: "loading", attempt: 2, since: 1, skeleton: true }) + expect(step.effects).toContainEqual({ type: "fetch.start", server: A, attempt: 2 }) + expect(step.effects.some((effect) => effect.type === "timer.start" && effect.timer === "placeholder")).toBe(false) + }) + + test("a fresh cached list shows without a fetch; a stale one shows while it refreshes", () => { + const fresh = replay([target("connected", { cached: true, stale: false })]) + expect(fresh.state).toMatchObject({ status: "ready" }) + expect(fresh.effects).toEqual([]) + + const stale = replay([target("connected", { cached: true, stale: true })]) + expect(stale.state).toMatchObject({ status: "refreshing", attempt: 1 }) + expect(view(stale.state)).toEqual({ status: "ready", revealing: false }) + + // A failed refresh keeps the list. + expect(replay([{ type: "fetch.failed", attempt: 1, message: "x" }], stale.state).state).toMatchObject({ + status: "ready", + }) + }) + + test("a server that goes away keeps its list and stops waiting for the refresh", () => { + const refreshing = replay([target("connected", { cached: true, stale: true })]) + const offline = replay([target("offline", { cached: true })], refreshing.state) + + expect(offline.state).toMatchObject({ status: "ready" }) + expect(offline.effects).toEqual([{ type: "timer.stop", timer: "deadline" }]) + expect(transitionHomeSessionsLoad(offline.state, target("offline", { cached: true })).state).toBe(offline.state) + }) + + test("an invalidation refreshes the list, and one during a fetch runs one more fetch", () => { + const ready = replay([target("connected"), { type: "fetch.succeeded", attempt: 1, reducedMotion: false }]) + const refreshing = replay([{ type: "refresh", server: A }], ready.state) + expect(refreshing.effects).toContainEqual({ type: "fetch.start", server: A, attempt: 2 }) + + const queued = replay([{ type: "refresh", server: A }], refreshing.state) + expect(queued.state).toMatchObject({ status: "refreshing", attempt: 2, queued: true }) + expect(queued.effects).toEqual([]) + + const again = replay([{ type: "fetch.succeeded", attempt: 2, reducedMotion: false }], queued.state) + expect(again.state).toMatchObject({ status: "refreshing", attempt: 3, queued: false }) + expect(again.effects).toContainEqual({ type: "fetch.start", server: A, attempt: 3 }) + + // Another server's invalidation changes nothing. + expect(transitionHomeSessionsLoad(ready.state, { type: "refresh", server: B }).state).toBe(ready.state) + }) + + test("a result for a server the user left is ignored", () => { + const step = replay([target("connected"), target("connected", { server: B })]) + expect(step.state).toMatchObject({ status: "loading", server: B, attempt: 2 }) + + expect( + transitionHomeSessionsLoad(step.state, { type: "fetch.succeeded", attempt: 1, reducedMotion: false }).state, + ).toBe(step.state) + expect(transitionHomeSessionsLoad(step.state, { type: "fetch.failed", attempt: 1, message: "x" }).state).toBe( + step.state, + ) + }) + + test("disposing stops every timer and ignores what arrives later", () => { + const loading = replay([target("connected")]) + const disposed = replay([{ type: "disposed" }], loading.state) + + expect(disposed.effects).toEqual([ + { type: "timer.stop", timer: "placeholder" }, + { type: "timer.stop", timer: "deadline" }, + ]) + + for (const event of [ + { type: "fetch.succeeded", attempt: 1, reducedMotion: false }, + target("connected", { server: B }), + { type: "retry" }, + ] satisfies HomeSessionsLoadEvent[]) { + expect(transitionHomeSessionsLoad(disposed.state, event).state).toBe(disposed.state) + } + }) +}) diff --git a/packages/app/src/home/sessions/load-machine.ts b/packages/app/src/home/sessions/load-machine.ts new file mode 100644 index 000000000000..4e5e08c25dc6 --- /dev/null +++ b/packages/app/src/home/sessions/load-machine.ts @@ -0,0 +1,430 @@ +import type { ServerConnection } from "@/runtime/server/registry" + +/** Matches `staleTime` in `queries.ts`: a cached list younger than this shows without a refetch. */ +export const HOME_SESSIONS_STALE_MS = 30_000 + +export const HOME_SESSIONS_FETCH_TIMEOUT_MS = 30_000 + +export const HOME_SESSIONS_CONNECT_TIMEOUT_MS = 15_000 + +export const HOME_SESSIONS_PLACEHOLDER_DELAY_MS = 250 + +// Matches the list's reveal animation in view.css. +export const HOME_SESSIONS_REVEAL_MS = 200 + +export type HomeSessionsUnavailableReason = "offline" | "auth" | "incompatible" + +/** + * The focused server as the list sees it. `cached` says the shared `["home-sessions", conn]` cache holds a list, which + * the list shows whatever the phase; `stale` says that list is missing, invalidated or older than the stale time. + */ +export type HomeSessionsTarget = { + readonly server: ServerConnection.Key + readonly connection: "connected" | "connecting" | HomeSessionsUnavailableReason + readonly cached: boolean + readonly stale: boolean +} + +export type HomeSessionsFailure = { readonly type: "rejected"; readonly message: string } | { readonly type: "timeout" } + +/** + * The focused server's session index. The list itself lives in the shared query cache; this machine owns only the + * phase. `connecting` and `loading` show placeholder rows once `since`'s delay passes (`skeleton`), and carry it across + * the connect so the rows never restart. `reveal` is non-zero while the list fades in over the placeholder rows, and + * names the fetch that revealed it. `queued` records a refresh asked for while a fetch was in flight: one more fetch + * runs when it settles. + */ +export type HomeSessionsLoadState = + | { readonly status: "idle"; readonly issued: number } + | { + readonly status: "connecting" + readonly issued: number + readonly server: ServerConnection.Key + readonly attempt: number + readonly since: number + readonly skeleton: boolean + } + | { + readonly status: "loading" + readonly issued: number + readonly server: ServerConnection.Key + readonly attempt: number + readonly since: number + readonly skeleton: boolean + readonly queued: boolean + } + | { + readonly status: "ready" + readonly issued: number + readonly server: ServerConnection.Key + readonly reveal: number + } + | { + readonly status: "refreshing" + readonly issued: number + readonly server: ServerConnection.Key + readonly attempt: number + readonly reveal: number + readonly queued: boolean + } + | { + readonly status: "unavailable" + readonly issued: number + readonly server: ServerConnection.Key + readonly reason: HomeSessionsUnavailableReason + } + | { + readonly status: "error" + readonly issued: number + readonly server: ServerConnection.Key + readonly failure: HomeSessionsFailure + } + | { readonly status: "disposed" } + +export type HomeSessionsTimer = "placeholder" | "deadline" | "reveal" + +export type HomeSessionsTimerEvent = + | { readonly type: "placeholder.due"; readonly since: number } + | { readonly type: "connect.timed-out"; readonly attempt: number } + | { readonly type: "fetch.timed-out"; readonly attempt: number } + | { readonly type: "reveal.completed"; readonly attempt: number } + +export type HomeSessionsLoadEvent = + | HomeSessionsTimerEvent + | { readonly type: "context.changed"; readonly target: HomeSessionsTarget | undefined } + | { readonly type: "fetch.succeeded"; readonly attempt: number; readonly reducedMotion: boolean } + | { readonly type: "fetch.failed"; readonly attempt: number; readonly message: string } + /** The cached list was invalidated, or the browser came back online while it was stale. */ + | { readonly type: "refresh"; readonly server: ServerConnection.Key } + | { readonly type: "retry" } + | { readonly type: "disposed" } + +export type HomeSessionsLoadEffect = + | { readonly type: "fetch.start"; readonly server: ServerConnection.Key; readonly attempt: number } + | { readonly type: "fetch.cancel"; readonly server: ServerConnection.Key } + | { readonly type: "probe.servers" } + | { + readonly type: "timer.start" + readonly timer: HomeSessionsTimer + readonly delayMs: number + readonly event: HomeSessionsTimerEvent + } + | { readonly type: "timer.stop"; readonly timer: HomeSessionsTimer } + +export type HomeSessionsLoadTransition = { + readonly state: HomeSessionsLoadState + readonly effects: readonly HomeSessionsLoadEffect[] +} + +export type HomeSessionsListView = + | { readonly status: "loading"; readonly skeleton: boolean } + | { readonly status: "ready"; readonly revealing: boolean } + | { readonly status: "unavailable"; readonly reason: HomeSessionsUnavailableReason } + | { readonly status: "error"; readonly failure: HomeSessionsFailure } + +type LiveState = Exclude + +export const INITIAL_HOME_SESSIONS_LOAD_STATE: HomeSessionsLoadState = Object.freeze({ status: "idle", issued: 0 }) + +const DISPOSED: HomeSessionsLoadState = Object.freeze({ status: "disposed" }) + +const NONE: readonly HomeSessionsLoadEffect[] = Object.freeze([]) + +const PROBE: HomeSessionsLoadEffect = Object.freeze({ type: "probe.servers" }) + +export function transitionHomeSessionsLoad( + state: HomeSessionsLoadState, + event: HomeSessionsLoadEvent, +): HomeSessionsLoadTransition { + if (state.status === "disposed") return unchanged(state) + + if (event.type === "disposed") return { state: DISPOSED, effects: stop(state) } + + if (event.type === "context.changed") return retarget(state, event.target) + + if (event.type === "placeholder.due") { + if (state.status !== "connecting" && state.status !== "loading") return unchanged(state) + + if (state.skeleton || state.since !== event.since) return unchanged(state) + + return { state: { ...state, skeleton: true }, effects: NONE } + } + + if (event.type === "connect.timed-out") { + if (state.status !== "connecting" || state.attempt !== event.attempt) return unchanged(state) + + return { + state: { status: "unavailable", issued: state.issued, server: state.server, reason: "offline" }, + effects: stop(state), + } + } + + if (event.type === "fetch.succeeded") return succeeded(state, event) + + if (event.type === "fetch.failed" || event.type === "fetch.timed-out") return failed(state, event) + + if (event.type === "reveal.completed") { + if (state.status !== "ready" && state.status !== "refreshing") return unchanged(state) + + if (state.reveal === 0 || state.reveal !== event.attempt) return unchanged(state) + + return { state: { ...state, reveal: 0 }, effects: NONE } + } + + if (event.type === "refresh") return refresh(state, event.server) + + if (state.status === "error") return load(state, state.server) + + if (state.status === "unavailable" && state.reason === "offline") return connect(state, state.server, [PROBE]) + + return unchanged(state) +} + +/** Placeholder rows and the search spinner show only while a connect or first fetch is in flight, both bounded. */ +export function selectHomeSessionsSearchLoading(state: HomeSessionsLoadState) { + return state.status === "connecting" || state.status === "loading" +} + +/** What the list area shows. `hasSessions`: the cached index or the server's live store holds sessions to list. */ +export function selectHomeSessionsListView(state: HomeSessionsLoadState, hasSessions: boolean): HomeSessionsListView { + if (state.status === "connecting" || state.status === "loading") + return { status: "loading", skeleton: state.skeleton } + + if (state.status === "ready" || state.status === "refreshing") + return { status: "ready", revealing: state.reveal !== 0 } + + if (state.status === "error") return { status: "error", failure: state.failure } + + if (state.status === "unavailable" && !hasSessions) return { status: "unavailable", reason: state.reason } + + return { status: "ready", revealing: false } +} + +function retarget(state: LiveState, target: HomeSessionsTarget | undefined): HomeSessionsLoadTransition { + if (!target) { + if (state.status === "idle") return unchanged(state) + + return { state: { status: "idle", issued: state.issued }, effects: stop(state) } + } + + if (state.status === "idle" || state.server !== target.server) return enter(state, target) + + if (target.connection === "connected") { + if (state.status === "connecting") return fetch(state, state.since, state.skeleton) + + if (state.status === "ready") { + // The cache lost the list it showed (another connection object for the server): load it again. + if (!target.cached) return enter(state, target) + + return target.stale ? refetch(state, state.reveal) : unchanged(state) + } + + // A fetch in flight keeps running; a failed one waits for the user's retry. + if (state.status !== "unavailable") return unchanged(state) + + return enter(state, target) + } + + if (target.connection === "connecting") + return state.status === "unavailable" ? enter(state, target) : unchanged(state) + + // A list already shown stays shown while the server is away. + if (state.status === "ready") return unchanged(state) + + if (state.status === "refreshing") { + return { + state: { status: "ready", issued: state.issued, server: state.server, reveal: state.reveal }, + effects: [stopTimer("deadline")], + } + } + + if (state.status === "unavailable" && state.reason === target.connection) return unchanged(state) + + return enter(state, target) +} + +// A new target starts over: a list cached for it shows at once, and only a connected server is asked for one. +function enter(state: LiveState, target: HomeSessionsTarget): HomeSessionsLoadTransition { + const effects = stop(state) + + if (target.cached && (target.connection !== "connected" || !target.stale)) + return { state: { status: "ready", issued: state.issued, server: target.server, reveal: 0 }, effects } + + if (target.cached) return refetch({ issued: state.issued, server: target.server }, 0, effects) + + if (target.connection === "connected") return load(state, target.server, effects) + + if (target.connection === "connecting") return connect(state, target.server, effects) + + return { + state: { status: "unavailable", issued: state.issued, server: target.server, reason: target.connection }, + effects, + } +} + +function refresh(state: LiveState, server: ServerConnection.Key): HomeSessionsLoadTransition { + if (state.status === "idle" || state.server !== server) return unchanged(state) + + if (state.status === "ready") return refetch(state, state.reveal) + + if (state.status === "loading" || state.status === "refreshing") { + return state.queued ? unchanged(state) : { state: { ...state, queued: true }, effects: NONE } + } + + if (state.status === "error") return load(state, server) + + return unchanged(state) +} + +function succeeded( + state: LiveState, + event: Extract, +): HomeSessionsLoadTransition { + if (state.status === "loading" && state.attempt === event.attempt) { + const reveal = state.skeleton && !event.reducedMotion ? state.attempt : 0 + + const effects = [ + ...placeholderStop(state), + ...(reveal ? [startTimer("reveal", HOME_SESSIONS_REVEAL_MS, { type: "reveal.completed", attempt: reveal })] : []), + ] + + if (state.queued) return refetch(state, reveal, effects) + + return { + state: { status: "ready", issued: state.issued, server: state.server, reveal }, + effects: [...effects, stopTimer("deadline")], + } + } + + if (state.status !== "refreshing" || state.attempt !== event.attempt) return unchanged(state) + + if (state.queued) return refetch(state, state.reveal) + + return { + state: { status: "ready", issued: state.issued, server: state.server, reveal: state.reveal }, + effects: [stopTimer("deadline")], + } +} + +function failed( + state: LiveState, + event: Extract, +): HomeSessionsLoadTransition { + if ((state.status !== "loading" && state.status !== "refreshing") || state.attempt !== event.attempt) + return unchanged(state) + + // A request that timed out may still hold the shared query; cancelling it lets the next fetch start fresh. + const settle: HomeSessionsLoadEffect[] = [ + stopTimer("deadline"), + ...(event.type === "fetch.timed-out" ? [{ type: "fetch.cancel" as const, server: state.server }] : []), + ] + + // A failed refresh keeps the list it shows. + if (state.status === "refreshing") + return { + state: { status: "ready", issued: state.issued, server: state.server, reveal: state.reveal }, + effects: settle, + } + + const failure: HomeSessionsFailure = + event.type === "fetch.failed" ? { type: "rejected", message: event.message } : { type: "timeout" } + + return { + state: { status: "error", issued: state.issued, server: state.server, failure }, + effects: [...placeholderStop(state), ...settle], + } +} + +function load( + state: { readonly issued: number }, + server: ServerConnection.Key, + effects: readonly HomeSessionsLoadEffect[] = NONE, +): HomeSessionsLoadTransition { + const attempt = state.issued + 1 + + return fetch({ issued: state.issued, server }, attempt, false, [...effects, placeholder(attempt)]) +} + +// Keeps `since` and `skeleton`, so placeholder rows shown while connecting stay up through the first fetch. +function fetch( + state: { readonly issued: number; readonly server: ServerConnection.Key }, + since: number, + skeleton: boolean, + effects: readonly HomeSessionsLoadEffect[] = NONE, +): HomeSessionsLoadTransition { + const attempt = state.issued + 1 + + return { + state: { status: "loading", issued: attempt, server: state.server, attempt, since, skeleton, queued: false }, + effects: [...effects, ...request(state.server, attempt)], + } +} + +function refetch( + state: { readonly issued: number; readonly server: ServerConnection.Key }, + reveal: number, + effects: readonly HomeSessionsLoadEffect[] = NONE, +): HomeSessionsLoadTransition { + const attempt = state.issued + 1 + + return { + state: { status: "refreshing", issued: attempt, server: state.server, attempt, reveal, queued: false }, + effects: [...effects, ...request(state.server, attempt)], + } +} + +function connect( + state: { readonly issued: number }, + server: ServerConnection.Key, + effects: readonly HomeSessionsLoadEffect[] = NONE, +): HomeSessionsLoadTransition { + const attempt = state.issued + 1 + + return { + state: { status: "connecting", issued: attempt, server, attempt, since: attempt, skeleton: false }, + effects: [ + ...effects, + placeholder(attempt), + startTimer("deadline", HOME_SESSIONS_CONNECT_TIMEOUT_MS, { type: "connect.timed-out", attempt }), + ], + } +} + +function request(server: ServerConnection.Key, attempt: number): HomeSessionsLoadEffect[] { + return [ + { type: "fetch.start", server, attempt }, + startTimer("deadline", HOME_SESSIONS_FETCH_TIMEOUT_MS, { type: "fetch.timed-out", attempt }), + ] +} + +function placeholder(since: number) { + return startTimer("placeholder", HOME_SESSIONS_PLACEHOLDER_DELAY_MS, { type: "placeholder.due", since }) +} + +// A superseded fetch keeps running and fills the shared cache; only its result is ignored here. +function stop(state: LiveState): HomeSessionsLoadEffect[] { + if (state.status === "connecting" || state.status === "loading") + return [...placeholderStop(state), stopTimer("deadline")] + + if (state.status === "refreshing") return [stopTimer("deadline"), ...(state.reveal ? [stopTimer("reveal")] : [])] + + if (state.status === "ready" && state.reveal) return [stopTimer("reveal")] + + return [] +} + +function placeholderStop(state: { readonly skeleton: boolean }): HomeSessionsLoadEffect[] { + return state.skeleton ? [] : [stopTimer("placeholder")] +} + +function startTimer(timer: HomeSessionsTimer, delayMs: number, event: HomeSessionsTimerEvent): HomeSessionsLoadEffect { + return { type: "timer.start", timer, delayMs, event } +} + +function stopTimer(timer: HomeSessionsTimer): HomeSessionsLoadEffect { + return { type: "timer.stop", timer } +} + +function unchanged(state: HomeSessionsLoadState): HomeSessionsLoadTransition { + return { state, effects: NONE } +} diff --git a/packages/app/src/home/sessions/region.tsx b/packages/app/src/home/sessions/region.tsx index 979fb7fdf96d..be3b7b7cb4eb 100644 --- a/packages/app/src/home/sessions/region.tsx +++ b/packages/app/src/home/sessions/region.tsx @@ -15,7 +15,8 @@ export function HomeSessions(props: { ({ + type: "touch.down", + sessionID, + x: 100, + y: 20, + menuX: 40, + menuY: 12, +}) + +const submit: HomeSessionRowEvent = { + type: "editor.submit", + sessionID: "ses_a", + server: SERVER, + session: SESSION, + title: "Old", +} + +const rename: HomeSessionRowEvent[] = [ + { type: "rename.start", sessionID: "ses_a", title: "Old" }, + { type: "editor.input", sessionID: "ses_a", draft: "New" }, + submit, +] + +function replay(events: HomeSessionRowEvent[], state = INITIAL_HOME_SESSION_ROW_STATE) { + return events.reduce<{ state: HomeSessionRowState; effects: readonly HomeSessionRowEffect[] }>( + (step, event) => transitionHomeSessionRow(step.state, event), + { state, effects: [] }, + ) +} + +describe("home session row machine", () => { + test("Escape cancels a save that hangs, and its late answer changes nothing", () => { + const renaming = replay(rename) + expect(renaming.state).toMatchObject({ status: "renaming", attempt: 1, draft: "New" }) + expect(renaming.effects).toEqual([ + { + type: "rename.save", + attempt: 1, + server: SERVER, + session: SESSION, + title: "New", + timeoutMs: HOME_SESSION_RENAME_TIMEOUT_MS, + }, + ]) + expect(selectRowEditor(renaming.state, "ses_a")?.status).toBe("renaming") + + const cancelled = replay([{ type: "editor.cancel", sessionID: "ses_a", reason: "escape" }], renaming.state) + expect(cancelled.state).toMatchObject({ status: "idle" }) + expect(cancelled.effects).toEqual([ + { type: "rename.abort", attempt: 1 }, + { type: "focus.row", sessionID: "ses_a", ifOwned: false }, + ]) + + for (const type of ["rename.succeeded", "rename.failed", "rename.timed-out"] as const) { + expect(transitionHomeSessionRow(cancelled.state, { type, attempt: 1 }).state).toBe(cancelled.state) + } + }) + + test("a failed or timed-out save returns to editing with the draft; clicking away lets it finish", () => { + const renaming = replay(rename) + expect( + transitionHomeSessionRow(renaming.state, { type: "editor.cancel", sessionID: "ses_a", reason: "blur" }).state, + ).toBe(renaming.state) + + const timedOut = replay([{ type: "rename.timed-out", attempt: 1 }], renaming.state) + expect(timedOut.state).toMatchObject({ status: "editing", draft: "New" }) + expect(timedOut.effects).toEqual([ + { type: "rename.abort", attempt: 1 }, + { type: "toast.rename-timeout" }, + { type: "focus.editor", sessionID: "ses_a", select: false, ifOwned: true }, + ]) + + expect(replay([{ type: "rename.failed", attempt: 1 }], renaming.state).state).toMatchObject({ + status: "editing", + draft: "New", + }) + + const saved = replay([{ type: "rename.succeeded", attempt: 1 }], renaming.state) + expect(saved.state).toMatchObject({ status: "idle" }) + expect(saved.effects).toEqual([{ type: "focus.row", sessionID: "ses_a", ifOwned: true }]) + + // An unchanged title saves nothing. + const unchanged = replay([{ type: "rename.start", sessionID: "ses_a", title: "Old" }, submit]) + expect(unchanged.state.status).toBe("idle") + expect(unchanged.effects).toEqual([{ type: "focus.row", sessionID: "ses_a", ifOwned: false }]) + }) + + test("a long press opens the menu and swallows its release click once, whichever row instance gets it", () => { + const pressing = replay([press()]) + expect(pressing.effects).toEqual([{ type: "long-press.start", attempt: 1, delayMs: 500 }]) + + // Moves inside the slop are filtered before any event is built. + expect(selectLongPressMoved(pressing.state, 106, 26)).toBe(false) + expect(transitionHomeSessionRow(pressing.state, { type: "touch.move", x: 106, y: 26 }).state).toBe(pressing.state) + const scrolled = replay([{ type: "touch.move", x: 100, y: 40 }], pressing.state) + expect(scrolled.state.status).toBe("idle") + expect(scrolled.effects).toEqual([{ type: "long-press.stop" }]) + + const opened = replay([{ type: "long-press.fired", attempt: 1 }], pressing.state) + expect(selectRowMenu(opened.state, "ses_a")).toMatchObject({ x: 40, y: 12 }) + expect(selectRowSuppressClick(opened.state, "ses_a", 1)).toBe(true) + expect(selectRowSuppressClick(opened.state, "ses_a", 0)).toBe(false) + + const clicked = replay([{ type: "row.clicked", sessionID: "ses_a" }], opened.state) + expect(selectRowSuppressClick(clicked.state, "ses_a", 1)).toBe(false) + expect(selectRowMenu(clicked.state, "ses_a")).toBeDefined() + + // The menu can close before the release click arrives. + const closed = replay([{ type: "menu.closed", sessionID: "ses_a" }], opened.state) + expect(selectRowSuppressClick(closed.state, "ses_a", 1)).toBe(true) + const consumed = replay([{ type: "row.clicked", sessionID: "ses_a" }], closed.state) + expect(selectRowSuppressClick(consumed.state, "ses_a", 1)).toBe(false) + expect(selectRowSuppressClick(replay([{ type: "pointer.down" }], closed.state).state, "ses_a", 1)).toBe(false) + + // A stale long-press timer changes nothing. + expect(transitionHomeSessionRow(clicked.state, { type: "long-press.fired", attempt: 1 }).state).toBe(clicked.state) + }) + + test("Android's contextmenu during a long press still swallows the release click", () => { + const opened = replay([press(), { type: "menu.open", sessionID: "ses_a", x: 40, y: 12 }]) + + expect(opened.effects).toEqual([{ type: "long-press.stop" }]) + expect(selectRowSuppressClick(opened.state, "ses_a", 1)).toBe(true) + expect(transitionHomeSessionRow(opened.state, { type: "long-press.fired", attempt: 1 }).state).toBe(opened.state) + }) + + test("closing the menu restores focus to the row unless the user clicked elsewhere or chose Rename", () => { + const open = replay([{ type: "menu.open", sessionID: "ses_a", x: 12, y: 40 }]) + expect(selectRowSuppressClick(open.state, "ses_a", 1)).toBe(false) + expect(replay([{ type: "menu.closed", sessionID: "ses_a" }], open.state).effects).toEqual([ + { type: "focus.row", sessionID: "ses_a", ifOwned: false }, + ]) + + const outside = replay( + [ + { type: "menu.interact-outside", sessionID: "ses_a" }, + { type: "menu.closed", sessionID: "ses_a" }, + ], + open.state, + ) + + expect(outside.state.status).toBe("idle") + expect(outside.effects).toEqual([]) + + const renaming = replay( + [ + { type: "rename.start", sessionID: "ses_a", title: "Old" }, + { type: "menu.closed", sessionID: "ses_a" }, + ], + open.state, + ) + + expect(selectRowEditor(renaming.state, "ses_a")).toMatchObject({ status: "editing", draft: "Old" }) + expect(renaming.effects).toEqual([]) + + // The editor keeps the native menu. + expect(transitionHomeSessionRow(renaming.state, { type: "menu.open", sessionID: "ses_a", x: 0, y: 0 }).state).toBe( + renaming.state, + ) + }) + + test("a row that leaves the list ends its gesture; one that moves to another group keeps it", () => { + const pressing = replay([press()]) + expect( + transitionHomeSessionRow(pressing.state, { type: "sessions.synced", sessionIDs: new Set(["ses_a"]) }).state, + ).toBe(pressing.state) + + const gone = replay([{ type: "sessions.synced", sessionIDs: new Set(["ses_b"]) }], pressing.state) + expect(gone.state.status).toBe("idle") + expect(gone.effects).toEqual([{ type: "long-press.stop" }]) + }) + + test("disposing stops the long press and ignores what arrives later", () => { + const disposed = replay([press(), { type: "disposed" }]) + + expect(disposed.effects).toEqual([{ type: "long-press.stop" }]) + expect(transitionHomeSessionRow(disposed.state, { type: "long-press.fired", attempt: 1 }).state).toBe( + disposed.state, + ) + }) +}) diff --git a/packages/app/src/home/sessions/row-machine.ts b/packages/app/src/home/sessions/row-machine.ts new file mode 100644 index 000000000000..5c4de68842af --- /dev/null +++ b/packages/app/src/home/sessions/row-machine.ts @@ -0,0 +1,365 @@ +import type { SessionInfo } from "@opencode/client/promise" +import type { ServerConnection } from "@/runtime/server/registry" + +export const HOME_SESSION_LONG_PRESS_MS = 500 + +/** How far a touch may drift before it is a scroll rather than a long press. */ +export const HOME_SESSION_LONG_PRESS_SLOP_PX = 8 + +export const HOME_SESSION_RENAME_TIMEOUT_MS = 15_000 + +/** + * The Home session rows' context menu, touch long press and inline rename. One row at a time owns a gesture. It lives at + * the list root, so it survives a row remounting when its session moves to another date group. + * + * A long press opens the menu while the finger is still down, and the browser then sends a click for the release: + * `suppressClick` swallows it once. It moves to `idle` when the menu closes before that click arrives. `renaming` keeps + * the draft, so a failed or timed-out save returns to `editing` with it. + */ +export type HomeSessionRowState = + | { readonly status: "idle"; readonly issued: number; readonly suppressClick: string | undefined } + | { + readonly status: "pressing" + readonly issued: number + readonly attempt: number + readonly sessionID: string + readonly x: number + readonly y: number + readonly menuX: number + readonly menuY: number + } + | { + readonly status: "menu" + readonly issued: number + readonly sessionID: string + readonly x: number + readonly y: number + readonly suppressClick: boolean + readonly outside: boolean + } + | { readonly status: "editing"; readonly issued: number; readonly sessionID: string; readonly draft: string } + | { + readonly status: "renaming" + readonly issued: number + readonly attempt: number + readonly sessionID: string + readonly draft: string + } + | { readonly status: "disposed" } + +export type HomeSessionRowEvent = + | { + readonly type: "touch.down" + readonly sessionID: string + readonly x: number + readonly y: number + readonly menuX: number + readonly menuY: number + } + /** A mouse or pen press: any press ends the wait for a long press's release click. */ + | { readonly type: "pointer.down" } + | { readonly type: "touch.move"; readonly x: number; readonly y: number } + | { readonly type: "touch.up" } + | { readonly type: "touch.cancel" } + | { readonly type: "long-press.fired"; readonly attempt: number } + | { readonly type: "row.clicked"; readonly sessionID: string } + | { readonly type: "menu.open"; readonly sessionID: string; readonly x: number; readonly y: number } + | { readonly type: "menu.interact-outside"; readonly sessionID: string } + | { readonly type: "menu.closed"; readonly sessionID: string } + | { readonly type: "rename.start"; readonly sessionID: string; readonly title: string } + | { readonly type: "editor.input"; readonly sessionID: string; readonly draft: string } + | { readonly type: "editor.cancel"; readonly sessionID: string; readonly reason: "escape" | "blur" } + | { + readonly type: "editor.submit" + readonly sessionID: string + readonly server: ServerConnection.Key + readonly session: SessionInfo + /** The title the row shows now; submitting it unchanged saves nothing. */ + readonly title: string + } + | { readonly type: "rename.succeeded"; readonly attempt: number } + | { readonly type: "rename.failed"; readonly attempt: number } + | { readonly type: "rename.timed-out"; readonly attempt: number } + | { readonly type: "sessions.synced"; readonly sessionIDs: ReadonlySet } + | { readonly type: "disposed" } + +export type HomeSessionRowEffect = + | { readonly type: "long-press.start"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "long-press.stop" } + | { + readonly type: "rename.save" + readonly attempt: number + readonly server: ServerConnection.Key + readonly session: SessionInfo + readonly title: string + readonly timeoutMs: number + } + | { readonly type: "rename.abort"; readonly attempt: number } + | { readonly type: "toast.rename-timeout" } + /** `ifOwned`: only when focus is still on the row or nowhere, so a late result never steals focus. */ + | { readonly type: "focus.row"; readonly sessionID: string; readonly ifOwned: boolean } + | { readonly type: "focus.editor"; readonly sessionID: string; readonly select: boolean; readonly ifOwned: boolean } + +export type HomeSessionRowTransition = { + readonly state: HomeSessionRowState + readonly effects: readonly HomeSessionRowEffect[] +} + +type LiveState = Exclude + +export const INITIAL_HOME_SESSION_ROW_STATE: HomeSessionRowState = Object.freeze({ + status: "idle", + issued: 0, + suppressClick: undefined, +}) + +const DISPOSED: HomeSessionRowState = Object.freeze({ status: "disposed" }) + +const NONE: readonly HomeSessionRowEffect[] = Object.freeze([]) + +const STOP: readonly HomeSessionRowEffect[] = Object.freeze([{ type: "long-press.stop" }]) + +export function transitionHomeSessionRow( + state: HomeSessionRowState, + event: HomeSessionRowEvent, +): HomeSessionRowTransition { + if (state.status === "disposed") return unchanged(state) + + // A save in flight finishes in the background: the server may already have it, and the list then shows it. + if (event.type === "disposed") return { state: DISPOSED, effects: stop(state) } + + if (event.type === "touch.down") { + if ((state.status === "editing" || state.status === "renaming") && state.sessionID === event.sessionID) + return unchanged(state) + + const attempt = state.issued + 1 + + return { + state: { + status: "pressing", + issued: attempt, + attempt, + sessionID: event.sessionID, + x: event.x, + y: event.y, + menuX: event.menuX, + menuY: event.menuY, + }, + effects: [...stop(state), { type: "long-press.start", attempt, delayMs: HOME_SESSION_LONG_PRESS_MS }], + } + } + + if (event.type === "pointer.down" || event.type === "touch.cancel") { + if (event.type === "touch.cancel" && state.status === "pressing") return toIdle(state, STOP) + + return released(state) + } + + if (event.type === "touch.move") { + if (!selectLongPressMoved(state, event.x, event.y)) return unchanged(state) + + return toIdle(state, STOP) + } + + if (event.type === "touch.up") return state.status === "pressing" ? toIdle(state, STOP) : unchanged(state) + + if (event.type === "long-press.fired") { + if (state.status !== "pressing" || state.attempt !== event.attempt) return unchanged(state) + + return changed(menu(state, state.sessionID, state.menuX, state.menuY, true)) + } + + if (event.type === "row.clicked") + return selectRowSuppressClick(state, event.sessionID, 1) ? released(state) : unchanged(state) + + if (event.type === "menu.open") return opened(state, event) + + if (event.type === "menu.interact-outside") { + if (state.status !== "menu" || state.sessionID !== event.sessionID || state.outside) return unchanged(state) + + return changed({ ...state, outside: true }) + } + + if (event.type === "menu.closed") { + if (state.status !== "menu" || state.sessionID !== event.sessionID) return unchanged(state) + + return { + state: idle(state, state.suppressClick ? state.sessionID : undefined), + // A dismissal by interacting elsewhere leaves focus where the user put it. + effects: state.outside ? NONE : [{ type: "focus.row", sessionID: state.sessionID, ifOwned: false }], + } + } + + if (event.type === "rename.start") { + return { + state: { status: "editing", issued: state.issued, sessionID: event.sessionID, draft: event.title }, + effects: [...stop(state), { type: "focus.editor", sessionID: event.sessionID, select: true, ifOwned: false }], + } + } + + if (event.type === "editor.input") { + if (state.status !== "editing" || state.sessionID !== event.sessionID || state.draft === event.draft) + return unchanged(state) + + return changed({ ...state, draft: event.draft }) + } + + if (event.type === "editor.cancel") return cancelled(state, event) + + if (event.type === "editor.submit") return submitted(state, event) + + if (event.type === "sessions.synced") { + if (state.status === "idle" || event.sessionIDs.has(state.sessionID)) return unchanged(state) + + return toIdle(state, stop(state)) + } + + return settled(state, event) +} + +/** The row's open menu, positioned in the row, or undefined. */ +export function selectRowMenu(state: HomeSessionRowState, sessionID: string) { + return state.status === "menu" && state.sessionID === sessionID ? state : undefined +} + +/** The row's rename editor, or undefined while it shows as a button. */ +export function selectRowEditor(state: HomeSessionRowState, sessionID: string) { + return (state.status === "editing" || state.status === "renaming") && state.sessionID === sessionID + ? state + : undefined +} + +/** A click on the row is the release of a long press that opened its menu. Keyboard activation (`detail` 0) never is. */ +export function selectRowSuppressClick(state: HomeSessionRowState, sessionID: string, detail: number) { + if (detail === 0) return false + + if (state.status === "menu") return state.sessionID === sessionID && state.suppressClick + + return state.status === "idle" && state.suppressClick === sessionID +} + +/** A touch moved past the slop while waiting for a long press. Pointer moves are checked here before any event. */ +export function selectLongPressMoved(state: HomeSessionRowState, x: number, y: number) { + return ( + state.status === "pressing" && + (Math.abs(x - state.x) > HOME_SESSION_LONG_PRESS_SLOP_PX || Math.abs(y - state.y) > HOME_SESSION_LONG_PRESS_SLOP_PX) + ) +} + +// An Android long press also sends `contextmenu`; it opens the same menu and still owes the release click. +function opened( + state: LiveState, + event: Extract, +): HomeSessionRowTransition { + if (state.status === "editing" || state.status === "renaming") { + // The editor keeps the native menu, so paste and spelling work. + if (state.sessionID === event.sessionID) return unchanged(state) + } + + if (state.status === "menu" && state.sessionID === event.sessionID) { + if (state.x === event.x && state.y === event.y) return unchanged(state) + + return changed({ ...state, x: event.x, y: event.y }) + } + + const pressed = state.status === "pressing" && state.sessionID === event.sessionID + + return { state: menu(state, event.sessionID, event.x, event.y, pressed), effects: stop(state) } +} + +function cancelled( + state: LiveState, + event: Extract, +): HomeSessionRowTransition { + if ((state.status !== "editing" && state.status !== "renaming") || state.sessionID !== event.sessionID) + return unchanged(state) + + const focus: HomeSessionRowEffect = { type: "focus.row", sessionID: state.sessionID, ifOwned: false } + + if (state.status === "editing") return toIdle(state, event.reason === "escape" ? [focus] : NONE) + + // Clicking away while a save is in flight lets it finish; Escape cancels it. + if (event.reason === "blur") return unchanged(state) + + return toIdle(state, [{ type: "rename.abort", attempt: state.attempt }, focus]) +} + +function submitted( + state: LiveState, + event: Extract, +): HomeSessionRowTransition { + if (state.status !== "editing" || state.sessionID !== event.sessionID) return unchanged(state) + const title = state.draft.trim() + + if (!title || title === event.title) + return toIdle(state, [{ type: "focus.row", sessionID: state.sessionID, ifOwned: false }]) + + const attempt = state.issued + 1 + + return { + state: { status: "renaming", issued: attempt, attempt, sessionID: state.sessionID, draft: state.draft }, + effects: [ + { + type: "rename.save", + attempt, + server: event.server, + session: event.session, + title, + timeoutMs: HOME_SESSION_RENAME_TIMEOUT_MS, + }, + ], + } +} + +function settled( + state: LiveState, + event: Extract, +): HomeSessionRowTransition { + if (state.status !== "renaming" || state.attempt !== event.attempt) return unchanged(state) + + if (event.type === "rename.succeeded") + return toIdle(state, [{ type: "focus.row", sessionID: state.sessionID, ifOwned: true }]) + + const focus: HomeSessionRowEffect = { type: "focus.editor", sessionID: state.sessionID, select: false, ifOwned: true } + + return { + state: { status: "editing", issued: state.issued, sessionID: state.sessionID, draft: state.draft }, + effects: + event.type === "rename.failed" + ? [focus] + : [{ type: "rename.abort", attempt: state.attempt }, { type: "toast.rename-timeout" }, focus], + } +} + +// Ends the wait for a long press's release click. +function released(state: LiveState): HomeSessionRowTransition { + if (state.status === "menu" && state.suppressClick) return changed({ ...state, suppressClick: false }) + + if (state.status === "idle" && state.suppressClick !== undefined) return changed(idle(state, undefined)) + + return unchanged(state) +} + +function menu(state: LiveState, sessionID: string, x: number, y: number, suppressClick: boolean): HomeSessionRowState { + return { status: "menu", issued: state.issued, sessionID, x, y, suppressClick, outside: false } +} + +function idle(state: LiveState, suppressClick: string | undefined): HomeSessionRowState { + return { status: "idle", issued: state.issued, suppressClick } +} + +function toIdle(state: LiveState, effects: readonly HomeSessionRowEffect[]): HomeSessionRowTransition { + return { state: idle(state, undefined), effects } +} + +function stop(state: LiveState) { + return state.status === "pressing" ? STOP : NONE +} + +function changed(state: HomeSessionRowState): HomeSessionRowTransition { + return { state, effects: NONE } +} + +function unchanged(state: HomeSessionRowState): HomeSessionRowTransition { + return { state, effects: NONE } +} diff --git a/packages/app/src/home/sessions/search-machine.test.ts b/packages/app/src/home/sessions/search-machine.test.ts new file mode 100644 index 000000000000..9bb91bc4a288 --- /dev/null +++ b/packages/app/src/home/sessions/search-machine.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, test } from "bun:test" +import type { SessionInfo } from "@opencode/client/promise" +import type { HomeSessionRecord } from "./records" +import { + HOME_SESSION_LOOKUP_TIMEOUT_MS, + INITIAL_HOME_SESSION_SEARCH_STATE, + selectSearchExact, + selectSearchLookingUp, + selectSearchOpen, + selectSearchValue, + transitionHomeSessionSearch, + type HomeSessionSearchEffect, + type HomeSessionSearchEvent, + type HomeSessionSearchState, +} from "./search-machine" + +const SESSION_ID = "ses_0123456789abcdefghijklmnop" + +const record = (directory: string): HomeSessionRecord => ({ + // SAFETY: the machine stores the record as it is; only its identity matters here. + session: { id: SESSION_ID, location: { directory } } as SessionInfo, + project: { id: "proj", worktree: directory }, + projectName: "project", +}) + +const scope = (value: string, connected = true): HomeSessionSearchEvent => ({ + type: "scope.changed", + scope: value, + connected, +}) + +function replay(events: HomeSessionSearchEvent[], state = INITIAL_HOME_SESSION_SEARCH_STATE) { + return events.reduce<{ state: HomeSessionSearchState; effects: readonly HomeSessionSearchEffect[] }>( + (step, event) => transitionHomeSessionSearch(step.state, event), + { state, effects: [] }, + ) +} + +describe("home session search machine", () => { + test("tabbing out closes the results panel and keeps the text; tabbing back reopens it", () => { + const open = replay([scope("a\0"), { type: "focused" }, { type: "input.changed", value: "jump" }]) + expect(selectSearchOpen(open.state)).toBe(true) + + const blurred = replay([{ type: "blurred" }], open.state) + expect(selectSearchOpen(blurred.state)).toBe(false) + expect(selectSearchValue(blurred.state)).toBe("jump") + + expect(selectSearchOpen(replay([{ type: "focused" }], blurred.state).state)).toBe(true) + }) + + test("another server or project drops the exact match and looks the ID up again there", () => { + const found = replay([ + scope("a\0"), + { type: "input.changed", value: SESSION_ID }, + { type: "lookup.resolved", attempt: 1, record: record("/a") }, + ]) + + expect(selectSearchExact(found.state)).toEqual(record("/a")) + + const moved = replay([scope("b\0")], found.state) + expect(selectSearchExact(moved.state)).toBeUndefined() + expect(moved.effects).toEqual([ + { type: "lookup.start", attempt: 2, sessionID: SESSION_ID, timeoutMs: HOME_SESSION_LOOKUP_TIMEOUT_MS }, + ]) + + // The first server's late answer cannot land in the second server's search. + expect( + transitionHomeSessionSearch(moved.state, { type: "lookup.resolved", attempt: 1, record: record("/a") }).state, + ).toBe(moved.state) + + const inFlight = replay([scope("c\0")], moved.state) + expect(inFlight.effects[0]).toEqual({ type: "lookup.abort" }) + }) + + test("a session ID is looked up only while the server is connected", () => { + const text = replay([scope("a\0", true), { type: "input.changed", value: "jump" }]) + expect(text.effects).toEqual([]) + expect(selectSearchLookingUp(text.state)).toBe(false) + + const waiting = replay([scope("a\0", false), { type: "input.changed", value: SESSION_ID }]) + expect(waiting.effects).toEqual([]) + expect(selectSearchLookingUp(waiting.state)).toBe(false) + + const connected = replay([scope("a\0", true)], waiting.state) + expect(selectSearchLookingUp(connected.state)).toBe(true) + + const dropped = replay([scope("a\0", false)], connected.state) + expect(selectSearchLookingUp(dropped.state)).toBe(false) + expect(dropped.effects).toEqual([{ type: "lookup.abort" }]) + }) + + test("every lookup ends: found, missing, failed, timed out, closed or disposed", () => { + const looking = replay([scope("a\0"), { type: "focused" }, { type: "input.changed", value: SESSION_ID }]) + expect(selectSearchLookingUp(looking.state)).toBe(true) + + const missing = replay([{ type: "lookup.resolved", attempt: 1, record: undefined }], looking.state) + expect(missing.state.status).toBe("idle") + + const failed = replay([{ type: "lookup.failed", attempt: 1 }], looking.state) + expect(failed.state.status).toBe("idle") + expect(failed.effects).toEqual([]) + + const timedOut = replay([{ type: "lookup.timed-out", attempt: 1 }], looking.state) + expect(timedOut.state.status).toBe("idle") + expect(timedOut.effects).toEqual([{ type: "lookup.abort" }]) + + const closed = replay([{ type: "closed" }], looking.state) + expect(closed.state).toMatchObject({ status: "idle", focused: false, value: "" }) + expect(closed.effects).toEqual([{ type: "lookup.abort" }]) + + const disposed = replay([{ type: "disposed" }], looking.state) + expect(disposed.effects).toEqual([{ type: "lookup.abort" }]) + expect( + transitionHomeSessionSearch(disposed.state, { type: "lookup.resolved", attempt: 1, record: record("/a") }).state, + ).toBe(disposed.state) + }) +}) diff --git a/packages/app/src/home/sessions/search-machine.ts b/packages/app/src/home/sessions/search-machine.ts new file mode 100644 index 000000000000..4b6067e82187 --- /dev/null +++ b/packages/app/src/home/sessions/search-machine.ts @@ -0,0 +1,181 @@ +import { looksLikeSessionID } from "@/session/search" +import type { HomeSessionRecord } from "./records" + +export const HOME_SESSION_LOOKUP_TIMEOUT_MS = 10_000 + +type SearchFields = { + /** The server and project the results belong to; an exact match from another scope is never shown. */ + readonly scope: string + readonly connected: boolean + readonly issued: number + readonly focused: boolean + readonly value: string + readonly highlighted: string +} + +/** + * Home's session search. Typing a session ID looks it up on the focused server; `found` holds that session until the + * text, server or project changes. The results panel shows while the search has focus and text. + */ +export type HomeSessionSearchState = + | (SearchFields & { readonly status: "idle" }) + | (SearchFields & { readonly status: "looking-up"; readonly attempt: number; readonly sessionID: string }) + | (SearchFields & { readonly status: "found"; readonly exact: HomeSessionRecord }) + | { readonly status: "disposed" } + +export type HomeSessionSearchEvent = + | { readonly type: "scope.changed"; readonly scope: string; readonly connected: boolean } + | { readonly type: "focused" } + /** Focus left the search control, by keyboard or pointer. */ + | { readonly type: "blurred" } + | { readonly type: "closed" } + | { readonly type: "input.changed"; readonly value: string } + | { readonly type: "highlight.changed"; readonly key: string } + | { readonly type: "lookup.resolved"; readonly attempt: number; readonly record: HomeSessionRecord | undefined } + | { readonly type: "lookup.failed"; readonly attempt: number } + | { readonly type: "lookup.timed-out"; readonly attempt: number } + | { readonly type: "disposed" } + +export type HomeSessionSearchEffect = + | { readonly type: "lookup.start"; readonly attempt: number; readonly sessionID: string; readonly timeoutMs: number } + | { readonly type: "lookup.abort" } + +export type HomeSessionSearchTransition = { + readonly state: HomeSessionSearchState + readonly effects: readonly HomeSessionSearchEffect[] +} + +type LiveState = Exclude + +export const INITIAL_HOME_SESSION_SEARCH_STATE: HomeSessionSearchState = Object.freeze({ + status: "idle", + scope: "", + connected: false, + issued: 0, + focused: false, + value: "", + highlighted: "", +}) + +const DISPOSED: HomeSessionSearchState = Object.freeze({ status: "disposed" }) + +const NONE: readonly HomeSessionSearchEffect[] = Object.freeze([]) + +const ABORT: readonly HomeSessionSearchEffect[] = Object.freeze([{ type: "lookup.abort" }]) + +export function transitionHomeSessionSearch( + state: HomeSessionSearchState, + event: HomeSessionSearchEvent, +): HomeSessionSearchTransition { + if (state.status === "disposed") return unchanged(state) + + if (event.type === "disposed") return { state: DISPOSED, effects: aborts(state) } + + if (event.type === "focused") return state.focused ? unchanged(state) : changed({ ...state, focused: true }) + + if (event.type === "blurred") return state.focused ? changed({ ...state, focused: false }) : unchanged(state) + + if (event.type === "closed") { + if (state.status === "idle" && !state.focused && !state.value && !state.highlighted) return unchanged(state) + + return settle(state, { ...fields(state), focused: false, value: "", highlighted: "" }) + } + + if (event.type === "input.changed") { + if (event.value === state.value) return unchanged(state) + + return settle(state, { ...fields(state), value: event.value, highlighted: "" }) + } + + if (event.type === "highlight.changed") { + return event.key === state.highlighted ? unchanged(state) : changed({ ...state, highlighted: event.key }) + } + + if (event.type === "scope.changed") return rescope(state, event) + + if (state.status !== "looking-up" || state.attempt !== event.attempt) return unchanged(state) + + if (event.type === "lookup.resolved" && event.record) + return changed({ ...fields(state), status: "found", exact: event.record }) + + return { state: { ...fields(state), status: "idle" }, effects: event.type === "lookup.timed-out" ? ABORT : NONE } +} + +export function selectSearchValue(state: HomeSessionSearchState) { + return state.status === "disposed" ? "" : state.value +} + +export function selectSearchQuery(state: HomeSessionSearchState) { + return selectSearchValue(state).trim() +} + +export function selectSearchOpen(state: HomeSessionSearchState) { + return state.status !== "disposed" && state.focused && selectSearchQuery(state).length > 0 +} + +export function selectSearchLookingUp(state: HomeSessionSearchState) { + return state.status === "looking-up" +} + +export function selectSearchExact(state: HomeSessionSearchState) { + return state.status === "found" ? state.exact : undefined +} + +export function selectSearchHighlighted(state: HomeSessionSearchState) { + return state.status === "disposed" ? "" : state.highlighted +} + +// Another server or project drops the exact match and looks the ID up again there; a lookup waits for a connection. +function rescope(state: LiveState, event: Extract) { + if (event.scope === state.scope && event.connected === state.connected) return unchanged(state) + + if (event.scope !== state.scope) + return settle(state, { ...fields(state), scope: event.scope, connected: event.connected, highlighted: "" }) + + if (event.connected && state.status === "idle") return settle(state, { ...fields(state), connected: true }) + + if (!event.connected && state.status === "looking-up") + return { state: { ...fields(state), connected: false, status: "idle" as const }, effects: ABORT } + + return changed({ ...state, connected: event.connected }) +} + +function settle(previous: LiveState, next: SearchFields): HomeSessionSearchTransition { + const value = next.value.trim() + const sessionID = looksLikeSessionID(value) ? value : undefined + + if (!sessionID || !next.connected) return { state: { ...next, status: "idle" }, effects: aborts(previous) } + + const attempt = next.issued + 1 + + return { + state: { ...next, status: "looking-up", issued: attempt, attempt, sessionID }, + effects: [ + ...aborts(previous), + { type: "lookup.start", attempt, sessionID, timeoutMs: HOME_SESSION_LOOKUP_TIMEOUT_MS }, + ], + } +} + +function fields(state: LiveState): SearchFields { + return { + scope: state.scope, + connected: state.connected, + issued: state.issued, + focused: state.focused, + value: state.value, + highlighted: state.highlighted, + } +} + +function aborts(state: HomeSessionSearchState) { + return state.status === "looking-up" ? ABORT : NONE +} + +function changed(state: HomeSessionSearchState): HomeSessionSearchTransition { + return { state, effects: NONE } +} + +function unchanged(state: HomeSessionSearchState): HomeSessionSearchTransition { + return { state, effects: NONE } +} diff --git a/packages/app/src/home/sessions/search.ts b/packages/app/src/home/sessions/search.ts index bade5e332ada..7e954ec1ea3e 100644 --- a/packages/app/src/home/sessions/search.ts +++ b/packages/app/src/home/sessions/search.ts @@ -5,39 +5,72 @@ import { useServers } from "@/runtime/server/registry" import { displayName } from "@opencode/ui/project-avatar" import { sessionLabel } from "@/session/title" import { makeEventListener } from "@solid-primitives/event-listener" -import { createMemo, onCleanup, onMount } from "solid-js" -import { createStore } from "solid-js/store" +import { createEffect, createMemo, createSignal, onCleanup, onMount, untrack } from "solid-js" import type { HomeController } from "../model" import { homeSessionSearchKey, type HomeSessionRecord, type HomeSessionsController } from "./controller" -import { looksLikeSessionID } from "@/session/search" +import { + INITIAL_HOME_SESSION_SEARCH_STATE, + selectSearchExact, + selectSearchHighlighted, + selectSearchLookingUp, + selectSearchOpen, + selectSearchQuery, + selectSearchValue, + transitionHomeSessionSearch, + type HomeSessionSearchEffect, + type HomeSessionSearchEvent, +} from "./search-machine" type HomeSessionSearchSource = Pick +type PendingLookup = { controller: AbortController; timer: ReturnType } + export function createHomeSessionSearchController(home: HomeController, sessions: HomeSessionSearchSource) { const command = useCommand() const language = useLanguage() const layout = useLayout() const servers = useServers() - const [state, setState] = createStore<{ - value: string - focused: boolean - highlighted: string - exact: HomeSessionRecord | undefined - lookingUp: boolean - }>({ - value: "", - focused: false, - highlighted: "", - exact: undefined, - lookingUp: false, - }) - - let lookup = 0 + const [searchState, setSearchState] = createSignal(INITIAL_HOME_SESSION_SEARCH_STATE) + let lookup: PendingLookup | undefined let root: HTMLDivElement | undefined let input: HTMLInputElement | undefined let list: HTMLDivElement | undefined - const query = createMemo(() => state.value.trim()) + const query = createMemo(() => selectSearchQuery(searchState())) + const highlighted = createMemo(() => selectSearchHighlighted(searchState())) + + const dispatch = (event: HomeSessionSearchEvent) => + untrack(() => { + const previous = searchState() + const next = transitionHomeSessionSearch(previous, event) + + if (next.state !== previous) setSearchState(next.state) + next.effects.forEach(run) + }) + + function run(effect: HomeSessionSearchEffect) { + clearTimeout(lookup?.timer) + lookup?.controller.abort() + lookup = undefined + + if (effect.type === "lookup.abort") return + const controller = new AbortController() + const attempt = effect.attempt + const timer = setTimeout(() => dispatch({ type: "lookup.timed-out", attempt }), effect.timeoutMs) + lookup = { controller, timer } + void sessions.session.lookup(effect.sessionID, controller.signal).then( + (record) => { + clearTimeout(timer) + dispatch({ type: "lookup.resolved", attempt, record }) + }, + () => { + clearTimeout(timer) + + if (controller.signal.aborted) return + dispatch({ type: "lookup.failed", attempt }) + }, + ) + } const results = createMemo(() => { const value = query().toLowerCase() @@ -48,20 +81,22 @@ export function createHomeSessionSearchController(home: HomeController, sessions .searchRecords() .filter((record) => `${sessionLabel(record.session)} ${record.projectName}`.toLowerCase().includes(value)) - if (!state.exact || records.some((record) => record.session.id === state.exact?.session.id)) return records + const exact = selectSearchExact(searchState()) + + if (!exact || records.some((record) => record.session.id === exact.session.id)) return records - return [state.exact, ...records] + return [exact, ...records] }) const active = createMemo(() => { const records = results() - if (records.some((record) => homeSessionSearchKey(record) === state.highlighted)) return state.highlighted + if (records.some((record) => homeSessionSearchKey(record) === highlighted())) return highlighted() return records[0] ? homeSessionSearchKey(records[0]) : "" }) - const open = createMemo(() => state.focused && query().length > 0) + const open = createMemo(() => selectSearchOpen(searchState())) const placeholder = createMemo(() => { const project = home.project.selected() @@ -77,6 +112,14 @@ export function createHomeSessionSearchController(home: HomeController, sessions return language.t("home.sessions.search.placeholder") }) + // An exact match belongs to the server and project it was looked up in. + createEffect(() => { + const selection = home.selection.value() + const scope = `${selection.server ?? ""}\0${selection.directory ?? ""}` + const connected = home.server.focusedContext()?.sdk.connection.status() === "connected" + dispatch({ type: "scope.changed", scope, connected }) + }) + onCleanup( makeEventListener(document, "pointerdown", (event) => { if (!open()) return @@ -86,7 +129,7 @@ export function createHomeSessionSearchController(home: HomeController, sessions close() }), ) - onCleanup(() => lookup++) + onCleanup(() => dispatch({ type: "disposed" })) onMount(() => { if (layout.home.searchFocus.take()) focus() }) @@ -104,31 +147,17 @@ export function createHomeSessionSearchController(home: HomeController, sessions function focus() { input?.focus() - setState("focused", true) + dispatch({ type: "focused" }) } - function close() { - lookup++ - setState({ value: "", focused: false, exact: undefined, lookingUp: false }) + // Focus moving inside the search (to a result) keeps it open; the window losing focus keeps the input focused. + function blur(next: EventTarget | null) { + if ((next instanceof Node && root?.contains(next)) || document.activeElement === input) return + dispatch({ type: "blurred" }) } - function update(value: string) { - const current = ++lookup - const sessionID = value.trim() - setState({ value, highlighted: "", exact: undefined, lookingUp: false }) - - if (!looksLikeSessionID(sessionID)) return - setState("lookingUp", true) - void sessions.session.lookup(sessionID).then( - (record) => { - if (current !== lookup) return - setState({ exact: record, lookingUp: false }) - }, - () => { - if (current !== lookup) return - setState("lookingUp", false) - }, - ) + function close() { + dispatch({ type: "closed" }) } function select(record: HomeSessionRecord, options?: { background?: boolean }) { @@ -139,27 +168,29 @@ export function createHomeSessionSearchController(home: HomeController, sessions return { query: { - value: () => state.value, + value: () => selectSearchValue(searchState()), placeholder, open, focus, - input: update, + blur, + input: (value: string) => dispatch({ type: "input.changed", value }), close, }, result: { - loading: () => sessions.data.loading() || state.lookingUp, + loading: () => sessions.data.loading() || selectSearchLookingUp(searchState()), list: results, active, noResultsLabel: () => language.t("home.sessions.search.noResults", { query: query() }), - highlight: (record: HomeSessionRecord) => setState("highlighted", homeSessionSearchKey(record)), + highlight: (record: HomeSessionRecord) => + dispatch({ type: "highlight.changed", key: homeSessionSearchKey(record) }), move: (delta: number) => { const records = results() if (records.length === 0) return const index = records.findIndex((record) => homeSessionSearchKey(record) === active()) const next = ((index === -1 ? 0 : index) + delta + records.length) % records.length - setState("highlighted", homeSessionSearchKey(records[next])) - list?.querySelector(`[data-key="${state.highlighted}"]`)?.scrollIntoView({ block: "nearest" }) + dispatch({ type: "highlight.changed", key: homeSessionSearchKey(records[next]) }) + list?.querySelector(`[data-key="${highlighted()}"]`)?.scrollIntoView({ block: "nearest" }) }, select, selectActive: () => { diff --git a/packages/app/src/home/sessions/view.tsx b/packages/app/src/home/sessions/view.tsx index 87970dc512a1..ad3f4fc4a313 100644 --- a/packages/app/src/home/sessions/view.tsx +++ b/packages/app/src/home/sessions/view.tsx @@ -1,7 +1,7 @@ import type { SessionInfo } from "@opencode/client/promise" import { Key } from "@solid-primitives/keyed" -import { createEffect, createMemo, createSignal, For, Index, onCleanup, Show } from "solid-js" -import { createStore, type SetStoreFunction } from "solid-js/store" +import { createEffect, createMemo, createSignal, For, Index, Match, onCleanup, Show, Switch, untrack } from "solid-js" +import { createStore } from "solid-js/store" import { InlineInput } from "@opencode/ui/inline-input" import { Loader } from "@opencode/ui/loader" import { ActivityRing } from "@opencode/ui/activity-ring" @@ -11,10 +11,10 @@ import { IconButton } from "@opencode/ui/icon-button" import { Menu } from "@opencode/ui/menu" import { MenuScroll } from "@opencode/ui/menu-scroll" import { Tooltip } from "@opencode/ui/tooltip" -import { prefersReducedMotion } from "@opencode/ui/motion" import { useLanguage } from "@/runtime/i18n/language" import { ServerConnection } from "@/runtime/server/registry" import { SessionTabAvatarView } from "@/shell/layout/session-tab-avatar" +import { showToast } from "@/shell/notifications/toast" import { sessionLabel } from "@/session/title" import { shouldOpenSessionInBackground } from "./open" import { createAltHold } from "./alt-hold" @@ -26,6 +26,18 @@ import { type HomeSessionRecord, type OpenSessionOptions, } from "./controller" +import type { HomeSessionsFailure, HomeSessionsListView, HomeSessionsUnavailableReason } from "./load-machine" +import { + INITIAL_HOME_SESSION_ROW_STATE, + selectLongPressMoved, + selectRowEditor, + selectRowMenu, + selectRowSuppressClick, + transitionHomeSessionRow, + type HomeSessionRowEffect, + type HomeSessionRowEvent, + type HomeSessionRowState, +} from "./row-machine" const SHOW_HOME_SESSION_ARCHIVE = false @@ -33,12 +45,11 @@ const HOME_SECTION_LABEL = "text-v2-text-text-muted [font-weight:440]" const HOME_SESSION_SEARCH_RESULTS_ID = "home-session-search-results" -const HOME_SESSION_LONG_PRESS_MS = 500 +const POINTER_DOWN: HomeSessionRowEvent = Object.freeze({ type: "pointer.down" }) -const HOME_SESSION_PLACEHOLDER_DELAY_MS = 250 +const TOUCH_UP: HomeSessionRowEvent = Object.freeze({ type: "touch.up" }) -// Matches the list's reveal animation in view.css. -const HOME_SESSION_REVEAL_MS = 200 +const TOUCH_CANCEL: HomeSessionRowEvent = Object.freeze({ type: "touch.cancel" }) // Title widths for the placeholder rows, as a share of the row's label area. const HOME_SESSION_PLACEHOLDER_WIDTHS = [56, 38, 66, 46, 30, 52] @@ -59,7 +70,7 @@ function isBackgroundOpen(event: MouseEvent) { export type HomeSessionsViewProps = { language: ReturnType groups: HomeSessionGroup[] - loading: boolean + listView: HomeSessionsListView desktop: boolean location: (record: HomeSessionRecord) => { worktree: string; branch: string | undefined } onRevealLocations: (record?: HomeSessionRecord) => void @@ -76,10 +87,17 @@ export type HomeSessionsViewProps = { titleOpacity: (id: HomeSessionGroup["id"]) => number isOpenTab: (record: HomeSessionRecord) => boolean onCreateSession: () => void + onRetry: () => void onOpenSession: (session: SessionInfo, options?: OpenSessionOptions) => void onArchiveSession: (session: SessionInfo) => Promise - onRenameSession: (server: ServerConnection.Key, session: SessionInfo, title: string) => Promise - onExportSession: (server: ServerConnection.Key, session: SessionInfo) => Promise + onRenameSession: ( + server: ServerConnection.Key, + session: SessionInfo, + title: string, + signal: AbortSignal, + ) => Promise + onExportSession: (server: ServerConnection.Key, session: SessionInfo) => void + isExportingSession: (server: ServerConnection.Key, session: SessionInfo) => boolean onDeleteSession: (server: ServerConnection.Key, session: SessionInfo) => void onSetHoverTarget: (element: HTMLElement) => void onSetThumbTrack: (element: HTMLDivElement) => void @@ -90,6 +108,7 @@ export type HomeSessionsViewProps = { onSetSearchInput: (element: HTMLInputElement) => void onSetSearchList: (element: HTMLDivElement) => void onSearchFocus: () => void + onSearchBlur: (next: EventTarget | null) => void onSearchInput: (value: string) => void onSearchClose: () => void onSearchMove: (delta: number) => void @@ -98,29 +117,100 @@ export type HomeSessionsViewProps = { onSearchSelect: (record: HomeSessionRecord, options?: OpenSessionOptions) => void } -// Session store updates recreate row components, so row-local state would -// close an open context menu or drop an in-progress rename. Keep both keyed -// by session ID at the view root, like the projects list does. -type HomeSessionRowUI = { - menu: { id: string; x: number; y: number } | undefined - editor: { id: string; draft: string; renaming: boolean } | undefined -} - export function HomeSessionsView(props: HomeSessionsViewProps) { - const [rowUI, setRowUI] = createStore({ menu: undefined, editor: undefined }) + // Session store updates and date-group moves recreate row components, so the menu, long press and rename live here, + // keyed by session ID. + const [rowState, setRowState] = createSignal(INITIAL_HOME_SESSION_ROW_STATE) const [hover, setHover] = createStore<{ sessionID: string | undefined }>({ sessionID: undefined }) const showLocations = createAltHold(props.desktop, props.onRevealLocations) + let longPressTimer: ReturnType | undefined + const renames = new Map }>() + // A list that arrives within the delay paints directly; slower loads show placeholder rows until it does, which stay // mounted while the list fades in over them. - const [placeholder, setPlaceholder] = createSignal(false) + const skeleton = () => + (props.listView.status === "loading" && props.listView.skeleton) || + (props.listView.status === "ready" && props.listView.revealing) - createEffect(() => { - const timer = props.loading - ? setTimeout(() => setPlaceholder(true), HOME_SESSION_PLACEHOLDER_DELAY_MS) - : setTimeout(() => setPlaceholder(false), prefersReducedMotion() ? 0 : HOME_SESSION_REVEAL_MS) + const dispatchRow = (event: HomeSessionRowEvent) => + untrack(() => { + const previous = rowState() + const next = transitionHomeSessionRow(previous, event) + + if (next.state !== previous) setRowState(next.state) + next.effects.forEach(runRowEffect) + }) + + function runRowEffect(effect: HomeSessionRowEffect) { + if (effect.type === "long-press.start") { + clearTimeout(longPressTimer) + longPressTimer = setTimeout( + () => dispatchRow({ type: "long-press.fired", attempt: effect.attempt }), + effect.delayMs, + ) + + return + } + + if (effect.type === "long-press.stop") return clearTimeout(longPressTimer) + + if (effect.type === "rename.save") { + const attempt = effect.attempt + const controller = new AbortController() + const timer = setTimeout(() => dispatchRow({ type: "rename.timed-out", attempt }), effect.timeoutMs) + renames.set(attempt, { controller, timer }) + // A cancelled save resolves false for an attempt the machine already left. + void props.onRenameSession(effect.server, effect.session, effect.title, controller.signal).then((saved) => { + clearTimeout(timer) + renames.delete(attempt) + dispatchRow({ type: saved ? "rename.succeeded" : "rename.failed", attempt }) + }) + + return + } + + if (effect.type === "rename.abort") { + const rename = renames.get(effect.attempt) + clearTimeout(rename?.timer) + rename?.controller.abort() + renames.delete(effect.attempt) + + return + } + + if (effect.type === "toast.rename-timeout") { + showToast({ + title: props.language.t("common.requestFailed"), + description: props.language.t("home.sessions.load.timeout"), + }) + + return + } + + // Focus targets are looked up by session ID: rows remount, so instance refs can point at detached nodes. + const row = `[data-component="home-session-row-container"][data-session-id="${effect.sessionID}"]` + const active = document.activeElement + + if (effect.ifOwned && active !== document.body && !document.querySelector(row)?.contains(active)) return + requestAnimationFrame(() => { + if (effect.type === "focus.row") { + document.querySelector(`${row} [data-component="home-session-row"]`)?.focus() + + return + } + + const input = document.querySelector(`${row} [data-component="home-session-rename"]`) + input?.focus() - onCleanup(() => clearTimeout(timer)) + if (effect.select) input?.select() + }) + } + + createEffect(() => { + const sessionIDs = new Set(props.groups.flatMap((group) => group.sessions.map((record) => record.session.id))) + dispatchRow({ type: "sessions.synced", sessionIDs }) }) + onCleanup(() => dispatchRow({ type: "disposed" })) return (
- + - - 0} - fallback={ - + + {(failure) => ( + - } - > + )} + + + {(reason) => ( + + )} + + + + +
{/* Index keeps group subtrees mounted when the group arrays are rebuilt, so store updates cannot recreate rows mid-gesture. */} @@ -207,8 +316,8 @@ export function HomeSessionsView(props: HomeSessionsViewProps) { setHover("sessionID", sessionID)} @@ -220,13 +329,23 @@ export function HomeSessionsView(props: HomeSessionsViewProps) { )}
-
-
+ +
) } +const UNAVAILABLE_TITLE = { + offline: "session.error.unreachable", + auth: "session.error.signedOut", + incompatible: "session.error.incompatible", +} as const satisfies Record + +function failureDescription(failure: HomeSessionsFailure, language: ReturnType) { + return failure.type === "timeout" ? language.t("home.sessions.load.timeout") : failure.message +} + // The project avatar leads the row and never changes; a working session shows its activity ring at the row's trailing // edge, as session tabs do. `order-last` moves the ring past the labels from here, so one status subscription serves // both, and `ms-auto` pins it to the end even where the labels are `display: contents`. @@ -284,10 +403,17 @@ function HomeSessionSearch( ) { return (
-
+
props.onSearchBlur(event.relatedTarget)} + > + {/* Pressing in the panel keeps focus in the input, so the search stays open until a result opens. */}
event.preventDefault()} class={` absolute flex flex-col overflow-hidden rounded-[12px] bg-v2-background-bg-base shadow-[var(--v2-elevation-floating)] @@ -523,8 +649,8 @@ function HomeSessionGroupHeader(props: { function HomeSessionRow( props: HomeSessionsViewProps & { record: HomeSessionRecord - rowUI: HomeSessionRowUI - setRowUI: SetStoreFunction + rowState: HomeSessionRowState + onRowEvent: (event: HomeSessionRowEvent) => void showLocations: boolean hoveredSession: string | undefined onHoverSession: (sessionID: string | undefined) => void @@ -534,76 +660,12 @@ function HomeSessionRow( const location = createMemo(() => props.location(props.record)) const showProjectName = () => props.showProjectName && props.record.projectName const sessionID = () => props.record.session.id - const menu = () => (props.rowUI.menu?.id === sessionID() ? props.rowUI.menu : undefined) - const editor = () => (props.rowUI.editor?.id === sessionID() ? props.rowUI.editor : undefined) - let longPressTimer: ReturnType | undefined - let longPressStart: { x: number; y: number } | undefined - let suppressClick = false - let menuInteractedOutside = false - - // Focus targets are looked up by session ID: session store updates recreate - // row components, so instance refs can point at detached nodes by the time - // deferred focus runs. - const rowSelector = () => `[data-component="home-session-row-container"][data-session-id="${sessionID()}"]` - - const rowButton = () => - document.querySelector(`${rowSelector()} [data-component="home-session-row"]`) - - const renameInput = () => - document.querySelector(`${rowSelector()} [data-component="home-session-rename"]`) - - const clearLongPress = () => { - if (longPressTimer !== undefined) clearTimeout(longPressTimer) - longPressTimer = undefined - longPressStart = undefined - } - - onCleanup(clearLongPress) + const menu = () => selectRowMenu(props.rowState, sessionID()) + const editor = () => selectRowEditor(props.rowState, sessionID()) const openMenu = (element: HTMLElement, clientX: number, clientY: number) => { const bounds = element.getBoundingClientRect() - props.setRowUI("menu", { id: sessionID(), x: clientX - bounds.left, y: clientY - bounds.top }) - } - - const openEditor = () => { - props.setRowUI("editor", { id: sessionID(), draft: title(), renaming: false }) - requestAnimationFrame(() => { - const input = renameInput() - input?.focus() - input?.select() - }) - } - - const closeEditor = () => { - if (editor()?.renaming) return - props.setRowUI("editor", (value) => (value?.id === sessionID() ? undefined : value)) - } - - const saveEditor = async () => { - const current = editor() - - if (!current || current.renaming) return - props.setRowUI("editor", { ...current, renaming: true }) - const saved = await props.onRenameSession(props.server, props.record.session, current.draft) - // Disabling the input during the request drops focus to the body; restore - // it unless the user focused another control while the rename was pending. - const restore = document.activeElement === document.body || document.activeElement === renameInput() - props.setRowUI("editor", (value) => { - if (value?.id !== sessionID()) return value - - return saved ? undefined : { ...value, renaming: false } - }) - - if (!restore) return - requestAnimationFrame(() => { - if (saved) { - rowButton()?.focus() - - return - } - - renameInput()?.focus() - }) + props.onRowEvent({ type: "menu.open", sessionID: sessionID(), x: clientX - bounds.left, y: clientY - bounds.top }) } return ( @@ -634,17 +696,18 @@ function HomeSessionRow( aria-label={props.language.t("common.rename")} dir="auto" value={editor()?.draft ?? ""} - disabled={editor()?.renaming ?? false} + // Read-only rather than disabled keeps focus here while saving, so Escape can cancel the save. + readOnly={editor()?.status === "renaming"} + aria-busy={editor()?.status === "renaming" || undefined} class={` block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-v2-text-text-base [font-weight:530] field-sizing-content outline-none focus:outline-none focus-visible:outline-none ${showProjectName() ? "max-w-[min(70%,480px)] flex-[0_1_auto]" : "flex-[1_1_auto]"} `} style={{ "--inline-input-shadow": "none", "text-align": "start" }} - onInput={(event) => { - const draft = event.currentTarget.value - props.setRowUI("editor", (value) => (value?.id === sessionID() ? { ...value, draft } : value)) - }} + onInput={(event) => + props.onRowEvent({ type: "editor.input", sessionID: sessionID(), draft: event.currentTarget.value }) + } onKeyDown={(event) => { event.stopPropagation() @@ -656,17 +719,22 @@ function HomeSessionRow( if (event.key === "Enter") { event.preventDefault() - void saveEditor() + props.onRowEvent({ + type: "editor.submit", + sessionID: sessionID(), + server: props.server, + session: props.record.session, + title: title(), + }) return } if (event.key !== "Escape") return event.preventDefault() - closeEditor() - requestAnimationFrame(() => rowButton()?.focus()) + props.onRowEvent({ type: "editor.cancel", sessionID: sessionID(), reason: "escape" }) }} - onBlur={closeEditor} + onBlur={() => props.onRowEvent({ type: "editor.cancel", sessionID: sessionID(), reason: "blur" })} /> @@ -696,32 +764,24 @@ function HomeSessionRow( }} onMouseLeave={() => props.onHoverSession(undefined)} onPointerDown={(event) => { - suppressClick = false - - if (event.pointerType !== "touch") return - clearLongPress() - const element = event.currentTarget - const x = event.clientX - const y = event.clientY - longPressStart = { x, y } - longPressTimer = setTimeout(() => { - suppressClick = true - clearLongPress() - openMenu(element, x, y) - }, HOME_SESSION_LONG_PRESS_MS) + if (event.pointerType !== "touch") return props.onRowEvent(POINTER_DOWN) + const bounds = event.currentTarget.getBoundingClientRect() + props.onRowEvent({ + type: "touch.down", + sessionID: sessionID(), + x: event.clientX, + y: event.clientY, + menuX: event.clientX - bounds.left, + menuY: event.clientY - bounds.top, + }) }} onPointerMove={(event) => { - if (!longPressStart) return - - if (Math.abs(event.clientX - longPressStart.x) <= 8 && Math.abs(event.clientY - longPressStart.y) <= 8) - return - clearLongPress() - }} - onPointerUp={clearLongPress} - onPointerCancel={() => { - clearLongPress() - suppressClick = false + // Checked first so a move inside the slop, or with no long press pending, allocates nothing. + if (!selectLongPressMoved(props.rowState, event.clientX, event.clientY)) return + props.onRowEvent({ type: "touch.move", x: event.clientX, y: event.clientY }) }} + onPointerUp={() => props.onRowEvent(TOUCH_UP)} + onPointerCancel={() => props.onRowEvent(TOUCH_CANCEL)} onKeyDown={(event) => { if (event.key !== "ContextMenu" && (event.key !== "F10" || !event.shiftKey)) return event.preventDefault() @@ -729,17 +789,14 @@ function HomeSessionRow( openMenu(event.currentTarget, bounds.left + 12, bounds.bottom) }} onClick={(event) => { - // The flag stays set until the long-press compatibility click - // arrives, however delayed; keyboard activation (detail 0) is - // never that click and passes through. - if (suppressClick) { - suppressClick = false + // The long press's release click arrives however late; keyboard activation is never that click. + const suppress = selectRowSuppressClick(props.rowState, sessionID(), event.detail) + props.onRowEvent({ type: "row.clicked", sessionID: sessionID() }) - if (event.detail !== 0) { - event.preventDefault() + if (suppress) { + event.preventDefault() - return - } + return } props.onOpenSession(props.record.session, { background: isBackgroundOpen(event) }) @@ -780,36 +837,34 @@ function HomeSessionRow( open={!!menu()} onOpenChange={(open) => { if (open) return - props.setRowUI("menu", (value) => (value?.id === sessionID() ? undefined : value)) + props.onRowEvent({ type: "menu.closed", sessionID: sessionID() }) }} > + {/* Disabled, so it takes no focus: Kobalte focuses the trigger on close, which would blur the rename editor + the Rename item just opened. Closing the menu restores focus to the row instead. */}