Compare commits

..
Author SHA1 Message Date
Filip Hejmowski 59632748f1 fix(core): limit snapshot retry to Windows object writes 2026-10-16 18:55:05 +02:00
Filip Hejmowski dcdfe2e37c fix(core): retry snapshot capture when concurrent Git writes collide on Windows 2026-10-16 18:48:09 +02:00
Filip 0a03b4bc9c test: fix Windows flakes in cli standalone, Storybook and snapshot tests (#56181) 2026-10-16 18:24:02 +02:00
Filip 582c974ee3 fix(ci): include PrivacyUrl in WinGet locale manifests (#56123) 2026-10-16 17:34:55 +02:00
Filip 24c7f7a17a fix(update): accept publish tokens only from dev and beta (#56085) 2026-10-16 17:31:45 +02:00
Filip b1d5965eec fix(ci): run app e2e on dev and every package's unit tests (#56117) 2026-10-16 17:31:14 +02:00
opencode-agent[bot]andthdxr ed772f5009 chore(release): drop the separate opencode-beta release repo (#56083)
Co-authored-by: thdxr <826656+thdxr@users.noreply.github.com>
2026-10-16 13:54:42 +00:00
Jack c5681f4e15 fix(stats): merge Cat Jam usage into Reflection Beam (#56025) 2026-10-16 21:44:35 +08:00
opencode-agent[bot]andthdxr c3a73eca34 fix(cli): don't crash auth login when no browser opener is available (#56082)
Co-authored-by: thdxr <thdxr@users.noreply.github.com>
2026-10-16 13:42:50 +00:00
opencode-agent[bot]anddc85 e1bba47bc3 docs(console): rename Cat Jam Free to Beam Free (#55993)
Co-authored-by: dc85 <83497+dc85@users.noreply.github.com>
2026-10-16 21:42:39 +08:00
opencode 83c5abbbe3 sync release versions for v2.0.31 [skip ci] 2026-10-16 12:37:41 +00:00
opencode-agent[bot] d68cf94dc2 chore(core): refresh bundled models.dev snapshot 2026-10-16 12:24:35 +00:00
Victor Navarro bd902fcb46 fix(tui): copy compaction summary as last message (#56055) 2026-10-16 14:22:53 +02:00
Victor Navarro b0d762154c feat(tui): make /copy copy last assistant message (#56053) 2026-10-16 14:16:53 +02:00
Victor Navarro d889cb2044 feat(core): read model reasoning from config (#55853) 2026-10-16 13:36:18 +02:00
Aarav Sareen 00e7472faa feat(tui): new dialog designs behind new designs experiment (#55810)
Lands the rest of the dialog redesign stack, all behind the new-designs experiment:

- put dialog search in the title row (#55800)
- hide dialog search on short lists (#55801)
- read the experiment through useNewDesigns (#55802)
- raise dialog footers (#55805)
- standardize dialog footer actions (#55806)
- style selected dialog list rows (#55807)
- show list overflow indicator (#55808)
- restyle dialog headers (#55809)
- use vivid agent colors (#55810)
2026-10-16 15:15:15 +05:30
Aarav Sareen 50d4280dbd refactor(tui): build DialogSelect on DialogLayout (#55799) 2026-10-16 14:52:35 +05:30
Aarav Sareen c5e513e98e feat(tui): add opencode2 theme and text.faint token (#55798) 2026-10-16 14:48:08 +05:30
Aarav Sareen 09ef07e11e feat(tui): add new designs experiment (#55818) 2026-10-16 14:36:10 +05:30
Jack 7b99646cf1 docs(go): remove retired Go models (#55761) 2026-10-16 16:38:49 +08:00
Jack 37e3912d8e docs(console): add GLM-5.3-Flash Free (#55975) 2026-10-16 14:34:24 +08:00
Aiden Cline f0c122f717 fix(update): cache rollout fallback reads (#55205) 2026-10-16 01:33:46 -05:00
opencode-agent[bot]anddc85 e3d10de997 docs(console): add LL Alpha Free (#55969)
Co-authored-by: dc85 <83497+dc85@users.noreply.github.com>
2026-10-15 23:31:33 -07:00
Aiden Cline 538f8b1da6 fix(core): respell variants when config changes a catalog model's package (#55962) 2026-10-16 01:26:53 -05:00
Aiden Cline f09eee5002 fix(core): treat unreadable config file references as empty (#55959) 2026-10-16 01:12:37 -05:00
Aiden Cline 4cce6aef4e fix(core): prioritize preferred free OpenCode models when signed out (#55972) 2026-10-16 01:09:50 -05:00
Aiden Cline ccc6a3fd59 fix(core): escape env config values that break parsing (#55915) 2026-10-16 00:33:51 -05:00
Aiden Cline 32b41bab13 test(cli): simplify service env test (#55952) 2026-10-16 00:14:35 -05:00
Lucas Kimandkimnamu e3d5a3bdd3 fix(core): hide newer Bedrock bare IDs that require inference profiles (#54486)
Co-authored-by: kimnamu <kimnamu@users.noreply.github.com>
2026-10-16 00:14:09 -05:00
JasonH 723a2f6892 fix(cli): load saved environment when starting managed services (#50907) 2026-10-16 00:05:51 -05:00
Aiden Cline b0a8e2501b fix(ai): honor Anthropic cache format on Bedrock Converse (#55942) 2026-10-15 23:53:14 -05:00
Jensen eeec76bb62 fix(tui): transparent background for embedded terminal panel (#55396) 2026-10-15 22:46:19 -04:00
Luke Parker e25b7abf89 fix(session-ui): slide the tool group count when it changes (#55617) 2026-10-16 11:10:33 +10:00
xin zhuangandAiden Cline 706a688994 fix(core): omit compaction replay context from sanitized exports (#55592)
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-15 20:10:25 -05:00
Aiden Cline 20d172e462 docs: document external_directory allow default (#55885) 2026-10-15 20:09:02 -05:00
opencode-agent[bot] 7049e5af4d chore(core): refresh bundled models.dev snapshot 2026-10-16 00:40:26 +00:00
Luke Parker d7d44a7e03 fix(app): fade long file names at the edge of the file tree (#55889) 2026-10-15 23:46:27 +00:00
Luke Parker 867a77a38f fix(app): keep the review pane steady when the side terminal toggles (#55879) 2026-10-15 23:34:29 +00:00
2e7ac8c8ea fix(tui): roll the compact form over to M at the rounding boundary (#55871)
Co-authored-by: argszero <argszero@users.noreply.github.com>
Co-authored-by: Tarquinen <78942835+Tarquinen@users.noreply.github.com>
2026-10-15 19:34:22 -04:00
Luke Parker 13263f30ed chore(release): publish the desktop app from beta (#55878) 2026-10-16 09:01:10 +10:00
opencode-agent[bot] b3aa790aae chore: update nix node_modules hashes 2026-10-15 22:45:48 +00:00
Filip d0f3204619 fix(util): hide plugin Git console windows on Windows (#55475) 2026-10-16 00:45:40 +02:00
Filip 17229d24f5 chore(ci): speed up and stabilize the test workflow (#55866) 2026-10-16 00:35:49 +02:00
DanteandDaniel Smolsky 7a4a03212e fix(core): seed configured limits before model transforms (#55778)
Co-authored-by: Daniel Smolsky <dannysmo@gmail.com>
2026-10-15 18:26:21 -04:00
berce e89206d397 fix(tui): say why /editor did nothing when no editor is set (#55872) 2026-10-15 17:12:22 -05:00
8db638c53c fix(core): default to big-pickle when only free OpenCode models are available (#55852)
Co-authored-by: rekram1-node <rekram1-node@users.noreply.github.com>
Co-authored-by: Aiden Cline <aidenpcline@gmail.com>
2026-10-15 17:05:21 -05:00
237 changed files with 4292 additions and 1895 deletions

No files matched your search

+5 -10
View File
@@ -49,8 +49,11 @@ runs:
echo "dir=$(bun pm cache)" >> "$GITHUB_OUTPUT"
echo "version=$(bun --version)" >> "$GITHUB_OUTPUT"
# On Windows, extracting the cache archive takes longer than Bun downloading and
# extracting the same packages itself, so Windows installs skip the cache.
- name: Restore Bun dependencies
id: bun-cache
if: runner.os != 'Windows'
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.cache.outputs.dir }}
@@ -61,19 +64,11 @@ runs:
shell: bash
- name: Install dependencies
run: |
# Workaround for patched peer variants
# e.g. ./patches/ for standard-openapi
# https://github.com/oven-sh/bun/issues/28147
if [ "$RUNNER_OS" = "Windows" ]; then
bun install --frozen-lockfile --linker hoisted ${{ inputs.install-flags }}
else
bun install --frozen-lockfile ${{ inputs.install-flags }}
fi
run: bun install --frozen-lockfile ${{ inputs.install-flags }}
shell: bash
- name: Save Bun dependencies
if: steps.bun-cache.outputs.cache-hit != 'true' && github.event_name != 'pull_request' && github.event_name != 'pull_request_target'
if: runner.os != 'Windows' && steps.bun-cache.outputs.cache-hit != 'true' && github.event_name != 'pull_request' && github.event_name != 'pull_request_target'
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: ${{ steps.cache.outputs.dir }}
+1 -1
View File
@@ -6,7 +6,7 @@ permissions:
on:
workflow_dispatch:
push:
branches: [dev, beta]
branches: [dev]
paths:
- "bun.lock"
- "package.json"
+9 -9
View File
@@ -68,12 +68,10 @@ jobs:
OPENCODE_BUMP: ${{ inputs.bump }}
OPENCODE_VERSION: ${{ inputs.version }}
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
GH_REPO: ${{ (github.ref_name == 'beta' && 'anomalyco/opencode-beta') || github.repository }}
outputs:
version: ${{ steps.version.outputs.version }}
release: ${{ steps.version.outputs.release }}
tag: ${{ steps.version.outputs.tag }}
repo: ${{ steps.version.outputs.repo }}
build-cli:
needs: version
@@ -102,7 +100,7 @@ jobs:
env:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
GH_REPO: ${{ needs.version.outputs.repo }}
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ steps.committer.outputs.token }}
- name: Build preview CLI
@@ -113,7 +111,7 @@ jobs:
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
OPENCODE_RELEASE: ${{ needs.version.outputs.release }}
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
GH_REPO: ${{ needs.version.outputs.repo }}
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ steps.committer.outputs.token }}
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
@@ -141,7 +139,8 @@ jobs:
sign-cli-macos:
needs: build-cli
runs-on: macos-26
if: github.repository == 'anomalyco/opencode'
# Beta publishes only the desktop app, which signs the CLI it bundles.
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta'
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
@@ -196,7 +195,7 @@ jobs:
needs: version
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
if: github.repository == 'anomalyco/opencode' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
steps:
- uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0
@@ -218,7 +217,7 @@ jobs:
needs:
- version
- build-node-app-archive
if: github.repository == 'anomalyco/opencode' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
if: github.repository == 'anomalyco/opencode' && github.ref_name != 'beta' && !(github.ref_name == 'dev' && (inputs.bump || inputs.version))
strategy:
fail-fast: false
matrix:
@@ -276,7 +275,7 @@ jobs:
needs:
- sign-cli-macos
runs-on: blacksmith-4vcpu-windows-2025
if: github.repository == 'anomalyco/opencode' && (github.ref_name == 'dev' || github.ref_name == 'beta')
if: github.repository == 'anomalyco/opencode' && github.ref_name == 'dev'
env:
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
@@ -591,6 +590,7 @@ jobs:
path: packages/opencode/dist
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
if: github.ref_name != 'beta'
with:
name: opencode-preview-cli
path: packages/cli/dist
@@ -648,7 +648,7 @@ jobs:
OPENCODE_RELEASE_NOTES: ${{ (github.ref_name == 'dev' && inputs.release_notes) || '' }}
AUR_KEY: ${{ secrets.AUR_KEY }}
GITHUB_TOKEN: ${{ steps.committer.outputs.token }}
GH_REPO: ${{ needs.version.outputs.repo }}
GH_REPO: ${{ github.repository }}
NPM_CONFIG_PROVENANCE: false
LATEST_YML_DIR: /tmp/latest-yml
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
+119 -58
View File
@@ -25,13 +25,14 @@ jobs:
name: affected packages
runs-on: blacksmith-4vcpu-ubuntu-2404
outputs:
app: ${{ steps.packages.outputs.app }}
e2e: ${{ steps.packages.outputs.app }}
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
# Pull requests diff against the merge's first parent; pushes diff against the previous dev head.
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
- name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
@@ -48,7 +49,8 @@ jobs:
echo "app=true" >> "$GITHUB_OUTPUT"
exit 0
fi
bun x turbo@2.10.2 ls --affected --filter=@opencode/app --output=json > affected.json
# Storybook hosts the component tests, but no app package depends on it.
bun x turbo@2.10.2 ls --affected --filter=@opencode/app --filter=@opencode/storybook --output=json > affected.json
bun -e 'const result = await Bun.file("affected.json").json(); console.log(`app=${result.packages.count > 0}`)' >> "$GITHUB_OUTPUT"
unit:
@@ -70,7 +72,8 @@ jobs:
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
# Pull requests diff against the merge's first parent; pushes diff against the previous dev head.
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
- name: Setup Node
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
@@ -93,15 +96,6 @@ jobs:
git config --global user.email "bot@opencode.ai"
git config --global user.name "opencode"
- name: Cache Turbo
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: node_modules/.cache/turbo
key: turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}-${{ github.sha }}
restore-keys: |
turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}-
turbo-${{ runner.os }}-
- name: Run unit tests
timeout-minutes: 20
run: |
@@ -134,32 +128,6 @@ jobs:
TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }}
TURBO_SCM_HEAD: ${{ github.sha }}
- name: Verify compiled service lifecycle
if: always()
timeout-minutes: 10
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build.ts --single --skip-install
bun run script/service-smoke.ts
- name: Setup Node build runtime
if: always()
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- name: Verify Node build
if: always()
timeout-minutes: 15
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build-node.ts --single --skip-install --outdir=dist/node
bun run script/service-smoke.ts --node
- name: Check generated client
if: runner.os == 'Linux'
working-directory: packages/client
@@ -170,9 +138,8 @@ jobs:
working-directory: services/www
run: bun run check:generated
e2e:
name: e2e (${{ matrix.settings.name }})
needs: affected
build:
name: build (${{ matrix.settings.name }})
strategy:
fail-fast: false
matrix:
@@ -182,39 +149,112 @@ jobs:
- name: windows
host: blacksmith-4vcpu-windows-2025
runs-on: ${{ matrix.settings.host }}
defaults:
run:
shell: bash
steps:
- name: Checkout repository
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
# Pull requests diff against the merge's first parent; pushes diff against the previous dev head.
fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 0 }}
- name: Setup Bun
uses: ./.github/actions/setup-bun
- name: Verify compiled service lifecycle
timeout-minutes: 10
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build.ts --single --skip-install
bun run script/service-smoke.ts
# Unit tests import workspace sources and never build the libraries they use, so this checks those builds. The
# CLI and app closures hold every library a tested package depends on. The builds are tsc and Bun.build with no
# platform-specific steps, and the libraries publish from Linux, so Windows skips them.
- name: Build workspace libraries
if: ${{ !cancelled() && runner.os == 'Linux' }}
timeout-minutes: 10
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
bun turbo build --concurrency=3 --filter='@opencode/cli^...' --filter='@opencode/app^...'
exit 0
fi
bun turbo build --affected --concurrency=3 --filter='@opencode/cli^...' --filter='@opencode/app^...'
env:
TURBO_SCM_BASE: ${{ github.event_name == 'pull_request' && format('{0}^1', github.sha) || github.event.before }}
TURBO_SCM_HEAD: ${{ github.sha }}
- name: Setup Node build runtime
if: ${{ !cancelled() }}
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "26.4.0"
- name: Verify Node build
if: ${{ !cancelled() }}
timeout-minutes: 15
working-directory: packages/cli
env:
NODE_OPTIONS: ${{ runner.os == 'Windows' && '--max-old-space-size=4096' || '' }}
run: |
bun run script/build-node.ts --single --skip-install --outdir=dist/node
bun run script/service-smoke.ts --node
e2e-suite:
name: e2e (${{ matrix.settings.name }}, ${{ matrix.suite.id }})
needs: affected
if: needs.affected.outputs.e2e == 'true'
strategy:
fail-fast: false
matrix:
settings:
- name: linux
host: blacksmith-4vcpu-ubuntu-2404
- name: windows
host: blacksmith-4vcpu-windows-2025
# Playwright splits whole spec files across shards by test count, not duration. Every app-N
# entry must use the same total, and the entries must cover 1..total. The service worker suite
# reuses shard 2's production build. Each component suite runs once per OS in its own leg, so the
# two suites' Storybook servers and test time are not added up on one runner.
suite:
- id: app-1
shard: 1/2
- id: app-2
shard: 2/2
- id: session-ui-components
- id: app-components
runs-on: ${{ matrix.settings.host }}
env:
E2E_ENABLED: ${{ needs.affected.outputs.app == 'true' && github.ref_name != 'dev' && github.head_ref != 'dev' }}
PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.playwright-browsers
defaults:
run:
shell: bash
steps:
- name: Checkout repository
if: env.E2E_ENABLED == 'true'
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node
if: env.E2E_ENABLED == 'true'
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
# Playwright 1.59 hangs while extracting Chromium with Node 24.16.
node-version: "24.15"
- name: Setup Bun
if: env.E2E_ENABLED == 'true'
uses: ./.github/actions/setup-bun
- name: Read Playwright version
if: env.E2E_ENABLED == 'true'
id: playwright-version
run: |
version=$(node -e 'console.log(require("./package.json").workspaces.catalog["@playwright/test"])')
echo "version=$version" >> "$GITHUB_OUTPUT"
- name: Cache Playwright browsers
if: env.E2E_ENABLED == 'true'
id: playwright-cache
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
@@ -222,47 +262,47 @@ jobs:
key: ${{ runner.os }}-${{ runner.arch }}-playwright-${{ steps.playwright-version.outputs.version }}-chromium
- name: Install Playwright system dependencies
if: env.E2E_ENABLED == 'true' && runner.os == 'Linux'
if: runner.os == 'Linux'
working-directory: packages/app
run: bunx playwright install-deps chromium
- name: Install Playwright browsers
if: env.E2E_ENABLED == 'true' && steps.playwright-cache.outputs.cache-hit != 'true'
if: steps.playwright-cache.outputs.cache-hit != 'true'
working-directory: packages/app
run: bunx playwright install chromium
- name: Run app e2e tests against production build
if: env.E2E_ENABLED == 'true'
run: bun --cwd packages/app test:e2e:built
if: matrix.suite.shard
run: bun --cwd packages/app test:e2e:built --shard=${{ matrix.suite.shard }}
env:
CI: true
timeout-minutes: 30
timeout-minutes: 15
- name: Verify service worker precaching and upgrades
if: env.E2E_ENABLED == 'true'
if: matrix.suite.shard == '2/2'
working-directory: packages/app
run: bunx playwright test --config e2e/service-worker/playwright.config.ts
timeout-minutes: 5
- name: Run session UI component tests
if: ${{ !cancelled() && env.E2E_ENABLED == 'true' }}
if: matrix.suite.id == 'session-ui-components'
run: bun --cwd packages/session-ui test:components
env:
CI: true
timeout-minutes: 15
- name: Run app component tests
if: ${{ !cancelled() && env.E2E_ENABLED == 'true' }}
if: matrix.suite.id == 'app-components'
run: bun --cwd packages/app test:components
env:
CI: true
timeout-minutes: 15
- name: Upload Playwright artifacts
if: always() && env.E2E_ENABLED == 'true'
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: playwright-${{ matrix.settings.name }}-${{ github.run_attempt }}
name: playwright-${{ matrix.settings.name }}-${{ matrix.suite.id }}-${{ github.run_attempt }}
if-no-files-found: ignore
retention-days: 7
path: |
@@ -272,3 +312,24 @@ jobs:
packages/session-ui/component-tests/playwright-report
packages/app/component-tests/test-results
packages/app/component-tests/playwright-report
# Branch rules require one e2e check per OS. These keep those names and pass only when every
# leg above passed, or when no leg was needed; a failing leg on either OS fails both checks.
e2e:
name: e2e (${{ matrix.os }})
needs: [affected, e2e-suite]
if: ${{ !cancelled() }}
strategy:
fail-fast: false
matrix:
os: [linux, windows]
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Check browser test results
env:
AFFECTED: ${{ needs.affected.result }}
SUITES: ${{ needs.e2e-suite.result }}
EXPECTED: ${{ needs.affected.outputs.e2e == 'true' && 'success' || 'skipped' }}
run: |
echo "affected packages: $AFFECTED, browser test legs: $SUITES (expected $EXPECTED)"
test "$AFFECTED" = success && test "$SUITES" = "$EXPECTED"
+138
View File
@@ -0,0 +1,138 @@
---
name: app-e2e-tests
description: Use when writing, changing, reviewing, or debugging Playwright e2e tests in packages/app/e2e (regression keepers and user stories). Covers the mocked opencode server harness and the Bun static server, per-test isolation, page-load and route cost, the suite-wide service-worker block, races with first mount, hover, measurement, clock, dialogs and shortcuts, projects, shards and worker scheduling, rehearsing Windows timing locally, and diagnosing a CI flake from its artifacts. Not for Storybook component tests or e2e/performance benchmarks.
---
# App e2e tests
Read `packages/app/e2e/AGENTS.md` and the Tests section of `packages/app/AGENTS.md` first. They define what to test, which locators to use, and how to assert. `packages/app/README.md` (E2E Testing) documents run modes and env vars. This skill covers what makes these tests slow or flaky in CI, which runs the suite as two shards per OS on 4-vCPU runners (`.github/workflows/test.yml:207-229`). Most races below were found on Windows.
All paths below are relative to `packages/app` unless they start with `packages/`, `services/` or `.github/`.
## What a test runs against
- **No opencode backend.** Each shard leg runs `bun --cwd packages/app test:e2e:built --shard=<n>/2` (`test.yml:274-279`). It builds once and starts one Bun static server, `e2e/utils/serve.ts`, on `127.0.0.1:${PLAYWRIGHT_PORT ?? 3000}`. All 5 workers share it (`playwright.config.ts:23-27`).
- `serve.ts` keeps vite preview's SPA fallback rules. Do not move built e2e back to vite preview. On case-insensitive file systems it synchronously reads the whole `dist/_assets` directory (about 3,100 files) for every asset request, so every worker's page loads wait in line. The `e2e/performance` configs still use it to keep their baselines comparable.
- **The API is an in-memory mock per page,** running in the test worker. `mockOpenCodeServer` (`e2e/utils/mock-server.ts:202`):
- answers `page.route("**/api/**")` with an Effect HttpApi handler;
- fakes `/api/event` SSE with an init-script `fetch` override;
- serves PTY sockets through `routeWebSocket`.
- **Unmocked routes fail the test** with a 501 and `Unmocked API request` (`mock-server.ts:403-411`). Add the route to `mock-server.ts` once instead of routing around it in a spec.
- **Build pages with the helpers:**
- `mockWorkspace`, `openSession`, `openDraft`, `openWorktreeDraft`, `mockRemoteServer`, `openSettings` (`e2e/utils/workspace.ts`);
- `setupTimeline` (`e2e/utils/timeline.ts:209`) for streamed timelines, `mockServers` (`mock-server.ts:495`) for several origins;
- `seed` (`e2e/utils/app.ts:61`) for storage, `holdRoute` (`app.ts:207`) to hold requests until you release them.
- **Deliver events** with the mock's `push`, which buffers until the app connects, or with `installSseTransport` (`e2e/utils/sse-transport.ts:60`), whose `send` resolves on delivery. After `page.reload()`, await `transport.waitForConnection()` before sending (`e2e/regression/timeline-stream.spec.ts:1700-1702`).
- **Windows-only failures are races, not Windows code paths.** Mock directories are `C:/OpenCode/<name>` on every OS (`workspace.ts:33`), and nothing touches the disk. Lazy chunks, stylesheets and responses finish out of order more often on the Windows runners.
## Isolation
- **No shared state between tests.** Each test gets a fresh context, mock handler and init scripts. Outside `e2e/service-worker`, which runs under its own config and shares builds through a worker fixture (`e2e/service-worker/cache.spec.ts:21`, `:74`), app e2e has no `beforeAll`, serial mode, `test.extend` or worker fixtures. Keep it that way so `-g` and `PLAYWRIGHT_FULLY_PARALLEL=1` keep working.
- **Handlers mutate the objects you pass.** Creating a session pushes into `sessions` (`mock-server.ts:839`). Renaming writes `session.title` (`:1340`), and VCS init writes `project.vcs` (`:1019`).
- Call `session()`/`project()` inside the test.
- `mockWorkspace` and `openSession` copy what you pass (`workspace.ts:36-48`).
- `mockOpenCodeServer` and `mockServers` use your objects as they are. Module-level fixtures like `multi-server.spec.ts:10-19` are therefore shared by every test in the file.
- **Timeline builders keep state per test attempt** (`timeline.ts:165-198`). Call stateful builders such as `assistantMessage` or `partUpdated` inside the test. Only pure ones such as `toolPart` belong at module scope.
- **Seed before the first `goto`.** `seed` writes storage once per tab behind a `sessionStorage` marker, so reloads keep what the app stored (`app.ts:59-90`). It cannot reset state mid-test.
## Keep it fast
- **Navigate once.** Every `goto` or `reload` is a cold load of the production bundle: about 150 requests per session open, about 125 of them static files. Each test has a new context, and any `page.route` disables the HTTP cache. Reach later states through the UI or through pushed events. Reload only when surviving a reload is the contract.
- **Service workers are already blocked suite-wide** (`serviceWorkers: "block"`, `playwright.config.ts:66-67`). Do not add a per-file block; the 11 in `e2e/regression` are redundant.
- Production registers `/sw.js` on load (`src/entry.tsx:54-55`) and precaches about 1,600 files (`globPatterns: ["**/*"]`, `vite.pwa.ts:34`). `e2e/service-worker/` covers it under its own config. The main config ignores that directory (`playwright.config.ts:33-36`), and CI runs it after shard 2 (`test.yml:281-285`).
- Opt back in with `test.use({ serviceWorkers: "allow" })` only when the worker is the contract. It never controls the first load (`clientsClaim: false`, `vite.pwa.ts:26-28`). After a reload it can control the page, and page routes may then miss its requests.
- Every built-mode page load logs Playwright's block warning. Console collectors must ignore it, as `captureConsoleWarnings` does (`e2e/utils/command-palette.ts:15-26`).
- **Match new routes with a RegExp or a query-aware glob, not a function.**
- A single function matcher makes Playwright intercept `**/*` for the page. Every static asset then round-trips to the test worker (250 continued requests in one Windows test).
- Existing `holdRoute` calls such as `review.spec.ts:51` and `mockMissingLocation` (`mock-server.ts:480`) still use functions and pay this. Converting one route gains nothing while another function route is registered on the page.
- Globs match the whole URL, so `**/api/vcs/init` misses `/api/vcs/init?location...`. Write `/\/api\/vcs\/init\?/` or `"**/api/session?*"` (`command-palette.spec.ts:10`, `:28`).
- **Use the stress fixture only when scale is the contract.** `fixture`, `mockStressTimeline` and `installStressSessionTabs` (`e2e/utils/session-fixture.ts:336`, `:436`, `:448`) serve a long timeline with 300-line diffs.
- Its cold mount reveals rows only after worker-rendered markdown arrives. Mounting one of its diffs blocked the renderer for 4-11 s on CI.
- The 14 regression files that use it held about half of the e2e flakes CI found.
- Prefer `openSession` or `setupTimeline` with the few messages the test needs.
- **Assert inside loops only when each step is the contract.** A web-first assertion that fails its first check retries after 100, 250, 500, then 1,000 ms. The 10-step loop at `mobile-timeline-scroll.spec.ts:688-693` takes about 8 s, mostly backoff.
- **Real-time waits cost their full length on every run and retry** (`settings-wsl.spec.ts:268-276` waits out a 10 s health check). Prefer `page.clock`:
- install it before the `goto` or `reload` whose timers you need (`timeline-stream.spec.ts:1700`);
- keep fast-forwards under the client's 45 s event-stream idle timeout (`packages/client/src/solid/connection.ts:35`).
- **Leave benchmark pacing out of regression tests.** The `sendAll` delays and `messageDelay` exist for benchmarks (`timeline.ts:306`, `mock-server.ts:82`). Hold message pages with `beforeMessagesResponse` instead.
## Wait for state, not time: races CI found
Most of these rarely reproduce on an idle local machine.
- **First mount happens in stages.** `openSession` and `expectSessionTitle` return once the composer is editable and a title is visible. Later the loading header's `<h1>` is replaced, and a cold timeline keeps its rows hidden while it scrolls itself to the bottom. Before you measure or hover in the session view, wait for something that only the final mount renders, such as the last `[data-timeline-row="UserMessage"]` or the row you click next.
- **Hovering during a scroll loses the tooltip.** A tooltip closes when its trigger scrolls, and Playwright's mouse never moves again. `session-summary.spec.ts:21-26` waits for the last row before it hovers; without that wait it needed a retry in 6 of 36 Windows runs.
- **One-shot measurements can hit a detached node.** `locator.evaluate` resolves the element, then evaluates in a second round trip. If the node is replaced in between, `getBoundingClientRect` returns an all-zero rect and `boundingBox` returns `null`. The subagent title-anchor test failed with "Expected: 0" in 11 runs until it waited for a timeline-only button (`subagent-child-navigation.spec.ts:60-64`). Take reference measurements once the final structure is in place. Polled reads re-resolve and are safe.
- **`goto` returns late, so a modal may already be open.**
- `goto` waits for `load`, which can fire after the app is already interactive.
- An open dialog sets `aria-hidden` on the app root, which hides everything behind it from role locators.
- What's New opens 500 ms after the changelog response, and it raced the Settings check in 11 of 36 Windows runs. Hold the request that opens a modal until readiness is asserted, as `startUpgraded` does (`whats-new.spec.ts:227-234`).
- **`pauseAt(new Date())` right after `install()` can throw** "Cannot fast-forward to the past", because the installed clock starts slightly ahead of the runner's clock. Install at an explicit time and pause at an offset from it (`tabs.spec.ts:443-445`).
- **A shortcut that does nothing is usually a product guard, not timing.** The global handler ignores keys while `dialog.active` (`src/shell/commands/command.tsx:489`). `active` is the top dialog that has not started closing (`packages/ui/src/context/dialog.tsx:52`, `:310-311`). A dialog that has started closing does not block keys during its 100 ms exit (`dialog.tsx:87`), but any open dialog does, including one you did not expect. Check that guard before you add a wait.
- **Shortcut tests fail on local macOS; that is not a regression.**
- The Desktop Chrome profile reports a Windows UA and `navigator.platform = "Win32"`, so the app (`IS_MAC`, `command.tsx:14`) expects Ctrl. On macOS, `ControlOrMeta` sends Meta.
- Every test that opens the palette through `openCommandPalette` (`e2e/utils/command-palette.ts:50`) fails locally and passes in CI, as do `tabs.spec.ts:835` and `timeline-cache.spec.ts:163`. Verify on Linux or in CI, or press `Control` in a throwaway copy. Do not edit tests for macOS.
- A new test can pick the modifier from the page, as `session-summary.spec.ts:29-30` does.
- **Font probes mislead.** `document.fonts.check()` can stay false after the font has loaded: when a lazy `@layer` stylesheet activates late, Chromium rebuilds font faces as unloaded. The code-font test failed outright in 9 of 36 Windows runs that way. Polling a probe that lays out text can make itself true. Await `document.fonts.ready`, lay out new text, and then check once (`timeline-cache.spec.ts:281-293`).
- **Use the harness's signals.** `holdRoute(...).arrived` resolves when the request reaches the route, and `transport.send` resolves after delivery. `setupTimeline(...).waitForPart` resolves once a part renders (`timeline.ts:328`).
- **Decide which side is wrong.** Three of eight investigated e2e flakes were product bugs, each since fixed in the product:
- a stale scroll offset restored when a scroll settles (`src/session/timeline/observe-element-offset.ts`);
- a video double-click that also entered native fullscreen (`packages/gui-extensions/src/file/artifact-view.tsx:617`);
- shortcuts dropped while a dialog closed.
If a user could hit the interleaving, fix the product and keep the assertion.
## Scheduling
- **Two projects split the suite** (`playwright.config.ts:69-86`). `chromium-touch-scroll` runs only `mobile-timeline-scroll.spec.ts`, which the `touchScroll` regex (`:29`) matches, with `fullyParallel: true`.
- Projects queue in declaration order, so its 37 tests start after every `chromium` file and spread across all workers. As one serial group, the file took 3-5 minutes in CI.
- A rename that the regex misses quietly puts the file back in `chromium` as that serial group.
- `--project chromium`, UI mode and the VS Code extension's default project skip the file.
- **In `chromium`, files are the scheduling unit.** `fullyParallel` is off unless `PLAYWRIGHT_FULLY_PARALLEL=1` (`:42`), so a file's tests run in order on one worker. A long file sets a floor and leaves an idle tail. New regressions go into the area's keeper file (`e2e/AGENTS.md`), so keep each case cheap.
- **Shards split whole files by test count, not duration** (`test.yml:219-222`). The touch project queues last, so its tests always fall in shard 2. To reproduce a leg's schedule, pass the same `--shard`.
- **Worker-scoped options fork a worker.** `launchOptions`, `channel`, `headless`, `video`, `trace`, `screenshot` and `defaultBrowserType` give a file its own worker hash.
- Playwright groups a project's files by worker hash in order of first appearance, so such a file runs after every default file in its project.
- Use test-scoped options instead: `viewport`, `deviceScaleFactor`, `hasTouch`, `isMobile`, `userAgent`, `colorScheme`, `serviceWorkers`, `locale`.
- Use `launchOptions` only when a Chromium flag is the contract, with a comment (`patch-border.spec.ts:5-9`).
- **Never spread `devices[...]` into `test.use`.** iPhone entries set `defaultBrowserType: "webkit"`, which forks a worker and needs a browser that CI never installs (`test.yml:269-272`). Copy the fields you need, as `mobile-timeline-scroll.spec.ts:23-28` does.
- **Retries are not free.** CI retries twice (`playwright.config.ts:44`). Each failure restarts the worker's browser and costs 10-30 s of cleanup on Windows. The first retry then reruns with a trace and a video (`:62-65`).
- **Timeouts are not a fix.** The limits are 60 s per test and 10 s per assertion (`playwright.config.ts:38-41`). `APP_READY_TIMEOUT` (30 s, `e2e/utils/waits.ts:4`) covers only first readiness.
- When one wait is genuinely long, scope the timeout to that assertion and say what takes the time. `settings-wsl.spec.ts:268-276` does this with `{ timeout: 20_000 }` for a 10 s health check.
- `test.setTimeout` does not lengthen assertions. `timeline-history.spec.ts:73` sets 240 s without a comment and still fails at the 10 s poll at `:127`.
## Before you push
Run from `packages/app`:
- [ ] Run in built mode, as CI does: `bun run test:e2e:built -- e2e/regression/<file>.spec.ts`. Dev mode serves unbundled modules, with the API on another origin (`playwright.config.ts:19-21`).
- [ ] Use a free port when another worktree or agent may hold 3000: `PLAYWRIGHT_PORT=4310 bun run test:e2e:built -- ...`. Built runs never reuse a server, and `serve.ts` fails on a busy port. Stay below 49152 on Windows: it reserves ports from there up and hands them out for outgoing connections (`services/www/src/docs/content/cli/web.mdx:43`, `packages/client/test/fixture/service-fixture.ts:108-109`).
- [ ] To repeat without rebuilding:
- build once with `VITE_OPENCODE_TEST_FIXTURES=1 bun run build`;
- keep `bun e2e/utils/serve.ts --host 127.0.0.1 --port 4310` running;
- run `PLAYWRIGHT_BUILD=1 PLAYWRIGHT_BASE_URL=http://127.0.0.1:4310 bun run test:e2e -- ...`.
- [ ] Repeat new or changed tests at CI concurrency without retries: `--repeat-each=10 --workers=5 --retries=0 -g "<title>"`. Run the file once with `PLAYWRIGHT_FULLY_PARALLEL=1` to prove that order does not matter.
- [ ] Rehearse Windows timing by delaying assets, not only the CPU. CPU throttling at 4x and 6x did not reproduce the tooltip or title-anchor races, but delayed responses did.
- In a throwaway copy, hold the suspect lazy chunk, stylesheet or API response with `holdRoute`, and release it 0.6-1.5 s after `arrived`.
- Route worker scripts with `page.context().route`.
- A race fix must fail before the fix and pass after it (`packages/app/AGENTS.md`, Tests).
- [ ] Check the cost on a noisy machine. Other agents add load, and local A/Bs at a load average of 20-35 were inconclusive.
- Compare the medians of interleaved before/after runs at `--workers=5`, or the step durations in the report (`bun run test:e2e:report`).
- Count every `goto` and `reload` you added.
- [ ] `bun run typecheck:e2e` reports 4 existing errors: `timeline-stream.spec.ts:1822`, `:1825`, and two `e2e/performance` probes. Add none. If you changed `playwright.config.ts`, update `test-browser/playwright-config.test.ts`.
## When CI flakes
- **Find it.** e2e runs on pull requests that affect `@opencode/app` or `@opencode/storybook`, including their workspace dependencies, and on every manual dispatch (`.github/workflows/test.yml:42-54`). It never runs on dev (`:28`).
- Each OS has the legs `app-1` and `app-2` (the shards), `session-ui-components` and `app-components`.
- The required `e2e (linux)` and `e2e (windows)` checks only aggregate those legs (`:316-335`).
- A pass on retry leaves a leg green. Check each Windows shard report's Flaky list, and make sure your new tests are not on it.
- **Download:** `gh run download <run-id> -n playwright-windows-app-2-1 -D <dir>`. Artifacts are named `playwright-<os>-<leg>-<run attempt>` (`test.yml:301-314`). App e2e results are in `<dir>/app/e2e/`.
- **In CI, the failing first attempt has no trace and no video** (`playwright.config.ts:62-65`).
- `test-results/<test>-<project>/` holds `error-context.md` (the aria snapshot at the failure) and `test-failed-1.png`.
- `<test>-<project>-retry1/` holds `trace.zip` and `video.webm` whether the retry passed or failed, plus failure files only if it failed. A second retry records neither.
- **Read `error-context.md` first.** An open dialog or an element with no accessible name explains most "element(s) not found" errors.
- **Get timings from the retry trace:** `bunx playwright show-trace <dir>/app/e2e/test-results/<test>-<project>-retry1/trace.zip`. To see which side won, compare when a screencast frame changed with when the response landed.
- **Get the transient state from a failing video,** sampled frame by frame (`ffmpeg -i video.webm -vf fps=4 frame-%03d.png`). That is how the tooltip race showed the tooltip closing in the same frame the timeline rows appeared.
- In CI, retry1's video shows the failure only if the retry failed too.
- Locally, a failing test keeps its video (`retain-on-failure`), so you can record the race with `--repeat-each` and delayed assets.
- **Open the report:** `bunx playwright show-report <dir>/app/e2e/playwright-report`. It shows step durations for every attempt, including passing ones.
+117
View File
@@ -0,0 +1,117 @@
---
name: component-tests
description: Use when writing, changing, debugging, or reviewing Storybook-based Playwright component tests. That covers specs in packages/app/component-tests or packages/session-ui/component-tests, `*.fixture.tsx` files there or beside source (such as packages/gui-extensions/src/browser/panel.fixture.tsx), the stories they mount, and the shared harness in packages/storybook (playwright/config.ts, playwright/story.ts, .storybook/main.ts, preview.tsx, mocks). Also use when a component test is flaky, passed on retry, or fails with "Execution context was destroyed", "Failed to fetch dynamically imported module", or `#storybook-root` hidden. Covers mount args, source modules imported by URL, Vite dependency pre-bundling and reloads, cold vs warm Storybook, mobile drawers, geometry, and checks before pushing.
---
# Component tests
Each package suite starts one Storybook/Vite dev server, and every worker shares it (`packages/storybook/playwright/config.ts:17-24`; CI uses 2 workers, `config.ts:15`). With `fullyParallel` (`config.ts:12`), the tests of one file run on several workers in any order. There is no backend: server, SDK and sync modules are in-page mocks. Every test gets a fresh context, and `mount` is a full iframe navigation (`packages/storybook/playwright/story.ts:37`). Slow or flaky component tests in CI have come from five sources: the shared server's dependency optimizer, module resolution that depended on the install layout, a cold first story, a product race (the mobile drawer), or an action that ran before the UI reached the state it needed.
Read these first rather than repeating them:
- `packages/storybook/playwright/README.md` covers layout, run commands and "Adding a test".
- `packages/app/AGENTS.md` "Tests" decides whether a test should exist, when theme or direction cases are allowed, and that a regression test must fail before the fix.
- `packages/app/e2e/AGENTS.md` "Test Hygiene" applies here unchanged.
## Stories and `mount`
- **Location.** Put the story next to the production component under `src/` of `ui`, `session-ui`, `app` or `gui-extensions`. Storybook indexes only the `stories` globs in `packages/storybook/.storybook/main.ts:44-49`.
- **Story ID.** It is the meta `id` if one is set (`packages/session-ui/src/components/session-review.stories.tsx:25`). Otherwise it is the kebab-cased `title`, then `--`, then the kebab-cased export. Check it at `http://127.0.0.1:6006/?path=/story/<id>`. A wrong ID never renders, so `mount` waits out its full 30 s root wait (`story.ts:39`) and then fails.
- **URL args can be dropped.** `mount(id, { args, globals })` writes them into the URL (`story.ts:20-36`). Storybook drops an arg when the story declares no `args`/`argTypes` entry for its key. It also drops one whose value is not `[A-Za-z0-9 _-]*`, a number, a hex color or `rgb()`/`hsl()`, which rules out paths, URLs and file names with dots. The only trace is the browser console warning "Omitted potentially unsafe URL args.", and the test then passes on the default scenario.
- Give every arg a typed default. With `args: { split: false }` (`session-review.stories.tsx:129`), `split:false` arrives as a boolean.
- Pick punctuated values inside the story, from a `scenario`-style arg.
- **Globals** are `theme`, `direction` and `locale` (`packages/storybook/.storybook/preview.tsx:106-122`). `mount` also sets `a11y.manual` (`story.ts:29-36`); caller globals override it.
- **Portaled UI.** `mount` returns `#storybook-root`. Dialogs, menus and drawers render outside it, so locate them from `page` (`packages/app/component-tests/composer.spec.ts:101-107`).
- **Server state** comes from the `resolve.alias` list in `viteFinal` (`main.ts:72-94`), which points app server, SDK and sync modules at `packages/storybook/.storybook/mocks/app/**`. Extend a mock rather than adding a server. Restore mock state in `onCleanup` (`mockProviderAuth`, `packages/app/src/providers/connect/dialog.stories.tsx:23`) so that switching stories in the Storybook UI does not inherit it. Tests reset it on every mount.
- **Requests the mocks do not answer.** Route them with `page.route`. That includes server endpoints such as `/api/fs/read` (`packages/session-ui/component-tests/read-image.spec.ts:20`) and external URLs such as favicons (`packages/session-ui/component-tests/markdown.spec.ts:217`).
## Fixtures imported by URL
Use these when the contract is not visible in a story, such as construction counts, unmount races or cache state.
- **Fixture file.** Put a `*.fixture.tsx` file in `component-tests/` or beside the source it drives (`packages/gui-extensions/src/browser/panel.fixture.tsx`). It exports a `mountX()` that renders into a host with a `data-testid` (`packages/session-ui/component-tests/basic-tool.fixture.tsx:7-46`). Never end the name in `.spec` or `.test`.
- **Mount it in three steps.**
1. Mount a light story first, so that the app styles load.
2. Import the fixture and call it inside `page.evaluate`.
3. Locate it with `page.getByTestId` (`packages/session-ui/component-tests/basic-tool.spec.ts:30-36`).
It renders outside the preview decorators, so it must supply its own providers (`packages/app/component-tests/browser-pane-restore.spec.ts:69-83`).
- **Module URLs.** Build each one with `sourceURL(new URL("<relative path with extension>", import.meta.url))` (`story.ts:10`), written as a string literal in the spec (`browser-pane-restore.spec.ts:6-24`). Any other spelling either fails to load or loads a second module instance whose contexts the page never provides; a hand-written `/@fs//...` is the documented second-instance case (`story.ts:6-9`). The literal also matters for pre-bundling (next section).
- **Aliases.** A module imported by URL is the real file. App code that reaches the same module through a `main.ts` alias gets the mock (`browser-pane-restore.spec.ts:95-96`). Decide which of the two the contract needs.
- **Spec imports.** Import source modules into the spec with `import type` only (`browser-pane-restore.spec.ts:2-4`). A value import runs browser code in the Node runner.
- **Async order.** Let the test decide the order through deferreds the fixture exposes (`mountExtensionHost`, `packages/app/component-tests/extension-host.fixture.tsx:135`). Await the outcome they lead to (`extension-host.spec.ts:46-77`), or poll in-page state with `until` (`extension-host.fixture.tsx:124-132`). Do not copy the fixed in-page `setTimeout` waits that other cases in `extension-host.spec.ts` (`:38`, `:88-90`, `:108-119`) use to prove a negative.
## Vite pre-bundling and reloads
`viteFinal` drops `storybook:optimize-deps-plugin` (`main.ts:105-108`) and sets `optimizeDeps` itself (`main.ts:56-67`). Its `entries` are every `*.stories.tsx` and `*.worker.ts` under the four `src/` trees, every module a component spec names by a `./` or `../` string literal ending in `.ts`/`.tsx` (collected at `main.ts:15-29`), and `preview.tsx`; `include` adds the Storybook preview runtime. Vite pre-bundles their bare imports before the first page loads. A dependency the scan misses is found on first import instead. If that changes chunks already served, Vite logs `✨ optimized dependencies changed. reloading` and sends `full-reload` with path `*` to every page in every worker, and requests with a stale `?v=` hash get a 504 "Outdated Optimize Dep".
- **The bar is zero reloads.** A cold run of either suite prints neither `new dependencies optimized` nor `optimized dependencies changed`; neither did the Linux and Windows CI legs. Dropping `preview.tsx` and `include` from `main.ts` brings one reload back, so these lines are the signal to watch.
- **Keep new code reachable by the scan.** A module path built at runtime, in a template literal, or without its extension is not collected, and neither is a spec named other than `*.spec.ts`. Name stories `*.stories.tsx`: Storybook indexes other extensions, but the scan reads only that one. Name workers `*.worker.ts`, since the scan does not follow `new Worker(new URL(…))`. Add an `optimizeDeps.include` entry only for a dependency the scan cannot reach. Vite names it in `✨ new dependencies optimized: …`, and `DEBUG=vite:deps` replaces that line with scan and discovery detail.
- **Symptoms.** "page.evaluate: Execution context was destroyed", "Failed to fetch dynamically imported module …/@fs/…", or fixture state that is gone right after `mount` ("Registrations: 1" not found, an empty tab strip).
- **Only `mount()` survives a reload,** because it navigates back to the same URL. A reload loses everything set up after it: `page.evaluate` imports, mounted fixtures, state from earlier clicks, and the elements your locators pointed at. Another worker's discovery can trigger it at any moment.
- **Fix reloads in the scan, never with retries, timeouts or import order.** The import-everything-before-mount `Promise.all` in `browser-pane-restore.spec.ts:43-58` (comment at `:56`) only narrowed the window. Before the entries existed, that file's `:123` and `:150` were retried in 31 CI jobs each, and failed attempts cost about 39-47 s (Linux) and 34 s (Windows) of worker time per run.
- **Clear the cache whenever entries matter.** Vite's `getConfigHash` covers `optimizeDeps.include`, `resolve` and plugin names, but not `entries`, and a valid `_metadata.json` skips the scan. A warm cache therefore never scans a new story or fixture, so it shows neither the reloads nor the absence of reloads that CI's cold scan would. Delete `packages/storybook/node_modules/.cache` before judging.
- **Resolve through package resolution, not paths into `node_modules`.** `main.ts:69-71` dedupes `@tanstack/solid-query` instead of aliasing it into `app/node_modules`, a path that exists only under bun's isolated linker. While Windows CI installed hoisted, that alias made every app story fail there, and 23 of 30 runs hit the step's 15-minute cap. CI now runs the same `bun install --frozen-lockfile` on every OS (`.github/actions/setup-bun/action.yml:66-68`), so such an alias would pass CI and still break a hoisted local install.
## Cold vs warm, and what a mount costs
- **CI is always cold.** Each suite runs in its own leg on a fresh runner (`test.yml:228-229`), so every leg starts Storybook with no cache and runs the full scan.
- **Do not count the first test.** In one CI run of this harness, the first test per worker took 5.7-7.0 s on Linux and 14-15 s on Windows. Warm tests had a median of 1.5 s (app) and 2.0 s (session-ui) on Linux and 2.4-2.6 s on Windows. A warm `mount` (navigation plus root wait) had a median of 1.0 s (app) and 1.5 s (session-ui) on Linux and 1.7-1.9 s on Windows, which is most of a typical test. Judge cost by warm attempts.
- **Local reuse.** Playwright reuses whatever answers on the port (`config.ts:20`; default 6006, `config.ts:3`). That hides cold cost and reloads, and with several worktrees another checkout's Storybook can serve your tests its own code. Set `PLAYWRIGHT_STORYBOOK_PORT` or `PLAYWRIGHT_STORYBOOK_URL` (`config.ts:3-4`). On Windows pick a port below 49152: the dynamic range starts there, and Hyper-V and WSL reserve blocks inside it (`netsh int ipv4 show excludedportrange protocol=tcp`). Two Storybooks in one checkout share, and race on, `packages/storybook/node_modules/.cache/storybook/<version>/<hash>/sb-vite`, so a separate port is not enough: use a separate worktree.
- **Keep mounts few.** Put one scenario in each test, and resize in place with `page.setViewportSize` (`composer.spec.ts:28-29`) instead of mounting again.
- `a11y.manual` makes addon-a11y skip its axe run after each render, so changing `a11y.test` in `preview.tsx:133-135` is not enforced by these tests. Assert accessibility in the spec when it is the contract.
- CI records video only on the first retry, next to the trace; local runs keep `retain-on-failure` (`config.ts:27-30`).
## Mobile, touch and drawers
- **Touch.** Use `story.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } })` inside a `story.describe` (`packages/session-ui/component-tests/session-timeline-mobile.spec.ts:3-4`). These options are test-scoped, so the shared workers stay. Prove that emulation took effect with `matchMedia("(hover: none)")` (`composer.spec.ts:244`), and interact with `tap()` or `page.touchscreen.tap` (`session-timeline-mobile.spec.ts:41-42`).
- **No `launchOptions`.** They are worker-scoped, so the file gets its own worker hash and its own workers. App e2e had to move `packages/app/e2e/regression/mobile-timeline-scroll.spec.ts:18` into its own `fullyParallel` project (`packages/app/playwright.config.ts:69-86`) because it otherwise formed one long serial group running alone on a single worker.
- **Drawers.** Below 768 px, pickers open in a bottom drawer (`composer.spec.ts:100-107`).
- @corvu/drawer 0.2.4 lost a close requested in the first frames after opening: focus stayed trapped in an off-screen sheet and `body` kept `pointer-events: none`. Before the fix, this caused most first-attempt failures of `composer.spec.ts:5`, in 17 of 31 Linux runs.
- `patches/@corvu%2Fdrawer@0.2.4.patch` (root `package.json` `patchedDependencies`) fixes it, so tests need no wait before pressing Escape or tapping outside.
- `composer.spec.ts:375-429` guards the patch. It dismisses in-page, before and as `data-opening` appears, because Playwright input cannot target those frames. Upgrading @corvu/drawer drops the patch, so rerun those tests.
- Before measuring or screenshotting a drawer, wait until it is fully in the viewport and has no `data-transitioning` (`packages/app/e2e/regression/mobile-model-pickers.spec.ts:25-26`).
- A stuck overlay is a product bug. Fix the product and guard it in-page, as the patch did, rather than waiting it out.
## Geometry, platforms, known failures
- **Fonts.** Inter's `@font-face` has no `font-display` (`packages/app/src/index.css:13-18`), so a story can lay out with fallback metrics and then shift. Windows CI saw 6.5 px in the composer overflow measurement (`composer.spec.ts:93-95`), which now waits first (`:25-26`). Before measuring, run `await page.evaluate(() => document.fonts.ready.then(() => undefined))` (`markdown.spec.ts:247`). The `.then` keeps the `FontFaceSet` from being returned to Node.
- **Page scroll.** Outside fullscreen, the preview frame is `calc(100vh - 2rem)` to fit Storybook's 1rem padding (`preview.tsx:82-84`). With `100vh`, every such story scrolled by 32 px, and any scroll-into-view shifted boxes (`composer.spec.ts:116` saw y go from 300 to 268). Do not give a story root `100vh`. A story taller than the viewport still scrolls, so measure relative to a container captured at the same moment, or use `parameters: { layout: "fullscreen" }`.
- **Shortcuts.** Write them as `ControlOrMeta+…` (`browser-pane-restore.spec.ts:134`). Derive expected labels from `navigator.platform` (`packages/app/component-tests/session-question-dock.spec.ts:121`).
- **Known local failure.** On macOS, `browser-pane-restore.spec.ts:123` fails after `ControlOrMeta+w` (Meta+W, `:134-135`), while CI (Control+W) passes. It is not your regression.
- **`story.fail`.** It waits out the full 10 s expect timeout on every run: `packages/session-ui/component-tests/file-tool.spec.ts:49-50` took 12.6 s on Linux CI and 14.8 s on Windows CI. Fix the product instead, or make the expected failure an immediate check once the state has settled.
## Before you push
From the owning package (`packages/session-ui` or `packages/app`):
1. **Repeat** at CI's worker count. Locally retries are already 0 (`config.ts:14`). Every attempt must pass: `bun run test:components -- component-tests/<file>.spec.ts --workers=2 --repeat-each=10`.
2. **Read durations** in `bunx playwright show-report component-tests/playwright-report`. Compare warm tests with the CI medians above. Anything much slower needs a reason in the work the test does.
3. **Rehearse load.** Late font swaps and focus restored after a menu closes (`composer.spec.ts:114-115`) race the test under load. In a throwaway copy of the spec, throttle before `mount` with `const cdp = await page.context().newCDPSession(page)` and then `await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 })`. Alternatively, repeat while the other suite runs.
4. **Run each suite cold** whenever you add a story, fixture, dependency, worker or lazy import, or change `packages/storybook`. From the repo root, once per suite, as CI runs each in its own leg. Playwright pipes Storybook's output into its own (`config.ts:22-23`), and a free port makes it start a fresh server:
```sh
rm -rf packages/storybook/node_modules/.cache
PLAYWRIGHT_STORYBOOK_PORT=6216 bun run --cwd packages/app test:components -- --workers=2 2>&1 | tee /tmp/app-components.log
grep -E "new dependencies optimized|optimized dependencies changed" /tmp/app-components.log
```
The `grep` must print nothing. Count optimizer events, not durations: under load, the same config ran anywhere from 127 to 189 s.
5. **Windows.** Check platform keys and labels and font-dependent geometry. The Windows component legs are the authoritative check.
- Do not skip on Windows, and do not raise `config.ts` timeouts, retries or the `mount` wait.
- If one test does genuinely expensive work, call `story.setTimeout(...)` in that test, with a comment that names the work.
6. **Confirm CI ran the component legs.** E2E never runs on pushes to dev (`test.yml:28`), so no post-merge run catches a regression.
- The `affected` gate filters on `@opencode/app` and `@opencode/storybook` (`test.yml:52-53`). `ui`, `session-ui` and `gui-extensions` count through app's dependencies. `workflow_dispatch` forces the legs on (`test.yml:48-51`).
- `test.yml` is listed in `globalDependencies` (`turbo.json:8`), so editing it marks every package affected.
- The required `e2e (linux)` and `e2e (windows)` checks also pass when no leg was needed (`test.yml:316-335`). Look for `e2e (<os>, session-ui-components)` and `e2e (<os>, app-components)`.
- If CI skipped them, report your local cold run in the PR.
## When CI flakes
- **Download the artifact.** Run `gh run download <run-id> -n playwright-<linux|windows>-<session-ui|app>-components-<attempt> -D <dir>` (`test.yml:301-314`). Results are in `<dir>/session-ui/component-tests/` or `<dir>/app/component-tests/`. Only the first retry has a trace and, in CI, a video: `test-results/<test>-components-retry1/`.
- **Find reloads.** Storybook's output reaches the job log with a `[WebServer]` prefix, so grep the log for `optimized dependencies changed`. In the retry trace, a reload shows up as any of:
- a second `iframe.html` load and a second `[vite] connecting...`;
- the deps `?v=` hash changing between requests;
- 504 "Outdated Optimize Dep" on `deps/*.js`.
+82
View File
@@ -0,0 +1,82 @@
---
name: tui-tests
description: Use when writing, fixing, or reviewing tests that render OpenTUI (testRender, createTestRenderer, createAppFixture) in packages/tui or packages/cli. Covers frame waits (waitForFrame, waitFor, waitForVisualIdle, flush), started vs non-started renderers, injected clocks, mock keyboard and mouse input, terminal sizes, cleanup and shared paths, and the 30s budget. Also use when a TUI test fails with "Timed out waiting for frame predicate after N passes", or when a tui test file is slow. For cli subprocess and service tests, use the unit-tests skill.
---
# TUI tests
packages/tui runs about 170 test files in one `bun test` process. CI runs it next to up to two other suites on 4-vCPU runners (`bun turbo test --affected --concurrency=3` in `.github/workflows/test.yml`), where it has taken 136-146s on Linux and 147-171s on Windows, most of it idle on frame pacing, production timers and sleeps. Most flakes come from waiting on the wrong signal and then running out of frames on a busy runner.
Read the root `AGENTS.md` Testing section (no `globalThis` mocks, run from the package directory) and its TUI Stories section. To drive the real TUI, use the `opencode-dev` skill. For CLI subprocesses, service deadlines, Effect `TestClock` and turbo test tasks, use the `unit-tests` skill.
## Frame budgets are not time
- `waitForFrame`, `waitFor` and `flush` give up after `maxPasses` (default 20). `waitForVisualIdle` gives up after `maxFrames` (default 20). One pass is one rendered frame (`DEFAULT_MAX_PASSES` in `@opentui/core/testing`). "Timed out waiting for frame predicate after 20 passes" comes from this budget, not from bun's timeout.
- **Started renderer** (`setup.renderer.start()`, as `createAppFixture` does at `packages/tui/test/fixture/app.ts:28`): frames tick at OpenTUI's default 30 fps, so 20 passes are about 0.66s. Production renders at `targetFps: 60` (`packages/tui/src/app.tsx:241`), so test frames are twice as slow as the real app.
- **Not started** (the default for `testRender` and `createTestRenderer`): `waitFor` and `waitForFrame` fail within milliseconds when no render is scheduled, and the error shows `isRunning: false`. In the same state `flush()` and `waitForVisualIdle()` return immediately without error; they do not wait for fetches or timers. Await the signal, then `renderOnce()`.
- Wait on frames only for something a frame produces. For anything else, wait on the signal itself:
- **Focus set on a timer.** `DialogSelect` focuses its filter with `setTimeout(..., 1)` (`packages/tui/src/ui/dialog-select.tsx:702`), which takes about 15ms on Windows. `typeText` sends keys to whatever is focused, so early keys are dropped and Enter then picks the default option. Put the focus in the predicate, as both dialog waits in `packages/tui/test/command-selection.test.tsx` do (`:68-70` for the model, `:75-80` for the variant): `setup.renderer.currentFocusedRenderable instanceof InputRenderable`. Before the variant wait had it, the test flaked in 5 CI runs in 20 hours, including a dev push, and a bigger budget did not help: it still failed with `maxPasses: 150`, because the keys were lost, not late. If a wait fails with the focus in the predicate, look for a state race, not the budget.
- **Markdown and code text.** `<markdown>` (`packages/tui/src/routes/session/message-parts.tsx:182`) draws no text until the shared tree-sitter worker replies, while frames keep ticking, so a plain `waitForFrame` can spend all 20 passes on a loaded runner with the text still pending. Use `waitForHighlightedFrame(setup, predicate, options?)` from `packages/tui/test/fixture/frame.ts`. When the predicate fails, it awaits every in-flight `CodeRenderable.highlightingDone` inside the frame predicate, and awaiting there does not use up passes. It accepts any setup with `renderer` and `waitForFrame`; app-lifecycle, session-group-navigation and session-home wait on transcript text this way. If the code under test accepts a client, inject `new MockTreeSitterClient({ autoResolveTimeout: 0 })` instead (`packages/tui/test/mini/scrollback.surface.test.ts:87`).
- **Requests and other state.** Await the deferred response your fetch handler returns. With no signal to await, poll with a wall-clock deadline instead of raising `maxPasses`: the file-local `waitForFrame(setup, matches)` at `command-selection.test.tsx:117` checks `captureCharFrame()` every 10ms for up to 2s. `wait` in `packages/tui/test/cli/tui/data.test.tsx:37` and `waitForModel` in `packages/tui/test/fixture/local.tsx:109` do the same for state.
- `waitForVisualIdle` returns on the first frame with `cellsUpdated === 0` by default. A frame waiting on a highlight is also quiet, so wait for the text before you measure layout or assert on it: `session-home.test.tsx:227` waits for "History message 0001" with `waitForHighlightedFrame` after `waitForVisualIdle()` instead of reading the frame directly.
- Settle steps cost frames. Each `waitForVisualIdle({ quietFrames: 3 })` takes at least 3 frames, about 100ms at 30 fps. `session-group-navigation.test.tsx` has 14 of them. When you know what you are waiting for, wait for that frame instead.
- Do not use `maxPasses` as a clock. Several waits do, and each assumes 33ms frames:
- `app-lifecycle.test.tsx:792`: 120 passes to cover the 1s reconnect delay after `setup.events.disconnect()` at `:784`;
- `app-lifecycle.test.tsx:1721-1723`: 200 passes per retry-countdown second;
- `component/dialog-shell-output.test.tsx:144`: 100 passes for a 1s poll, plus `Bun.sleep(1100)` at `:163` and `:182`;
- `session-panel.test.tsx:590`: 120 passes in `ready()` for the initial load.
With test frame rates scaled 4x, dialog-shell-output (3 tests) and session-activity-anchor (2 tests) failed. The same budgets are why tests cannot yet run at production fps. A larger budget is fine only for a long run of frame-driven work, such as scrolling 50 rows.
## Pick the renderer mode and clock
- **Component logic:** `testRender(() => <X />, { width, height })` without `start()`. Change state, `await app.renderOnce()`, then assert on `captureCharFrame()`. One frame, deterministic.
- **Time-driven renderables:** pass `clock: new ManualClock()`, call `renderer.pause()`, then advance the clock and `renderOnce()` (`fixture()` in `packages/tui/test/component/retry-provider.test.tsx:8`). `pause()` also stops `requestLive()` (spinners, animations) from starting the frame loop.
- **Clock order:** inject a clock first (OpenTUI `ManualClock`; Effect `TestClock` for Effect code, see `unit-tests`). Use `jest.useFakeTimers()` only when nothing is injectable: it patches the global timers of a process that runs every tui file, so restore them with `jest.useRealTimers()` in `finally` (`packages/tui/test/util/delayed-presence.test.ts:24-26`).
- **Whole app:** `createAppFixture` (`packages/tui/test/fixture/app.ts`) gives a started renderer, an in-process `Bun.serve` and `kittyKeyboard: true`. Call `await setup.ready` before the first wait. Passing `config` replaces the default `{ animations: false }`, so include `animations: false` yourself. The first use in a process pays `await import("../../src/app")`: about 1s idle, 12-25s under heavy load. Use it only when the behavior spans routes or data.
- **Server behavior:** use the existing `createFetch` and `createEventStream` fixture (`packages/tui/test/fixture/tui-client.ts:15`, `:69`) rather than spawning a server. The persistent PTY, for example, is faked as `/api/experimental/persistent-pty/...` routes plus a `Bun.serve` websocket (`packages/tui/test/session-wheel-focus.test.tsx:52`); real PTY behavior is tested in `packages/server/test/persistent-pty.test.ts`. Every fixture server listens on `port: 0` (`fixture/app.ts:32`) and is reached through `server.url`; never hard-code a port. Windows hands out ephemeral ports from 49152 up, so a fixed port in that range can already be taken by another connection.
## Keyboard and mouse
- Use `setup.mockInput`: `pressKey`, `typeText`, `pressEnter`, `pressEscape`, `pressArrow`, `pasteBracketedText`.
- Create renderers with `kittyKeyboard: true`. Without it, `mockInput` silently sends something else (OpenTUI 0.5.17):
| Input | Without kitty mode | With kitty mode |
| -------------------------------------------- | ----------------------------------------- | --------------- |
| `pressKey("u", { ctrl: true, shift: true })` | `ctrl+u` | `ctrl+shift+u` |
| `pressKey("2", { ctrl: true })` | `2` | `ctrl+2` |
| `pressEnter({ shift: true })` | `return` | `shift+return` |
| `pressEscape()` then `pressKey("a")` | `meta+a` (a lone Escape is held for 20ms) | `escape`, `a` |
- A second click on the same renderable within 500ms (renderer clock) and within 1 cell becomes a word or line selection. Do not sleep past that window: `Bun.sleep(550)` at `packages/tui/test/session-activity-anchor.test.tsx:120` costs 4.4s per file. Call `setup.renderer.clearSelection()` first, which resets the click history, or click at least 2 cells away. In a `ManualClock` renderer driven by `renderOnce()`, `clock.advance(501)` also works.
## Terminal sizes
- Always pass `width` and `height`. Otherwise the renderer uses `process.stdout.columns`: your terminal locally, 80 in CI.
- Cover layout at a narrow and a wide width, for example `test.each([100, 44])` (`packages/tui/test/app-lifecycle.test.tsx:13`). After `setup.resize(w, h)`, `await setup.renderOnce()` or `flush()` before asserting. Run any real-time sequence at one width only.
- Measure work by counting, not timing: mounted rows (`packages/tui/test/session-mount-budget.test.tsx`), rendered diff lines (`packages/tui/test/cli/tui/diff-viewer.test.tsx:2198`). `performance.now()` thresholds fail on slow Windows runners.
## Timers, cleanup and shared state
- A TUI test that takes over a second is usually waiting on a production constant; make it injectable instead of waiting it out. Two such constants: the shell output poll `setTimeout(poll, more ? 0 : 1_000)` (`packages/tui/src/component/dialog-shell-output.tsx:73`; 6 tests, 18.8s, 95% idle) and `reconnectDelay = 1_000` (`packages/client/src/solid/connection.ts:33`; about 1s per reconnect test). connection.ts already takes `idleTimeout` and `flushInterval` options, so add a sibling.
- Clean up with `await using` or `finally`: destroy the renderer and stop the fixture server. Cancel timers first, or they throw "TextBuffer is destroyed" into the next test.
- Remove the tmpdir last. Destroy the renderer and await the app task first, as `createAppFixture`'s `[Symbol.asyncDispose]` does (`fixture/app.ts:63`). Removing it under a pending write logs "Failed to persist" and flock "lock is compromised".
- `TestTuiContexts` (`packages/tui/test/fixture/tui-environment.tsx:32-35`) defaults `home` and `state` to fixed `/tmp/opencode/...` paths. When the tree mounts a provider that writes under `paths.state` (`StorageProvider` in `src/context/storage.tsx:145`, `LocalProvider`, or the prompt history, frecency and stash providers), pass `paths={{ state, home }}` built from `tmpdir()` (`test/fixture/fixture.ts:8`). Process-shared paths are what keep tui from parallel workers: `--parallel=2 --no-isolate` halved local wall time (162.9s to 80.7s). Isolated mode re-imports `src/app` in each of the 18 test files that load it, at 6x the CPU.
- Bun does not cancel a timed-out test body. It keeps running and can fail the next test or rerun as "Unhandled error between tests". Triage the first failure in a file; the ones after it may be leftovers.
- Import another package's test helpers by relative path only from a package in tui's workspace dependency closure. `@opencode/tui#test` depends on `transit` in `turbo.json`, which folds tui's whole workspace dependency closure into the test hash, so `data.test.tsx:7` reaching `../../../../core/test` is covered because tui depends on `@opencode/core`. A package outside that closure is not hashed, and a change there can replay a stale pass (see `unit-tests`, Turbo test tasks).
## Timeouts and failures
- The tui and cli test scripts run `bun test --timeout 30000`; Bun's default is 5s. In tui, that budget exists for the cold `src/app` import, not for slow waits.
- A frame-budget failure is not a timeout problem. Raising the test timeout does nothing for it, and raising `maxPasses` only hides the wrong wait.
- A per-test timeout below 30s, like the 15000 at `session-group-navigation.test.tsx:249`, must still cover the cold import when the file runs alone. New per-test timeouts name their work in a comment (see `unit-tests`, Know the budget).
- A frame-budget failure that reproduces on every run of one branch is a regression in that change, not a flake. dialog-shell-output failed "after 100 passes" in 21 of 29 tui runs on one PR stack and in 0 of about 102 elsewhere. Do not answer it with a bigger budget.
- Do not add `skipIf(process.platform === "win32")` to hide a timing flake; fix the wait. Windows timers have about 15ms resolution, so a 1ms `setTimeout` race that never shows on macOS fails there.
## Before you push
- From `packages/tui`: `bun test --timeout 30000 test/<file>`. This matches CI's budget and prints per-test milliseconds, which the package script's `--only-failures` hides.
- `bun test --timeout 30000 test/<file> --rerun-each 10`: all 10 must pass. The first iteration pays the cold import, so a timeout on iteration 1 under heavy load is that import, not your wait. Repeat while one other suite runs (for example `bun run test` in `packages/core`), not on an overloaded machine. Before its focus wait, the command-selection race failed 5 of 8 local runs under load.
- Force the race you suspect: temporarily slow the timer or reply (for example the focus `setTimeout` to 150ms). The test must still pass. Revert afterwards.
- Negative control: make the predicate impossible. The test must fail fast with a frame dump, not hang until the timeout.
- Windows-sensitive behavior to check for: timers under 16ms, renaming a file another process holds, process kill, and paths shown in frames. On pushes and pull requests the unit job runs `--affected`, so `@opencode/tui:test` is scheduled only when tui, a workspace package it depends on, or a `globalDependencies` file in `turbo.json` changed. In the `unit (windows)` log, confirm the lines prefixed `@opencode/tui:test:` are there with `cache miss, executing` and a pass, and compare its `Ran N tests across M files. [Xs]` line with a recent run that included tui. Per-file timing is only available locally.
+140
View File
@@ -0,0 +1,140 @@
---
name: unit-tests
description: Use when writing, reviewing, speeding up, or fixing a flaky `bun test` unit test in any package (core, cli, server, ai, codemode, util, client, sdk, plugin, http-recorder, merman, app src and test-browser, desktop, gui-extensions, ui, session-ui, latex, ...), except OpenTUI renderer tests (see tui-tests). Also use when a test "timed out after 5000ms" on Windows CI, fails only on Windows, when the unit job is slow, when adding cli subprocess or service tests, or when adding a package's test task to turbo.json. Covers controlling time instead of sleeping, per-test timeouts, process and git spawn cost on Windows, Windows-only failures, temp dirs and process state, leaks between files, and reading CI timeouts.
---
# Fast, Reliable Unit Tests
CI runs `bun turbo test --affected --concurrency=3` on 4-vCPU Linux and Windows runners (unit job in `.github/workflows/test.yml`), so each suite shares the CPU with two others, and Windows is the slower leg. Most slow or flaky unit tests here wait on real time, spawn too many processes, or assert wall-clock speed.
Read these first; this skill does not repeat them:
- Root `AGENTS.md`: the Testing and Style Guide sections.
- `packages/app/AGENTS.md` Tests (`packages/desktop` and `packages/gui-extensions` follow it): one owner per contract, and no production seams for tests.
- `packages/ai/AGENTS.md`: cassettes. The `effect` skill: `it.effect` and `it.live`.
Sibling skills: `tui-tests` (OpenTUI renderer tests in tui and cli), `app-e2e-tests` (Playwright in `packages/app/e2e`), `component-tests` (Storybook Playwright). This skill owns cli subprocess and service tests.
## Know the budget
- Bun's default per-test timeout is 5000ms. Check the package's `test` script:
- 30s: ai, cli, desktop, http-recorder, latex, merman, simulation, theme and tui pass `--timeout 30000`; core's `script/test.ts` passes `--timeout=30000`.
- 5s: client, httpapi-codegen and sdk pass `--timeout 5000`; app, codemode, function, gui-extensions, plugin, plugin-browser, script, server, session-ui, ui and util use the default.
- Size Windows risk by counting spawns, not by local wall time.
- npm.test.ts "installs a Git package from an npm ::path: subdirectory at a branch" takes 0.4s locally and hit 5000ms on Windows CI. Each Npm.add Git case makes about 75 git process events: 3 `clone --recurse-submodules`, which run the git-submodule shell script.
- Assume roughly 40ms per Git-for-Windows spawn (estimated from an earlier git.test run on Windows CI: ~24s for 564 spawns). Some core file groups run 5-9x slower on Windows than locally.
- Those `test.each` cases (`npm.test.ts:223`, `:251`) hit 5000ms in 13 of 45 Windows core runs; that is why core's runner now defaults to 30s (comment at `packages/core/script/test.ts:38`).
- A timeout loosens the budget only when it exceeds the package default.
- In a 5s package, work that legitimately needs longer gets a per-test timeout and a comment naming the work: `packages/server/test/fetch.test.ts:406-407` ("Real retries wait 18 \* 200 ms ...", `{ timeout: 10_000 }`). `test.each(table)(name, fn, 30_000)` takes it as the third argument. Use file-wide `setDefaultTimeout` only when every test in the file does such work.
- In core, the four file-level `setDefaultTimeout(30_000)` calls only restate the runner default, and a per-test `{ timeout: 15_000 }` (still in `tool-shell.test.ts`, `session-generate.test.ts` and others) is stricter than it. Do not add values at or below 30s there.
- Never absorb a sleep, poll or production interval with a larger timeout, `--retry`, or `skipIf(win32)`; remove the wait. Skip on Windows only when the platform lacks the capability, with a comment (`npm.test.ts:313`, symlinks).
## Control time; do not wait for it
- **Effect code.** `it.effect` from `packages/core/test/lib/effect.ts` runs on `TestClock`; `testEffect(layer)` adds your layer. server and cli import it from `../../core/test/lib/effect`; ai has `packages/ai/test/lib/effect.ts`.
- **Fork, then adjust.** Fork with `Effect.forkChild({ startImmediately: true })` (`packages/ai/test/http-timeout.test.ts:58`), or await a Deferred the code completes and then `Effect.yieldNow` (`:80-81`). Otherwise `TestClock.adjust` can run before the sleep is registered, and the join hangs until Bun's timeout.
- **Debounced streams and watchers.** `advance(condition)` and `drain` in `packages/core/test/lib/clock.ts` alternate one real 1ms macrotask with 500ms adjusts, because debounces register sleeps across fiber hops. Use `drain` (4 such steps) before a "nothing happened" assertion instead of `Bun.sleep(25)`. `advance`'s 100-step bound is right under TestClock, but a condition waiting on slow real work (a child, a large write) can run out of steps under load.
- **Real I/O between virtual steps.** `TestClock.withLive(Effect.sleep("10 millis"))`. `registered()` at `packages/cli/test/service.test.ts:740` tests the 5s registration watch with real file I/O under `it.effect`. This departs from the effect skill's "filesystem → `it.live`" on purpose: the timer is the contract.
- **Real events need `it.live`.** Under `it.effect` the clock moves only when the test adjusts it, so an Effect timeout on a path driven by real processes, sockets or file events never fires and a missing event hangs instead of failing. The AppProcess tests (`packages/core/test/process/process.test.ts:13-14`) use `it.live` because the spawner's 1-second post-exit capture deadline (`packages/util/src/cross-spawn-spawner.ts:322`) never fired under TestClock.
- **Give a racing component its own clock.** When a real-time deadline races slow setup, provide that component a `Clock` that only the test moves past the deadline. `packages/core/test/browser-idle.test.ts:24-38` wraps the live clock for `LocationActivity` (`:49-51`) and adds the TTL at `:84`, once the browser state is attached. Before, it waited out a real 2s TTL and failed on Windows CI with "RPC is unavailable: experimental.browser" when plugin activation was slow. Shortening a real TTL makes that race flakier.
- **Product Effect code must stay on the caller's clock**, which is what makes both patterns above possible. Read time through `Clock`, wait with `Effect.sleep` or `Schedule`, and run nested effects with the caller's context.
- A bare `Effect.runPromise` runs on the default real clock. McpStdio does this (`packages/core/src/mcp/stdio.ts:66`, `:82`, `:109`), so `packages/core/test/mcp.test.ts:832` waits the real 2s `CLOSE_GRACE` on every OS.
- Capture `yield* Effect.context()` and use `Effect.runPromiseWith(context)`, as `packages/cli/src/acp/agent.ts:27` does.
- **Code outside Effect** (app, desktop, ui, session-ui): `jest.useFakeTimers()` and `setSystemTime` from `bun:test`, restored in `afterEach` (`packages/desktop/src/main/extension/lifecycle.test.ts:27-32`, `packages/desktop/src/main/storage/drafts.test.ts:15-17`).
- **Advance fake timers to the next timer** (`jest.advanceTimersToNextTimer()`, `jest.runOnlyPendingTimers()`), not in small fixed steps. The 10ms-step `advance` at `lifecycle.test.ts:37` turns the 1,000-seed fuzz test (`:607`) into about 430k event-loop turns: 2.8-3.8s on Windows, 0.56s on Linux.
## Real-time waits: deadlines, not attempt counts
- Bound a real-time poll in milliseconds, generously, and return as soon as it holds: `until` at `packages/cli/test/service-lifecycle.test.ts:267` (30s), `eventually` at `packages/core/test/integration.test.ts:37` (10s).
- Attempt-count loops hide a small budget that shrinks under load. Do not copy `waitUntil` at `packages/core/test/config/reload.test.ts:371` (100 × 10ms; the skills test at `:57` timed out after 1.2s on a Linux dev push) or `packages/core/test/plugin/provider-azure.test.ts:219` (3000 × 1ms).
- Poll for every state you assert afterwards: the reload poll at `reload.test.ts:301-317` includes the skills that `:319-320` assert.
- Let the test, not a timer, release a child's next step. The login command in `integration.test.ts:230-254` prints its secret only after the test, having seen the pending status, writes a release file; it used to print after a fixed `Bun.sleep(50)`.
- Small timer gaps race too: `packages/core/test/process/process.test.ts:59-67` ordered stdout and stderr with 10ms and 20ms child timers and failed on Windows CI (`out 2` read before `err 1`); it now uses 100ms and 200ms.
## When the wait happens in another process
TestClock cannot reach a spawned server or worker. These production waits already cost real time:
- cli (about 60s of its roughly 2-minute suite): the 15s bind-retry deadline (`Date.now() + 15_000` in `packages/cli/src/server-process.ts`), the 5s registration watch (`packages/cli/src/services/service-registration.ts:63`), and fixed sleeps (`Bun.sleep(8_000)` at `service.test.ts:620`, `Bun.sleep(5_500)` at `service-lifecycle.test.ts:237`).
- core (about 8s locally): McpStdio `CLOSE_GRACE` 2s + `FORCE_KILL_AFTER` 2s (`stdio.ts:10-13`), Shell `forceKillAfter` 3s (`packages/core/src/shell.ts:306`, `:401`), and the 1s capture deadline in cross-spawn-spawner.
To avoid adding more:
- Test the timing logic in-process under TestClock (the `registered()` tests at `service.test.ts:270-299`). Keep real processes for exit codes, signals, stdio and port binding, with one test per escalation path. Do not add tests that wait out these constants.
- Shorten a production duration through an option, not by waiting it out. Precedent: real product options (`Flock.Options` in `packages/util/src/flock.ts:41-47`, `idleTimeout`/`flushInterval` in `packages/client/src/solid/connection.ts`) and client's hidden seam `withEnsureTiming` (`packages/client/src/service-timing.ts:31`, used by `packages/client/test/fixture/service-timing.ts`).
- For a spawned process the value must reach the child, as `timeoutMs` does through the worker payload at `packages/core/test/util/flock.test.ts:50-58`.
- server-process.ts has no override today, so its 15s tests cannot be shortened from the test side.
- app, desktop and gui-extensions forbid such seams (their AGENTS.md Tests sections); core, cli, util, client and tui have no such ban.
- Retry timing belongs in core under TestClock. `packages/server/test/fetch.test.ts:363-408` spends about 5.8s of server's 16s in real 200ms bind retries (`packages/core/src/plugin/provider/openai.ts:21`). The fixed ports 1455/1457 are the contract there; new server tests cover routing and error mapping only. Elsewhere bind port 0 (`packages/app/src/runtime/server/global-sync/bootstrap.test.ts:81`).
## Do not assert wall-clock speed
- `expect(performance.now() - startedAt).toBeLessThan(500)` failed on Windows at 510ms (`packages/ui/src/context/marked-parser.test.ts:84`); `packages/core/test/shell-scan/adversarial.test.ts:77` has the same shape. merman's layout audit no longer asserts its elapsed time.
- Count operations, or pick an input where a regression is catastrophic and assert only the result, so it trips the test timeout: `packages/codemode/test/openapi.test.ts:638` (depth 30 is 2^30 work without memoization). A ratio of two timings still fails on a load spike; if you keep one, use a generous factor and say it is timing-sensitive.
## Spawn less
- **Process start-up.** Each `bun run src/index.ts` CLI boot costs about 1.3s of CPU (the entry loads TUI `.tsx` through the preload in `packages/cli/bunfig.toml`). Test parsing and validation in-process; keep one or two real subprocess tests per file. Each cold bun child that imports the MCP SDK cost 1-3s; the MCP lifecycle tests, which spawned several, hit 5000ms on Windows until they moved to the in-process `resourceServer()` (`packages/core/test/mcp.test.ts:90`).
- **Spawned CLIs** use `isolatedEnv(root)` from `packages/cli/test/fixture/environment.ts`: isolated HOME, XDG and database, shared transpiler cache. `packages/cli/test/upgrade.test.ts:98` and `debug-paths.test.ts:24` set a private `XDG_CACHE_HOME` without `BUN_RUNTIME_TRANSPILER_CACHE_PATH`, so every spawn transpiles again; do not copy them.
- **Git.** Before the shared fixture below, a PATH shim counted about 2,850 git spawns per core run, and git.test took about 24s on Windows CI and 7s locally.
- Create repos with `packages/core/test/fixture/git.ts`. `initGit(directory, ...initArgs)` (`:24-27`) runs one `git init` and appends the fsmonitor, gpgsign and identity settings to `.git/config` in one write; `initRepo` (`:64-67`) adds an empty root commit (2 spawns; with one `git config` per key it took 6), and `gitRemote` builds on `initGit`.
- Do not write per-file `git init` plus `git config` copies. server still has two (`packages/server/test/vcs.test.ts:215-218`, `packages/server/test/worktree.test.ts:131-133`); server already imports core fixtures such as `tmpdir`.
- Use `-c user.name=… -c user.email=…` only for commits the test makes itself (`npm.test.ts:53`). Repos where production code commits later (snapshot, worktree, vcs) need repo-local identity.
- Keep identity repo-local. The unit job's "Configure git identity" step sets a global identity, but core's `script/test.ts` and cli's `isolatedEnv` replace HOME, so it is invisible there and visible to server and tui. That HOME isolation keeps core's missing-identity coverage: do not depend on CI's identity, and do not add a global gitconfig in core.
- **Independent children** start together (`Promise.all`, `packages/ai/test/exports.test.ts:63`). `packages/app/test-browser/playwright-config.test.ts` runs sequential `Bun.spawnSync` (3.5s on Windows, 1.4s on Linux); `packages/desktop/scripts/windows-installer.test.ts` makes 6 sequential cold `pwsh` starts for ACL reads, which one `pwsh` call could batch.
- **Size contention and thresholds to the claim.** `flock.test.ts:46` starts 16 bun workers; use only as many as still exceed the 4 CI vCPUs. A hard-coded threshold forces huge fixtures: `packages/core/test/git.test.ts:354` writes 2,100 files to cross `looseObjectLimit = 2048` (`packages/core/src/git.ts:50`), 2.7s locally and slower on Windows. Make the threshold an option with the production default, cross a small value in the test, and assert the default once.
## Windows-only failures
- Renaming onto a file another process holds open fails. cli `service.test.ts:462` failed on a dev push with `FileSystem.rename (...service-local.json.<uuid>.tmp)` from the temp-then-rename at `service-registration.ts:39`. Close handles the test holds; when two product processes race, fix the product, not the test.
- SIGTERM cannot be caught: `process.kill` ends the target at once with exit code 1, so a shutdown handler runs only on POSIX. Assert per platform with `catchesSigterm`, `stopSignal` and `stoppedExitCode` (`packages/client/test/fixture/service-fixture.ts:7-11`).
- Do not prove a stopped server released its port by binding it again. Windows hands out ephemeral ports from 49152 up, and any process, including suites running alongside, may take the port for an outgoing connection; a re-bind failed there with "Failed to start server. Is port 65518 in use?". Assert that nothing accepts connections (`expectNotListening`, `service-fixture.ts:108-117`).
- `os.tmpdir()` reads `TEMP` on Windows and `TMPDIR` on POSIX; set both for a child (`packages/util/test/global.test.ts:22-24`). Compare canonical paths with `fs.realpathSync.native`, which expands 8.3 short names such as `RUNNER~1` (`:84-86`).
- Reset a test socket once the request has arrived (`data`), not on `open`. Resetting on accept races the client's write, and on Windows the lost race is a write or connect error instead of a reset: `packages/util/src/retry.test.ts:25-30` recorded 2 of its 3 expected failures there. `packages/app/src/runtime/server/global-sync/bootstrap.test.ts:83-88` still resets on `open` and failed 3 of about 19 loaded local runs with `write EPIPE`, which `transientMessages` in `packages/util/src/retry.ts` does not list.
## Temp dirs, files, process state
- core's `script/test.ts` points HOME, XDG\_\* and TMPDIR (plus USERPROFILE, TMP and TEMP on Windows) at a fresh directory per run. Per-test dirs: `tmpdir()` (`await using`), `tmpdirScoped` or `withTempDir` from `packages/core/test/fixture/tmpdir.ts`.
- Close watchers, databases and children before the dir is removed. On Windows an open handle fails removal with `EBUSY`; `remove` in `tmpdir.ts` then forces a GC and retries every 100ms, up to 30 times.
- Restore process state: env with `withEnv` (`packages/core/test/fixture/env.ts`) in Effect tests and in `afterEach` elsewhere, real timers, and `setSystemTime()`.
- `CI=true` in the unit job, and Turbo passes it through. Code that reads `CI` takes another path there, so a test of the non-CI path unsets it itself: `packages/http-recorder/test/websocket.test.ts:132` wraps its record-mode case in `withEnvironment("CI", undefined, ...)`, because in CI that case replayed and waited forever for "open".
## Keep files independent without `--isolate`
- Except app, each suite runs all its files in one process with one module registry (core: 262 files), so state leaks between files.
- Do not use `mock.module`; it leaks across files.
- It is why app's scripts pass `--isolate`: app unit went from 2.4s to 9.9s locally, and unit plus browser from 5.3s to 12-20s on CI.
- `packages/cli/test/mini-config.test.ts:25` and `packages/core/test/plugin/provider-gitlab.test.ts:74` already leak in non-isolated suites; do not copy them.
- In Effect packages, provide the dependency through a test layer. In app, desktop and gui-extensions, drive the real module and entry point, and inject only through a parameter the product already has.
- Never add `--isolate` or bare `--parallel` (which implies `--isolate`) to a test script: ai went from 7.6s to 26.3s with `--parallel=2`.
- `--parallel=N --no-isolate` keeps the shared registry and measured 0.47-0.68x serial wall time at about the same CPU in core. It also exposed load-sensitive tests (browser-idle and integration's `eventually`, both since fixed).
- Adopting it is a runner decision for maintainers once CI passes on both OSes, not a fix for one slow test.
- Runtime imports run in every file that loads the module. `packages/desktop/src/main/storage/store.ts:3` imports `electron` only for `getStore`, so `src/main/extension/storage.test.ts` and `src/main/storage/store.test.ts` download the ~100MB Electron binary on a fresh install. On a first local run, storage.test.ts took 5.3s of file time for 0.1s of test bodies. Use `import type` for types (`packages/desktop/src/main/ipc-transport.test.ts:4`).
## Turbo test tasks
- `bun turbo test` runs every workspace package that has a `test` script, through the generic `test` task in `turbo.json` (`"dependsOn": ["transit"], "outputs": []`). A package with test files but no `test` script never runs in CI: give a new suite a script, and check with `bun turbo test --dry=json`. Add an `@opencode/<pkg>#test` entry only to override the generic task (desktop disables caching). Suites CI skipped rotted: client, util, sdk, http-recorder and merman needed fixes before CI could run them.
- `transit` runs nothing and depends on `^transit`, so a test hash covers the package's whole workspace closure. The global dependencies add root `package.json` (whose `packageManager` pins Bun), `bunfig.toml`, `patches/**`, `.npmrc`, `.github/actions/setup-bun/**` and `test.yml`.
- Tests do not wait for builds: workspace packages export their sources (`"./*": "./src/*.ts"` in `packages/core/package.json`), so a test must not read a dependency's `dist`. The build job's "Build workspace libraries" step checks the library builds on Linux.
- A package that compiles `src` with tsc keeps colocated tests out of the build (`"exclude": ["src/**/*.test.ts"]` in `packages/util/tsconfig.build.json`). Otherwise `bun test` also runs the compiled copies, as Windows CI did with `packages/util/dist/retry.test.js`.
## When CI flakes
- Most suites print only failures (`--only-failures`): `(fail) <name> [5000ms]` and `^ this test timed out after 5000ms`.
- When `killed 1 dangling process` and `# Unhandled error between tests` follow (for example `NpmInstallFailedError` with `SIGTERM` from a `git clone`), the test was still doing real work, not hanging.
- The unhandled error is the abandoned Effect failing after Bun killed its child, not a second bug. Count the work (see Before you push) before choosing a fix.
- Check whether the test also fails on dev pushes: `gh run list --workflow test.yml --branch dev --event push --status failure`. In one census before core's 30s default, 4 of 25 dev pushes went red, all on Windows unit tests (3 of them Npm.add 5s timeouts).
- Read whole job logs with `gh run view --log --job <id>`; `--log-failed` omits green jobs, whose `Ran N tests across M files. [Xs]` lines you need for comparison.
- Assert a child's stderr before its exit codes. `packages/core/test/util/effect-flock.test.ts:327-328` checks codes first, so its one CI failure never showed the cause.
## Before you push
Run from the package directory with the flags from its `test` script (app needs `--conditions` and `--preload`). In core use `bun run script/test.ts <file> …`, which forwards flags, isolates HOME and applies the 30s timeout.
- [ ] `bun test <file> --rerun-each 10` passes every time. Add `--randomize` for order dependence; reproduce a failure with `--seed=<n>`.
- [ ] Per-test durations: `--reporter=junit --reporter-outfile=<abs path>` (works through `script/test.ts`). Any test over about 1s does real work you can name.
- [ ] Windows: count spawns. `GIT_TRACE=<abs file>` logs roughly one `trace: built-in:` or `trace: exec:` line per git process; a logging `git` shim first on PATH also works. At about 40ms per spawn, compare with the package timeout.
- [ ] Rerun the file while the full package suite runs in another terminal; CI runs three suites on four vCPUs.
- [ ] Grep the diff for `Bun.sleep(`, `setTimeout(`, `Date.now() +`, `performance.now()`, `Effect.runPromise(` in product code, `mock.module`, `git config`, and literal port numbers.
- [ ] After CI: with `--only-failures`, the `unit (windows)` log hides passing durations. Compare your package's `Ran N tests across M files. [Xs]` line with a recent dev run's.
- [ ] New package suite: `bun turbo test --dry=json` lists `@opencode/<pkg>#test`.
+1
View File
@@ -166,6 +166,7 @@ const table = sqliteTable("session", {
- Avoid mocks as much as possible, you shouldn't be using globalThis.\* at all unless it's the only option.
- Test actual implementation, do not duplicate logic into tests
- Tests cannot run from repo root (guard: `do-not-run-tests-from-root`); run from package directories such as `packages/core`.
- Before writing or changing tests, read the matching skill in `.opencode/skills`: `unit-tests` (bun test), `tui-tests` (OpenTUI renderer tests), `app-e2e-tests` (Playwright in `packages/app/e2e`) or `component-tests` (Storybook Playwright). They cover what has made tests slow or flaky in CI.
## Checks
+34 -33
View File
@@ -33,7 +33,7 @@
},
"packages/ai": {
"name": "@opencode/ai",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@aws-sdk/credential-providers": "3.1057.0",
"@opencode/schema": "workspace:*",
@@ -55,7 +55,7 @@
},
"packages/app": {
"name": "@opencode/app",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@corvu/drawer": "catalog:",
"@dnd-kit/abstract": "0.5.0",
@@ -112,7 +112,7 @@
},
"packages/cli": {
"name": "@opencode/cli",
"version": "2.0.30",
"version": "2.0.31",
"bin": {
"opencode": "./bin/opencode.cjs",
"opencode2": "./bin/opencode2.cjs",
@@ -180,7 +180,7 @@
},
"packages/client": {
"name": "@opencode/client",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/protocol": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -205,7 +205,7 @@
},
"packages/codemode": {
"name": "@opencode/codemode",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"acorn": "8.15.0",
"effect": "catalog:",
@@ -218,7 +218,7 @@
},
"packages/console/app": {
"name": "@opencode/console-app",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@cloudflare/vite-plugin": "1.15.2",
"@ibm/plex": "6.4.1",
@@ -246,7 +246,7 @@
},
"packages/console/function": {
"name": "@opencode/console-function",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/console-resource": "workspace:*",
},
@@ -273,7 +273,7 @@
},
"packages/core": {
"name": "@opencode/core",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@ai-sdk/cohere": "3.0.27",
"@ai-sdk/perplexity": "3.0.26",
@@ -339,7 +339,7 @@
},
"packages/desktop": {
"name": "@opencode/desktop",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@zip.js/zip.js": "2.7.62",
"electron-context-menu": "5.0.0",
@@ -385,7 +385,7 @@
},
"packages/function": {
"name": "@opencode/function",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@octokit/auth-app": "8.0.1",
"@octokit/rest": "catalog:",
@@ -401,7 +401,7 @@
},
"packages/gui-extensions": {
"name": "@opencode/gui-extensions",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@betteroffice/docx": "0.4.3",
"@betteroffice/fonts": "0.4.0",
@@ -450,7 +450,7 @@
},
"packages/http-recorder": {
"name": "@opencode/http-recorder",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@effect/platform-node-shared": "catalog:",
},
@@ -469,7 +469,7 @@
},
"packages/httpapi-codegen": {
"name": "@opencode/httpapi-codegen",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"effect": "catalog:",
"prettier": "3.6.2",
@@ -482,7 +482,7 @@
},
"packages/latex": {
"name": "@opencode/latex",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opentui/core": "catalog:",
@@ -496,7 +496,7 @@
},
"packages/merman": {
"name": "@opencode/merman",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opentui/core": "catalog:",
@@ -511,7 +511,7 @@
},
"packages/plugin": {
"name": "@opencode/plugin",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@ai-sdk/provider": "3.0.8",
"@opencode/ai": "workspace:*",
@@ -548,7 +548,7 @@
},
"packages/plugin-browser": {
"name": "@opencode/plugin-browser",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/plugin": "workspace:*",
"@opencode/schema": "workspace:*",
@@ -563,7 +563,7 @@
},
"packages/plugins/figma": {
"name": "@opencode/plugin-figma",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"gray-matter": "4.0.3",
},
@@ -593,7 +593,7 @@
},
"packages/protocol": {
"name": "@opencode/protocol",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/schema": "workspace:*",
"effect": "catalog:",
@@ -608,7 +608,7 @@
},
"packages/schema": {
"name": "@opencode/schema",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@standard-schema/spec": "catalog:",
"effect": "catalog:",
@@ -632,7 +632,7 @@
},
"packages/sdk": {
"name": "@opencode/sdk",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/client": "workspace:*",
"@opencode/core": "workspace:*",
@@ -653,7 +653,7 @@
},
"packages/server": {
"name": "@opencode/server",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
@@ -676,7 +676,7 @@
},
"packages/session-ui": {
"name": "@opencode/session-ui",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@kobalte/core": "catalog:",
"@opencode/client": "workspace:*",
@@ -711,7 +711,7 @@
},
"packages/simulation": {
"name": "@opencode/simulation",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/ai": "workspace:*",
"@opencode/core": "workspace:*",
@@ -731,7 +731,7 @@
},
"packages/stats/app": {
"name": "@opencode/stats-app",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@ibm/plex": "6.4.1",
"@kobalte/core": "catalog:",
@@ -758,7 +758,7 @@
},
"packages/stats/core": {
"name": "@opencode/stats-core",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@planetscale/database": "1.19.0",
"drizzle-orm": "catalog:",
@@ -776,7 +776,7 @@
},
"packages/stats/server": {
"name": "@opencode/stats-server",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@effect/platform-node": "catalog:",
"@opencode/stats-core": "workspace:*",
@@ -822,7 +822,7 @@
},
"packages/theme": {
"name": "@opencode/theme",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opentui/core": "catalog:",
"effect": "catalog:",
@@ -836,7 +836,7 @@
},
"packages/tui": {
"name": "@opencode/tui",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@opencode/client": "workspace:*",
"@opencode/core": "workspace:*",
@@ -870,7 +870,7 @@
},
"packages/ui": {
"name": "@opencode/ui",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@kitlangton/solid-motion": "0.2.2",
"@kobalte/core": "catalog:",
@@ -906,7 +906,7 @@
},
"packages/util": {
"name": "@opencode/util",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@effect/opentelemetry": "catalog:",
"@effect/platform-node": "catalog:",
@@ -944,7 +944,7 @@
},
"packages/web": {
"name": "@opencode/web",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"@astrojs/cloudflare": "12.6.3",
"@astrojs/markdown-remark": "6.3.1",
@@ -998,7 +998,7 @@
},
"services/update": {
"name": "@opencode/update",
"version": "2.0.30",
"version": "2.0.31",
"dependencies": {
"jose": "6.0.11",
"semver": "catalog:",
@@ -1045,6 +1045,7 @@
"solid-js@1.9.15": "patches/solid-js@1.9.15.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
"@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch",
"@dnd-kit/dom@0.5.0": "patches/@dnd-kit%2Fdom@0.5.0.patch",
"@ai-sdk/openai-compatible@2.0.41": "patches/@ai-sdk%2Fopenai-compatible@2.0.41.patch",
},
+3 -3
View File
@@ -1,7 +1,7 @@
{
"nodeModules": {
"x86_64-linux": "sha256-wmSDJ8NZOJyfSaBD8hnAAtbYrp3qnMS4eJzgFdyrhFc=",
"aarch64-linux": "sha256-6WE4BHW11/gAQ75ktPbWU2Aw7uqivueMrElDAqu7QdE=",
"aarch64-darwin": "sha256-6aAic4o1Zx6QiMk8IFU6lV7typClc3yXoWH7Qiq+hFs="
"x86_64-linux": "sha256-foIqeQoc/G6w/9bd7OqC6mIxyQlCgbkPQWl3aHtb1l8=",
"aarch64-linux": "sha256-wiiiSjLyLhn0OFnh1Ug2CdAfwtpkncaUPLUI0TIucdA=",
"aarch64-darwin": "sha256-zQ26uuI0p+2tf7KYzcKLnPF+ERTumGz4uqezO9pObNg="
}
}
+3 -2
View File
@@ -2,7 +2,7 @@
"$schema": "https://json.schemastore.org/package.json",
"name": "opencode",
"description": "AI-powered development tool",
"version": "2.0.30",
"version": "2.0.31",
"private": true,
"type": "module",
"packageManager": "bun@1.4.2",
@@ -184,6 +184,7 @@
"@ff-labs/fff-bun@0.10.5": "patches/@ff-labs%2Ffff-bun@0.10.5.patch",
"ghostty-web@github:anomalyco/ghostty-web#83c0a07": "patches/ghostty-web@0.3.0.patch",
"vite@8.2.2": "patches/vite@8.2.2.patch",
"@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch"
"@modelcontextprotocol/client@2.0.0": "patches/@modelcontextprotocol%2Fclient@2.0.0.patch",
"@corvu/drawer@0.2.4": "patches/@corvu%2Fdrawer@0.2.4.patch"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.0.30",
"version": "2.0.31",
"name": "@opencode/ai",
"type": "module",
"license": "MIT",
@@ -516,7 +516,7 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request:
)
// Bedrock-Claude shares Anthropic's 4-breakpoint cap. Spend the budget in
// tools → system → messages order to favour the highest-impact prefixes.
const breakpoints = BedrockCache.breakpoints(request.model.id)
const breakpoints = BedrockCache.breakpoints(request.model)
const toolConfig = (() => {
if (flattened.tools.length === 0) return undefined
return {
@@ -1,5 +1,5 @@
import { Schema } from "effect"
import type { CacheHint } from "../../schema/index.js"
import type { CacheHint, LLMRequest } from "../../schema/index.js"
import { newBreakpoints, ttlBucket } from "./cache.js"
// Bedrock cache markers are positional: emit a `cachePoint` block immediately
@@ -28,14 +28,17 @@ const CLAUDE_5M = [
// Callers share the four-breakpoint budget across system, messages, and tools.
export const BEDROCK_BREAKPOINT_CAP = 4
export const breakpoints = (modelID: string) => {
export const breakpoints = (model: LLMRequest["model"]) => {
// Substring matching also handles regional prefixes and model-bearing ARNs.
const short = CLAUDE_5M.some((id) => modelID.includes(id))
const short = CLAUDE_5M.some((id) => model.id.includes(id))
return {
...newBreakpoints(BEDROCK_BREAKPOINT_CAP),
// An explicit Anthropic cache format opts opaque IDs such as application inference profile ARNs in.
// Assume modern Claude releases retain caching support; older generations need an explicit exception.
// Other model families use implicit caching where available.
supported: modelID.includes("anthropic.claude-") && (short || !LEGACY_CLAUDE.some((id) => modelID.includes(id))),
supported:
model.compatibility?.cacheFormat === "anthropic" ||
(model.id.includes("anthropic.claude-") && (short || !LEGACY_CLAUDE.some((id) => model.id.includes(id)))),
ttl1h: !short,
}
}
@@ -1,6 +1,6 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { CacheHint, LLM, Message, ToolCallPart } from "../../src/index.js"
import { CacheHint, LanguageModel, LLM, Message, ToolCallPart } from "../../src/index.js"
import { AmazonBedrock } from "../../src/providers.js"
import { compileRequest } from "../../src/route/client.js"
import { it } from "../lib/effect.js"
@@ -116,4 +116,53 @@ describe("Bedrock Converse cache policy", () => {
)
}
}
const arn = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abc123"
for (const ttlSeconds of [undefined, 3600]) {
it.effect(
`emits checkpoints for an opaque ARN declaring the Anthropic cache format (TTL: ${ttlSeconds ?? "default"})`,
() =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: LanguageModel.update(bedrock.model(arn), { compatibility: { cacheFormat: "anthropic" } }),
system: [
{ type: "text", text: "Agent" },
{ type: "text", text: "Project" },
],
tools: [{ name: "lookup", description: "Lookup", inputSchema: { type: "object" } }],
prompt: "Question",
cache:
ttlSeconds === undefined ? undefined : { tools: true, system: true, messages: { tail: 1 }, ttlSeconds },
}),
)
const marker = { cachePoint: ttlSeconds === undefined ? { type: "default" } : { type: "default", ttl: "1h" } }
expect(prepared.body).toMatchObject({
modelId: arn,
toolConfig: { tools: [{ toolSpec: { name: "lookup" } }, marker] },
system: [{ text: "Agent" }, marker, { text: "Project" }, marker],
messages: [{ role: "user", content: [{ text: "Question" }, marker] }],
})
if (ttlSeconds === undefined) expect(JSON.stringify(prepared.body)).not.toContain('"ttl"')
}),
)
}
for (const id of [arn, "amazon.nova-lite-v1:0"]) {
it.effect(`ignores the Alibaba cache format for ${id}`, () =>
Effect.gen(function* () {
const prepared = yield* compileRequest(
LLM.request({
model: LanguageModel.update(bedrock.model(id), { compatibility: { cacheFormat: "alibaba" } }),
system: "System prefix",
prompt: "Question",
}),
)
expect(JSON.stringify(prepared.body)).not.toContain("cachePoint")
}),
)
}
})
+11 -12
View File
@@ -39,7 +39,7 @@ bun run test:e2e:local
bun run test:e2e:local -- --grep "settings"
```
CI builds the app once and runs the same suite against Vite preview, serving production assets from `dist`. Managed built runs never reuse an existing server, so a running dev server cannot silently replace the production build. To run this mode locally:
CI builds the app once and runs the same suite against a static Bun server (`e2e/utils/serve.ts`) that serves the production assets in `dist` with Vite preview's SPA fallback rules. Managed built runs never reuse an existing server, so a running dev server cannot silently replace the production build. To run this mode locally:
```bash
bun run test:e2e:built
@@ -64,24 +64,23 @@ Compiled CLI startup and service lifecycle coverage runs separately in CI via `p
Environment options:
- `PLAYWRIGHT_BUILD=1` (build and preview locally; always enabled when `CI` is set)
- `PLAYWRIGHT_BUILD=1` (build and serve `dist` locally; always enabled when `CI` is set)
- `PLAYWRIGHT_SERVER_HOST` / `PLAYWRIGHT_SERVER_PORT` (dev fixture API address, default: `127.0.0.1:4096`; built runs use the app's origin, matching production)
- `PLAYWRIGHT_PORT` (managed dev or preview server port, default: `3000`)
- `PLAYWRIGHT_PORT` (managed dev or static server port, default: `3000`)
- `PLAYWRIGHT_BASE_URL` (use an externally managed app instead of starting a server; otherwise defaults to `http://127.0.0.1:<PLAYWRIGHT_PORT>`)
## Deployment
The `deploy` GitHub Actions workflow uses SST to deploy the web app from these branches in `anomalyco/opencode`:
The `deploy` GitHub Actions workflow uses SST to deploy the web app to `beta.opencode.ai` on every push to the
`beta` branch in `anomalyco/opencode`. The `dev` and `production` stages do not deploy the web app.
| Branch | Site |
| ------------ | --------------------- |
| `dev` | `app.dev.opencode.ai` |
| `production` | `app.opencode.ai` |
| `beta` | `beta.opencode.ai` |
`beta` is the team's dogfooding branch: `dev` merged in by hand, plus commits pushed directly to it. Do not rebase or
force-push it. Each push also runs the `publish` workflow, which ships the same commit as the OpenCode Beta desktop app
(see `packages/desktop/README.md`).
Changes merged into `v2` reach the beta site when they are promoted to `beta`. The beta SST stage deploys
only the web app, using the same `WebApp` StaticSite definition as production. It sets the build channel
and Sentry environment to `beta` without deploying the API, console, database, or billing infrastructure.
The beta SST stage deploys only the web app, using the `WebApp` StaticSite definition in `infra/webapp.ts`. It sets
the build channel and Sentry environment to `beta` without deploying the API, console, database, or billing
infrastructure.
`VITE_OPENCODE_SERVER_MODE` controls which server the web build provides at startup:
@@ -22,6 +22,8 @@ for (const direction of ["ltr", "rtl"]) {
await expect(component.locator('[data-action="composer-alternate-delivery"]')).toHaveCount(
alternate === "none" ? 0 : 1,
)
// A late Inter swap resizes the delivery keybind and shifts the toolbar; measure after fonts settle.
await page.evaluate(() => document.fonts.ready.then(() => undefined))
for (const width of [1024, 360]) {
await page.setViewportSize({ width, height: 720 })
@@ -110,6 +112,7 @@ for (const direction of ["ltr", "rtl"]) {
await add.click()
await expect(page.getByRole("menuitem", { name: "Images and files" })).toBeVisible()
await page.keyboard.press("Escape")
await expect(add).toBeFocused()
expect(await add.boundingBox()).toEqual(fixedAdd)
}
@@ -368,3 +371,59 @@ story("keeps default thinking accessible by keyboard without composer hover", as
await expect(control).not.toBeFocused()
await expect(control).toHaveCSS("opacity", "0")
})
story.describe("mobile variant drawer", () => {
story.use({ viewport: { width: 360, height: 720 } })
// Guards patches/@corvu%2Fdrawer@0.2.4.patch. The drawer starts its opening transition two frames after it opens.
// Dismissing it before then used to slide it open anyway, and dismissing it in that frame left it closing off screen
// for good, holding focus and disabling pointer input on the page. Playwright input cannot target those frames, so
// the page dismisses it.
for (const moment of ["before", "as"] as const) {
story(`closes and restores focus when dismissed ${moment} it starts opening`, async ({ mount, page }) => {
const component = await mount("opencode-composer-flow--model-and-variant")
const variant = component.getByRole("button", { name: "Choose model variant" })
const drawer = page.getByRole("dialog", { name: "Choose model variant", exact: true })
const high = drawer.getByRole("button", { name: "high", exact: true })
// Load the lazy drawer first so the dismissal below races only the drawer's own transition.
await variant.click()
await expect(high).toBeInViewport()
const content = await drawer.elementHandle()
if (!content) throw new Error("Missing variant drawer")
await page.keyboard.press("Escape")
await expect(drawer).toBeHidden()
await expect(variant).toBeFocused()
await variant.evaluate(
(trigger: HTMLElement, race) =>
new Promise<void>((resolve) => {
const dismiss = () => {
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }))
resolve()
}
// Mutation records arrive before the browser renders the opening transition's first frame.
const observer = new MutationObserver(() => {
if (!race.content.hasAttribute("data-opening")) return
observer.disconnect()
dismiss()
})
if (race.moment === "as") observer.observe(race.content, { attributeFilter: ["data-opening"] })
trigger.click()
if (race.moment === "before") dismiss()
}),
{ content, moment },
)
await expect(drawer).toBeHidden()
await expect(variant).toBeFocused()
await expect(page.locator("body")).not.toHaveCSS("pointer-events", "none")
await variant.click()
await expect(high).toBeInViewport()
})
}
})
@@ -48,6 +48,15 @@ test("lists recent sessions before a query is entered", async ({ page }) => {
await expect(page.getByRole("heading", { name: paletteSession.title, exact: true })).toBeVisible()
})
test("reopens from its shortcut as soon as it closes", async ({ page }) => {
const { dialog, input } = await openCommandPalette(page)
await input.press("Escape")
await expect(dialog).toHaveCount(0)
// A closed dialog stops blocking shortcuts when it leaves the screen, not when it is disposed afterwards.
await page.keyboard.press("ControlOrMeta+Shift+P")
await expect(dialog.getByRole("textbox")).toBeFocused()
})
test("appends search results without resetting the selected command", async ({ page }) => {
const { dialog, input } = await openCommandPalette(page)
const files = Promise.withResolvers<void>()
@@ -890,6 +890,12 @@ test("video files over 25 MB play in the viewer, expand into the theatre overlay
await page.mouse.click(8, 8)
await expect(fullscreen).toHaveAttribute("aria-pressed", "false")
expect(await video.evaluate((element) => element.dataset.e2eProbe)).toBe("retained")
// Chromium's controls also answer a double click with native fullscreen, which covers the backdrop. Opting out with
// controlslist="nofullscreen" would end their click-to-play as well.
await video.click()
await expect.poll(() => video.evaluate((element: HTMLVideoElement) => element.currentTime)).toBeGreaterThan(0)
expect(await page.evaluate(() => document.fullscreenElement)).toBeNull()
})
test("restores review state and the side-panel tab per session", async ({ page }) => {
@@ -18,6 +18,11 @@ for (const custom of [false, true]) {
const summary = page.getByRole("dialog", { name: "Session details", exact: true })
await expect(page.locator('[data-component="composer-editor"]')).toBeEditable()
await expect(trigger).toBeEnabled()
// The trigger scrolls with the timeline under its sticky header, and Kobalte closes a tooltip whenever its
// trigger scrolls. A cold timeline keeps scrolling to its bottom until it reveals its rows, so hover after that.
await expect(
page.locator(`[data-timeline-row="UserMessage"][data-message-id="${fixture.expected.sourceMessageIDs.at(-1)}"]`),
).toBeVisible()
await trigger.hover()
const tooltip = page.getByRole("tooltip")
await expect(tooltip).toContainText("Summary")
+52 -10
View File
@@ -109,7 +109,7 @@ test("terminal stacks under review by default and spans the bottom when configur
),
]
await openSession(page, { name: "SideStack", pty: {}, vcsDiff: diffs })
const { session } = await openSession(page, { name: "SideStack", pty: {}, vcsDiff: diffs })
const toggle = page.getByRole("button", { name: "Toggle review" })
const reviewPanel = page.locator("#review-panel")
const terminalPanel = page.locator("#terminal-panel")
@@ -163,13 +163,30 @@ test("terminal stacks under review by default and spans the bottom when configur
expect(Math.abs(closing.terminalBottom - stacked.terminalBottom)).toBeLessThanOrEqual(1)
expect(closing.anchor).toBeLessThanOrEqual(8)
expect(closing.terminalGap).toBeLessThanOrEqual(1)
expect(closing.reviewOverlap).toBeLessThanOrEqual(1)
await toggle.click()
await expect(reviewPanel).toBeVisible()
await expectMarked(review)
await expectTreeSentinel(page)
// Hiding the terminal mid-motion: both surfaces fill their regions and the clipped terminal keeps its size.
// Panels restored by a reload skip their entrance animation, and must still move together when the terminal hides.
await expect
.poll(() =>
page.evaluate(
(key) => JSON.parse(localStorage.getItem("opencode.window.browser.dat:tabs.panes") ?? "{}")[key],
tabKey(session.id),
),
)
.toMatchObject({ review: true, terminal: true })
await page.reload()
await expect(reviewPanel).toBeVisible()
await expect(terminal).toBeVisible()
await expectTreeSentinel(page)
await mark(terminal)
// Hiding the terminal mid-motion: both surfaces fill their regions, the review never runs under the gap, and the
// clipped terminal keeps its size.
const open = await stackGeometry(page)
await holdTransitions(page)
await page.keyboard.press("Control+Backquote")
@@ -180,6 +197,7 @@ test("terminal stacks under review by default and spans the bottom when configur
expect(hiding.terminalRegion).toBeLessThan(open.terminalRegion - 1)
expect(hiding.terminalRegion).toBeGreaterThan(1)
expect(hiding.reviewGap).toBeLessThanOrEqual(1)
expect(hiding.reviewOverlap).toBeLessThanOrEqual(1)
expect(hiding.terminalGap).toBeLessThanOrEqual(1)
expect(Math.abs(hiding.content.width - open.content.width)).toBeLessThanOrEqual(1)
expect(Math.abs(hiding.content.height - open.content.height)).toBeLessThanOrEqual(1)
@@ -293,6 +311,23 @@ for (const direction of ["ltr", "rtl"] as const) {
return actions.y + actions.height / 2 - (button.y + button.height / 2)
})
.toBe(0)
// Toggling the terminal under the review leaves the review header and the toggle in place.
const header = async () => {
const box = await page.locator('[data-slot="session-side-panel-actions"]').boundingBox()
return box && { y: box.y, height: box.height }
}
const stacked = await header()
for (const visible of [false, true]) {
await page.keyboard.press("Control+Backquote")
await expect(terminal).toBeVisible({ visible })
await expect.poll(header).toEqual(stacked)
await expect.poll(() => toggle.boundingBox()).toEqual(position)
}
await toggle.press("Enter")
await expect(toggle).toHaveAttribute("aria-expanded", "false")
await expect(toggle).toBeFocused()
@@ -321,6 +356,7 @@ async function expectTreeSentinel(page: Page) {
// Pauses each CSS transition as it starts, so a real toggle can be measured mid-motion.
function holdTransitions(page: Page) {
return page.evaluate(() => {
// SAFETY: only these two helpers write this optional global, in the declared shape.
const host = window as Window & { e2eHold?: { active: boolean } }
if (!host.e2eHold) {
@@ -341,7 +377,9 @@ function holdTransitions(page: Page) {
function releaseTransitions(page: Page) {
return page.evaluate(() => {
;(window as Window & { e2eHold?: { active: boolean } }).e2eHold!.active = false
// SAFETY: `holdTransitions` installed this global, in this shape, before any release.
const host = window as Window & { e2eHold?: { active: boolean } }
host.e2eHold!.active = false
document
.getAnimations()
.filter((item) => item instanceof CSSTransition && item.playState === "paused")
@@ -359,7 +397,7 @@ async function stackGeometry(page: Page, progress?: number) {
(item) =>
item instanceof CSSTransition && item.playState === "paused" && item.transitionProperty === "height",
)
.map((item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot")),
.map((item) => (item.effect instanceof KeyframeEffect ? item.effect.target?.getAttribute("data-slot") : null)),
)
if (progress !== undefined) {
@@ -371,9 +409,10 @@ async function stackGeometry(page: Page, progress?: number) {
.getAnimations()
.filter((item): item is CSSTransition => item instanceof CSSTransition && item.playState === "paused")
const region = transitions.find(
(item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot") === "session-side-region",
)
const slot = (item: CSSTransition) =>
item.effect instanceof KeyframeEffect ? item.effect.target?.getAttribute("data-slot") : null
const region = transitions.find((item) => slot(item) === "session-side-region")
if (progress !== undefined) {
const time = Number(region!.effect!.getTiming().duration) * progress
@@ -382,17 +421,20 @@ async function stackGeometry(page: Page, progress?: number) {
const box = (selector: string) => document.querySelector(selector)?.getBoundingClientRect()
const reviewRegion = box('[data-slot="session-side-region"]')!
const gap = box('[data-slot="session-side-panel-gap"]')!
const terminalRegion = box('[data-slot="session-side-terminal-region"]')!
const review = box("#review-panel")
const terminal = box("#terminal-panel")!
const content = box('[data-slot="terminal-panel-content"]')!
return {
moving: transitions.map((item) => ((item.effect as KeyframeEffect).target as Element).getAttribute("data-slot")),
moving: transitions.map(slot),
terminalRegion: terminalRegion.height,
terminalBottom: terminal.bottom,
anchor: Math.abs(terminal.top - content.top),
reviewGap: review ? Math.abs(reviewRegion.height - review.height) : 0,
// The gap paints over the review region, so any overlap hides the review's bottom corners.
reviewOverlap: reviewRegion.bottom - gap.top,
terminalGap: Math.abs(terminalRegion.height - terminal.height),
content: { width: content.width, height: content.height },
}
@@ -413,8 +455,8 @@ async function expectTerminalControlsAligned(terminal: Locator, toggle: Locator)
.poll(async () => {
const centers = await Promise.all(
[terminal.getByRole("button", { name: "New terminal", exact: true }), toggle].map((button) =>
button.locator("svg").evaluate((element) => {
const svg = element as SVGSVGElement
button.locator("svg").evaluate((svg) => {
if (!(svg instanceof SVGGraphicsElement)) return Number.NaN
const path = svg.getBBox()
return new DOMPoint(path.x + path.width / 2, path.y + path.height / 2).matrixTransform(svg.getScreenCTM()!)
@@ -57,9 +57,13 @@ test("keeps the parent title anchored when opening a subagent", async ({ page })
await page.evaluate((direction) => (document.documentElement.dir = direction), direction)
await expectSessionTitle(page, parentTitle)
// The title first renders in the loading header, which the timeline replaces once messages arrive.
// Measuring before then can read the detached heading, whose empty bounds put the start at 0.
const agents = page.getByRole("button", { name: "Used 1 Agent", exact: true })
await expect(agents).toBeVisible()
const start = await titleInlineStart(page.locator("[data-session-title]").getByRole("heading", { name: parentTitle }))
await page.getByRole("button", { name: "Used 1 Agent", exact: true }).click()
await agents.click()
await page.locator(`a[href="${sessionHref(childID)}"]`).click()
await expectSessionTitle(page, taskDescription)
+6 -2
View File
@@ -437,8 +437,12 @@ test("tab preview opens cold, switches immediately between tabs, and closes outs
const tabC = rows.filter({ has: page.locator(`a[href="${sessionHref(c.id)}"]`) })
const preview = page.locator('[data-component="session-tab-popover"]')
await expect(rows.locator("[data-titlebar-tab-title]")).toHaveText([a.title, b.title, c.title, d.title])
await page.clock.install()
await page.clock.pauseAt(new Date())
// Until it is paused the installed clock follows real time, and it starts slightly ahead of the runner's wall clock,
// so `pauseAt(new Date())` can name an instant the page has already passed. Pause at a fixed offset from an explicit
// install time instead; the offset only has to outlast the real time between the two calls.
const start = Date.now()
await page.clock.install({ time: start })
await page.clock.pauseAt(start + 10_000)
await tabB.hover()
await page.clock.runFor(700)
await expect(preview).toHaveCount(0)
@@ -30,7 +30,7 @@ for (const width of [1440, 390]) {
const spacer = content.querySelector('[data-timeline-row="bottom-spacer"]')
;(window as Window & { __coldReveal?: Reveal }).__coldReveal = {
window.__coldReveal = {
pending: content.querySelectorAll('[data-component="markdown"]:not([data-markdown-ready])').length,
clipped: [...content.querySelectorAll<HTMLElement>("[data-timeline-key]")].flatMap((row) =>
(row.firstElementChild?.getBoundingClientRect().height ?? 0) > row.getBoundingClientRect().height + 1
@@ -55,7 +55,7 @@ for (const width of [1440, 390]) {
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "hidden")
release.resolve()
await expect(page.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible")
const reveal = await page.evaluate(() => (window as Window & { __coldReveal?: Reveal }).__coldReveal)
const reveal = await page.evaluate(() => window.__coldReveal)
expect(reveal).toMatchObject({ pending: 0, clipped: [], tables: 1, codeBlocks: 4 })
expect(Math.abs(reveal?.bottomError ?? Infinity)).toBeLessThanOrEqual(1)
// The gap above the composer is part of the tail.
@@ -274,7 +274,23 @@ test("loads the transcript code font before opening rich history", async ({ page
await page.goto(sessionHref(fixture.sourceID))
await expect(page.getByText("A transcript with no code", { exact: true })).toBeVisible()
expect((await font).ok()).toBe(true)
await expect.poll(() => page.evaluate(() => document.fonts.check('440 13px "IBM Plex Mono"'))).toBe(true)
// Chromium recreates every @font-face as "unloaded", keeping its downloaded file, whenever a lazily loaded
// stylesheet with @layer rules activates ahead of one already applied, so the preloaded face's status alone is
// not stable. Once fonts settle, the first layout of new code must take that file at once, which marks the
// current face loaded; a face that still has to fetch its file reports "loading" here instead.
expect(
await page.evaluate(async () => {
await document.fonts.ready
const code = document.body.appendChild(document.createElement("code"))
code.style.font = "440 13px var(--font-family-mono)"
code.textContent = "code"
code.getBoundingClientRect()
const loaded = document.fonts.check('440 13px "IBM Plex Mono"')
code.remove()
return loaded
}),
).toBe(true)
})
test("waits for the requested session's history before constructing its cold timeline", async ({ page }) => {
@@ -464,6 +480,13 @@ async function expectAtTail(page: Page, lastUserID: string) {
type TabPaint = { first?: { last: boolean; bottomError?: number }; settled: boolean; removed: number; stop(): void }
declare global {
interface Window {
__coldReveal?: Reveal
__tabPaint?: TabPaint
}
}
// Samples painted frames of the timeline showing `sessionID`: the first frame that shows any of its messages, and
// every node of the first settled frame (at the tail, Markdown rendered) that is later removed.
async function sampleTabPaint(page: Page, sessionID: string) {
@@ -482,7 +505,7 @@ async function sampleTabPaint(page: Page, sessionID: string) {
},
}
;(window as Window & { __tabPaint?: TabPaint }).__tabPaint = state
window.__tabPaint = state
new MutationObserver((records) => {
if (!state.settled || !running) return
records.forEach((record) =>
@@ -520,10 +543,11 @@ async function sampleTabPaint(page: Page, sessionID: string) {
)
}
const visible = [...root.querySelectorAll<HTMLElement>("[data-message-id]")]
.filter(inView)
.map((element) => element.dataset.messageId!)
.filter((id) => destination.has(id))
const visible = [...root.querySelectorAll<HTMLElement>("[data-message-id]")].flatMap((element) => {
const id = element.dataset.messageId
return id && inView(element) && destination.has(id) ? [id] : []
})
const spacer = root.querySelector('[data-timeline-row="bottom-spacer"]')?.getBoundingClientRect()
const bottomError = spacer ? spacer.bottom - view.bottom : undefined
@@ -556,20 +580,20 @@ async function sampleTabPaint(page: Page, sessionID: string) {
last: history.findLast((message) => message.type === "user")!.id,
},
)
const read = () => page.evaluate(() => (window as Window & { __tabPaint?: TabPaint }).__tabPaint!.first)
const read = () => page.evaluate(() => window.__tabPaint!.first)
return {
async firstPaint() {
await expect.poll(read).toBeDefined()
await expect
.poll(() => page.evaluate(() => (window as Window & { __tabPaint?: TabPaint }).__tabPaint!.settled))
.poll(() => page.evaluate(() => window.__tabPaint!.settled))
.toBe(true)
return (await read())!
},
stop: () =>
page.evaluate(() => {
const state = (window as Window & { __tabPaint?: TabPaint }).__tabPaint!
const state = window.__tabPaint!
state.stop()
return state.removed
+15 -4
View File
@@ -68,8 +68,7 @@ const upgraded = { storage: { "highlights.v1": { version: "1.9.1" } } }
test("What's New shows the highlights since the version seen, pages to Get started, and is seen once shown", async ({
page,
}) => {
const requests = await serveChangelog(page)
await start(page, upgraded)
const requests = await startUpgraded(page)
const dialog = page.getByRole("dialog")
const title = dialog.getByRole("heading", { level: 1 })
const next = dialog.getByRole("button", { name: "Next", exact: true })
@@ -102,8 +101,7 @@ test("What's New shows the highlights since the version seen, pages to Get start
})
test("Don't show these in the future turns release notes off and closes What's New", async ({ page }) => {
await serveChangelog(page)
await start(page, upgraded)
await startUpgraded(page)
const dialog = page.getByRole("dialog")
await expect(dialog.getByRole("heading", { level: 1 })).toHaveText("Split panes")
await dialog.getByRole("button", { name: "Don't show these in the future", exact: true }).click()
@@ -222,6 +220,19 @@ async function start(page: Page, seed: SeedInput) {
await expectAppVisible(page.getByRole("button", { name: "Settings", exact: true }))
}
/**
* Starts as a user who last saw 1.9.1 and serves the changelog only once Home renders. What's New is a modal that hides
* Home from assistive technology, so opening it first would hide the Settings button `start` waits for.
*/
async function startUpgraded(page: Page) {
const held = Promise.withResolvers<void>()
const requests = await serveChangelog(page, changelog, held.promise)
await start(page, upgraded)
held.resolve()
return requests
}
function stored(page: Page, key: string) {
return page.evaluate((name) => localStorage.getItem(name), key).then((raw) => JSON.parse(raw ?? "null"))
}
+65
View File
@@ -0,0 +1,65 @@
import { stat } from "node:fs/promises"
import path from "node:path"
import { parseArgs } from "node:util"
// Serves the e2e build with vite preview's routing rules. vite preview checks the case of every requested
// path with a synchronous directory read on case-insensitive file systems (Windows, macOS), and the
// 3000-file _assets directory makes that the bottleneck for every page load across all workers.
const options = parseArgs({ options: { host: { type: "string" }, port: { type: "string" } } }).values
const dist = path.resolve(import.meta.dirname, "../../dist")
// Sent as text like vite's index.html middleware, so a media Range request that falls back gets a plain 200.
const index = await Bun.file(path.join(dist, "index.html")).text()
Bun.serve({
hostname: options.host,
port: Number(options.port),
async fetch(request) {
const pathname = decode(new URL(request.url).pathname)
if (pathname === undefined) return new Response(null, { status: 404 })
const target = path.resolve(dist, `.${pathname}`)
// Like vite's existsSync, a name the file system rejects (too long, NUL) is treated as missing.
const stats = target.startsWith(dist + path.sep) ? await stat(target).catch(() => undefined) : undefined
if (stats?.isFile()) {
const file = Bun.file(target)
return new Response(file, {
// Bun names .aac audio/x-aac, and only keeps the type on HEAD responses when it is set explicitly.
headers: { "content-type": path.extname(target) === ".aac" ? "audio/aac" : file.type },
})
}
if (fallback(request, pathname))
return new Response(index, { headers: { "content-type": "text/html;charset=utf-8" } })
return new Response(null, { status: 404 })
},
})
function decode(pathname: string) {
try {
return decodeURIComponent(pathname)
} catch {
return undefined
}
}
// Mirrors vite's htmlFallbackMiddleware: only page loads get index.html, so a missing script or a fetch
// asking for JSON still sees a 404.
function fallback(request: Request, pathname: string) {
if (request.method !== "GET" && request.method !== "HEAD") return false
if (pathname === "/favicon.ico") return false
// vite's index.html middleware never answers a script load with the page, so a missing chunk stays a 404.
if (request.headers.get("sec-fetch-dest") === "script") return false
const accept = request.headers.get("accept")
return !accept || accept.includes("text/html") || accept.includes("*/*")
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/app",
"version": "2.0.30",
"version": "2.0.31",
"description": "",
"type": "module",
"exports": {
+20 -3
View File
@@ -10,7 +10,7 @@ if (url.protocol !== "http:") throw new Error("E2E fixtures require an http:// a
const built = !!process.env.CI || process.env.PLAYWRIGHT_BUILD === "1"
// Production connects to its own origin, so fixture URLs must match the preview server.
// Production connects to its own origin, so fixture URLs must match the static server.
if (built) {
process.env.PLAYWRIGHT_SERVER_HOST = url.hostname
process.env.PLAYWRIGHT_SERVER_PORT = url.port || "80"
@@ -21,11 +21,13 @@ const serverHost = process.env.PLAYWRIGHT_SERVER_HOST ?? "127.0.0.1"
const serverPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
const command = built
? `bun run build && bun run serve -- --host 127.0.0.1 --port ${port} --strictPort`
? `bun run build && bun e2e/utils/serve.ts --host 127.0.0.1 --port ${port}`
: `bun run dev -- --host 127.0.0.1 --port ${port} --strictPort`
const workers = Number(process.env.PLAYWRIGHT_WORKERS ?? (process.env.CI ? 5 : 0)) || undefined
const touchScroll = /mobile-timeline-scroll\.spec\.ts/
export default defineConfig({
testDir: "./e2e",
testIgnore: [
@@ -59,12 +61,27 @@ export default defineConfig({
baseURL,
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "retain-on-failure",
// CI retries failures, so the retry records the video; local runs have no retries.
video: process.env.CI ? "on-first-retry" : "retain-on-failure",
// The PWA worker precaches the whole build in every test; e2e/service-worker covers it.
serviceWorkers: "block",
},
// The touch-scroll project exists only for scheduling: in the chromium project, mobile-timeline-scroll
// is one long serial group that ends up running alone on a single worker. Projects queue in
// declaration order, so this one runs the file's tests after every chromium group, spread across all
// workers. `--project chromium`, UI mode and the VS Code extension's default first-project selection
// therefore skip the file.
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
grepInvert: touchScroll,
},
{
name: "chromium-touch-scroll",
use: { ...devices["Desktop Chrome"] },
grep: touchScroll,
fullyParallel: true,
},
],
})
+14
View File
@@ -107,6 +107,11 @@
animation: side-region-presence-out 240ms cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
/* A collapsing frame's elevation outlives its height as a flat line over the panel beside it, so it fades out. */
[data-slot="session-side-region-presence"][data-opened="false"] #review-panel {
animation: side-panel-frame-out 240ms cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
[data-slot="terminal-panel-presence"][data-opened="true"] {
animation: terminal-panel-presence-in 200ms cubic-bezier(0.22, 1, 0.36, 1);
}
@@ -137,6 +142,7 @@
[data-slot="session-side-panel-presence"],
[data-slot="session-review-content"],
[data-slot="session-side-region-presence"],
[data-slot="session-side-region-presence"] #review-panel,
[data-component="terminal-panel"] {
animation: none !important;
}
@@ -173,6 +179,7 @@
}
}
/* Like `side-panel-frame-out`, the collapsing terminal frame drops its elevation. */
@keyframes side-terminal-panel-presence-out {
from {
opacity: 1;
@@ -180,6 +187,13 @@
to {
opacity: 0.999999;
visibility: hidden;
box-shadow: none;
}
}
@keyframes side-panel-frame-out {
to {
box-shadow: none;
}
}
@@ -159,12 +159,7 @@ export function SideRegion(props: {
props.region.select(value)
}}
>
{/* Tabs and actions share the review toggle's row: the session header's 48px, or the 51px
above a side dock's divider. */}
<div
class="session-review-v2-tabs-bar sticky top-0 shrink-0 flex items-center"
style={{ "--tabs-bar-height": props.stacked ? "51px" : "48px" }}
>
<div class="session-review-v2-tabs-bar sticky top-0 shrink-0 flex items-center">
<Tabs.List
ref={(el: HTMLDivElement) => {
tabList = el
+2 -13
View File
@@ -1,4 +1,4 @@
import { createEffect, createMemo, type Accessor } from "solid-js"
import { createMemo, type Accessor } from "solid-js"
import { createStore } from "solid-js/store"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { useLayout } from "@/shell/state/layout"
@@ -74,14 +74,6 @@ export function createSessionScreenLayout(
stacked: tabsOpen() && dockSideOpen(),
}))
const [motion, setMotion] = createStore({ gap: panelLayout().stacked, closing: false })
createEffect((previous) => {
const stacked = panelLayout().stacked
if (previous !== stacked) setMotion({ gap: stacked, closing: !stacked })
return stacked
}, panelLayout().stacked)
const sideRegionOpen = createMemo(() => tabsOpen() || fileTreeOpen())
const dockRegion = createMemo(() =>
@@ -124,10 +116,7 @@ export function createSessionScreenLayout(
},
side: {
contentWidth: sideContentWidth,
gap: {
closing: () => motion.closing,
height: createMemo(() => (motion.gap ? "8px" : "0px")),
},
gap: { height: createMemo(() => (panelLayout().stacked ? "8px" : "0px")) },
layout: panelLayout,
region: {
height: createMemo(() => {
+9 -7
View File
@@ -172,6 +172,9 @@ function SessionScreenContent(props: {
if (bottomDockVisible()) setStore("bottomDockCached", true)
if (!sideVisible()) setStore("sideHeightMotion", false)
// A side panel restored without its entrance animation never fires the animationend that enables height motion.
if (sideVisible() && !sidePresence.animate()) setStore("sideHeightMotion", true)
})
createEffect(() => {
if (!isDesktop() || screen.dock.bottom()) setStore("sideDockPresent", false)
@@ -368,11 +371,10 @@ function SessionScreenContent(props: {
<>
<div class="flex-1 min-h-0 flex flex-col gap-2 px-[var(--shell-inline-inset,8px)] pb-[var(--shell-bottom-inset,8px)] pt-[var(--shell-top-inset,8px)]">
<div ref={screen.panel.ref} class="relative flex-1 min-h-0 flex flex-col md:flex-row gap-2">
{/* Keep the control outside panel animations; a side dock's 52px header includes a 1px divider. */}
{/* Keep the control outside panel animations. */}
<Show when={isDesktop() && messagesReady() && session.identity.params.id}>
<div
class="absolute end-3 top-0 z-30 flex items-center"
classList={{ "h-[51px]": sideDockVisible(), "h-12": !sideDockVisible() }}
class="absolute end-3 top-0 z-30 h-12 flex items-center"
data-slot="session-review-toggle"
onPointerDown={hideTimelineScrollbar}
onClick={hideTimelineScrollbar}
@@ -487,13 +489,13 @@ function SessionScreenContent(props: {
</Show>
</div>
<div class="absolute start-0 bottom-0 flex flex-col" style={{ width: screen.side.contentWidth() }}>
{/* The gap moves with both regions, so together they always fill the column and the review's
bottom corners are never covered. */}
<div
data-slot="session-side-panel-gap"
classList={{
"relative z-0 shrink-0 overflow-visible bg-v2-background-bg-deep transition-[height] duration-[40ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none": true,
"delay-0": !screen.side.gap.closing(),
"delay-[200ms]": screen.side.gap.closing(),
"transition-none": !regionAnimating(),
"relative z-0 shrink-0 overflow-visible bg-v2-background-bg-deep transition-[height] duration-[240ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none": true,
"transition-none": screen.size.active() || !store.sideHeightMotion || !regionAnimating(),
}}
style={{ height: screen.side.gap.height() }}
onPointerDown={() => screen.size.start()}
@@ -1,19 +1,13 @@
import { expect, test } from "bun:test"
import { type Virtualizer } from "@tanstack/solid-virtual"
import { Node, Window } from "happy-dom"
import { Virtualizer } from "@tanstack/solid-virtual"
import { observeElementOffsetReconnectAware } from "./observe-element-offset"
test("restores a view observed before its first attachment", async () => {
const targetWindow = new Window()
const frame = openFrame()
const targetWindow = frame.targetWindow
const mutations = controlledMutations(targetWindow)
const viewport = targetWindow.document.createElement("div")
const instance = {
scrollElement: viewport,
targetWindow,
scrollOffset: 240,
options: { horizontal: false, isRtl: false, isScrollingResetDelay: 0, useScrollendEvent: false },
} as unknown as Virtualizer<HTMLDivElement, HTMLDivElement>
const instance = attachedVirtualizer(viewport, { scrollOffset: 240, isScrollingResetDelay: 0 })
const connections: boolean[] = []
@@ -32,12 +26,13 @@ test("restores a view observed before its first attachment", async () => {
expect(instance.scrollOffset).toBe(0)
} finally {
cleanup()
await targetWindow.happyDOM.close()
frame.close()
}
})
test("reports a divergent native offset once and ignores equal offsets and unrelated mutations", async () => {
const targetWindow = new Window()
const frame = openFrame()
const targetWindow = frame.targetWindow
const mutations = controlledMutations(targetWindow)
const route = targetWindow.document.createElement("section")
const viewport = targetWindow.document.createElement("div")
@@ -45,17 +40,7 @@ test("reports a divergent native offset once and ignores equal offsets and unrel
route.append(viewport)
targetWindow.document.body.append(route)
const instance = {
scrollElement: viewport,
targetWindow,
scrollOffset: 79_400,
options: {
horizontal: false,
isRtl: false,
isScrollingResetDelay: 0,
useScrollendEvent: false,
},
} as unknown as Virtualizer<HTMLDivElement, HTMLDivElement>
const instance = attachedVirtualizer(viewport, { scrollOffset: 79_400, isScrollingResetDelay: 0 })
const calls: [number, boolean][] = []
@@ -80,12 +65,13 @@ test("reports a divergent native offset once and ignores equal offsets and unrel
expect(calls).toEqual([[0, false]])
} finally {
cleanup?.()
await targetWindow.happyDOM.close()
frame.close()
}
})
test("keeps checking until stale reset-delay callbacks can no longer win", async () => {
const targetWindow = new Window()
const frame = openFrame()
const targetWindow = frame.targetWindow
const mutations = controlledMutations(targetWindow)
const animation = controlledAnimationFrames(targetWindow)
const route = targetWindow.document.createElement("section")
@@ -93,17 +79,7 @@ test("keeps checking until stale reset-delay callbacks can no longer win", async
route.append(viewport)
targetWindow.document.body.append(route)
const instance = {
scrollElement: viewport,
targetWindow,
scrollOffset: 79_400,
options: {
horizontal: false,
isRtl: false,
isScrollingResetDelay: 20,
useScrollendEvent: false,
},
} as unknown as Virtualizer<HTMLDivElement, HTMLDivElement>
const instance = attachedVirtualizer(viewport, { scrollOffset: 79_400, isScrollingResetDelay: 20 })
const calls: number[] = []
@@ -127,7 +103,39 @@ test("keeps checking until stale reset-delay callbacks can no longer win", async
expect(animation.pending()).toBe(0)
} finally {
cleanup?.()
await targetWindow.happyDOM.close()
frame.close()
}
})
test("settles on the live offset after a write whose scroll event is still pending", async () => {
const route = document.createElement("section")
const viewport = document.createElement("div")
route.append(viewport)
document.body.append(route)
const instance = attachedVirtualizer(viewport, { scrollOffset: 0, isScrollingResetDelay: 10 })
const calls: [number, boolean][] = []
const cleanup = observeElementOffsetReconnectAware(instance, (offset, isScrolling) => {
calls.push([offset, isScrolling])
instance.scrollOffset = offset
})
try {
viewport.scrollTop = 100
viewport.dispatchEvent(new Event("scroll"))
// A prepend anchor write lands before the reset delay; the browser has not dispatched its scroll event.
viewport.scrollTop = 2_500
await new Promise((resolve) => setTimeout(resolve, 25))
expect(calls).toEqual([
[100, true],
[2_500, false],
])
} finally {
cleanup?.()
route.remove()
}
})
@@ -137,17 +145,7 @@ test("cleanup suppresses queued delegated callbacks, reconnect checks, and later
route.append(viewport)
document.body.append(route)
const instance = {
scrollElement: viewport,
targetWindow: window,
scrollOffset: 0,
options: {
horizontal: false,
isRtl: false,
isScrollingResetDelay: 10,
useScrollendEvent: false,
},
} as unknown as Virtualizer<HTMLDivElement, HTMLDivElement>
const instance = attachedVirtualizer(viewport, { scrollOffset: 0, isScrollingResetDelay: 10 })
const calls: [number, boolean][] = []
@@ -170,49 +168,71 @@ test("cleanup suppresses queued delegated callbacks, reconnect checks, and later
route.remove()
})
type FrameWindow = {
requestAnimationFrame(callback: () => void): unknown
performance: { now(): number }
// A real virtualizer attached to the viewport the way its mount does (scroll element plus the window that owns it),
// without starting its own rect and offset observers, so each test drives the observer under test directly.
function attachedVirtualizer(viewport: HTMLDivElement, state: { scrollOffset: number; isScrollingResetDelay: number }) {
const instance = new Virtualizer<HTMLDivElement, HTMLDivElement>({
count: 0,
getScrollElement: () => viewport,
estimateSize: () => 0,
scrollToFn: () => {},
observeElementRect: () => {},
observeElementOffset: () => {},
isScrollingResetDelay: state.isScrollingResetDelay,
})
instance.scrollElement = viewport
instance.targetWindow = viewport.ownerDocument.defaultView
instance.scrollOffset = state.scrollOffset
return instance
}
async function frames(count: number, targetWindow: FrameWindow = window) {
// A separate window whose MutationObserver and animation frames a test can replace without touching the global
// window. happy-dom loads a srcdoc frame synchronously, so its window is ready once the frame is attached.
function openFrame() {
const frame = document.createElement("iframe")
frame.srcdoc = ""
document.body.append(frame)
const targetWindow = frame.contentDocument?.defaultView
if (!targetWindow) throw new Error("Frame window did not load")
return { targetWindow, close: () => frame.remove() }
}
async function frames(count: number, targetWindow: Window = window) {
for (let index = 0; index < count; index++) {
await new Promise<void>((resolve) => targetWindow.requestAnimationFrame(() => resolve()))
}
}
function controlledMutations(targetWindow: Window) {
let emit: (record: MutationRecord) => void = () => {
function controlledMutations(targetWindow: Window & typeof globalThis) {
let flush: () => void = () => {
throw new Error("Mutation observer is not active")
}
class ControlledMutationObserver {
// Delivers each operation's records as soon as it happens instead of at the next microtask.
class ControlledMutationObserver extends targetWindow.MutationObserver {
constructor(callback: MutationCallback) {
emit = (record) => callback([record], this as unknown as MutationObserver)
}
observe() {}
disconnect() {}
takeRecords() {
return []
super(callback)
flush = () => callback(this.takeRecords(), this)
}
}
Object.defineProperty(targetWindow, "MutationObserver", { value: ControlledMutationObserver })
const record = (target: Node, addedNodes: Node[], removedNodes: Node[]) =>
({ type: "childList", target, addedNodes, removedNodes }) as unknown as MutationRecord
return {
append(parent: Node, node: Node) {
parent.appendChild(node)
emit(record(parent, [node], []))
flush()
},
remove(node: Node) {
const parent = node.parentNode
if (!parent) throw new Error("Mutation target has no parent")
parent.removeChild(node)
emit(record(parent, [], [node]))
flush()
},
}
}
@@ -6,14 +6,18 @@ export function observeElementOffsetReconnectAware<TScrollElement extends Elemen
onReconnect?: () => void,
) {
let active = true
const element = instance.scrollElement
// TanStack resets isScrolling on a timer that reports the offset of the last scroll event. A virtualizer
// write since then (prepend anchoring, size compensation) may not have dispatched its scroll event yet, and
// compensating from that stale offset would undo the write, so a settled scroll reads the live scrollTop
// (vertical only, like the reconnect check below).
const deliver = (offset: number, isScrolling: boolean) => {
if (!active) return
callback(offset, isScrolling)
callback(isScrolling || !element?.isConnected ? offset : element.scrollTop, isScrolling)
}
const cleanupOffset = observeElementOffset(instance, deliver)
const element = instance.scrollElement
const targetWindow = instance.targetWindow
const root = element?.closest("main") ?? element?.ownerDocument.body
@@ -27,7 +27,7 @@ test.each([
expect(config.webServer.url).toBe(config.use.baseURL)
expect(config.webServer.command).toBe(
built
? "bun run build && bun run serve -- --host 127.0.0.1 --port 4321 --strictPort"
? "bun run build && bun e2e/utils/serve.ts --host 127.0.0.1 --port 4321"
: "bun run dev -- --host 127.0.0.1 --port 4321 --strictPort",
)
expect(config.webServer.reuseExistingServer).toBe(!built)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/cli",
"version": "2.0.30",
"version": "2.0.31",
"type": "module",
"license": "MIT",
"bin": {
+2
View File
@@ -71,6 +71,8 @@ const processEffect = Effect.fnUntraced(function* (options: Options) {
? Service.incumbent({ ...serviceOptions, url: serviceURL(hostname, port) })
: undefined
if (findIncumbent !== undefined && (yield* findIncumbent) !== undefined) return
// Desktop can launch the service directly without injecting its saved environment.
Object.assign(process.env, config.env)
// Keep a package-manager or curl install replaceable while the service runs; Desktop updates its own copy.
if (options.mode === "service" && process.platform === "win32" && RetainedImage.installed(global.home))
yield* RetainedImage.retain(global.cache, "service")
+2 -1
View File
@@ -17,7 +17,8 @@ export function requireInteractive(message: string) {
export const openUrl = Effect.fn("cli.prompt.open-url")(function* (url: string) {
const browser = yield* Effect.promise(() => import("@opencode/util/open"))
yield* Effect.promise(() => browser.openUrl(url)).pipe(Effect.ignore)
// Best effort: headless environments may lack a browser opener, and the caller already printed the URL.
yield* Effect.tryPromise(() => browser.openUrl(url)).pipe(Effect.ignore)
})
export function handlePromptErrors<A, E, R>(effect: Effect.Effect<A, E, R>) {
@@ -0,0 +1,8 @@
import { expect, test } from "bun:test"
import { Effect, Exit } from "effect"
import { openUrl } from "../src/ui/prompt"
test("suppresses browser open failures so the printed URL stays usable", async () => {
const exit = await Effect.runPromiseExit(openUrl("not-a-browser-url"))
expect(Exit.isSuccess(exit)).toBe(true)
})
+56
View File
@@ -192,6 +192,62 @@ test("service config manages environment variables", async () => {
}
})
test("managed service loads configured environment", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-env-"))
const registration = path.join(root, "state", "opencode", ServiceConfig.filename())
await fs.mkdir(path.join(root, "config"), { recursive: true })
await fs.writeFile(
path.join(root, "config", ServiceConfig.filename()),
JSON.stringify({ env: { OPENCODE_SERVICE_ENV_TEST: "configured", OPENCODE_SERVICE_ENV_EMPTY_TEST: "" } }),
)
await fs.writeFile(
path.join(root, "config", "opencode.json"),
JSON.stringify({
mcp: {
servers: {
env: {
type: "local",
command: ["true"],
environment: {
configured: "{env:OPENCODE_SERVICE_ENV_TEST}",
empty: "{env:OPENCODE_SERVICE_ENV_EMPTY_TEST}",
inherited: "{env:OPENCODE_SERVICE_ENV_INHERITED_TEST}",
},
},
},
},
}),
)
const owner = Bun.spawn(
[process.execPath, path.join(import.meta.dir, "../src/index.ts"), "serve", "--service", "--port", "0"],
{
env: isolatedEnv(root, {
OPENCODE_SERVICE_ENV_TEST: "inherited",
OPENCODE_SERVICE_ENV_EMPTY_TEST: "inherited",
OPENCODE_SERVICE_ENV_INHERITED_TEST: "inherited",
}),
stderr: "pipe",
stdout: "ignore",
},
)
try {
const info = await waitForInfo(registration)
const url = new URL("/api/config", info.url)
url.searchParams.set("location[directory]", root)
const response = await fetch(url, { headers: { authorization: "Basic " + btoa(`opencode:${info.password}`) } })
expect(response.status).toBe(200)
expect((await response.json())[0].info.mcp.servers.env.environment).toEqual({
configured: "configured",
empty: "",
inherited: "inherited",
})
} finally {
owner.kill("SIGTERM")
await owner.exited
await fs.rm(root, { recursive: true, force: true })
}
}, 30_000)
test("service filenames share release channels and identify preview channels", () => {
expect(ServiceConfig.filename("latest")).toBe("service.json")
expect(ServiceConfig.filename("dev")).toBe("service.json")
+4 -5
View File
@@ -1,14 +1,14 @@
import { expect, test } from "bun:test"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { tmpdir } from "../../core/test/fixture/tmpdir"
import { isolatedEnv } from "./fixture/environment"
test("standalone server exits when its owner is killed", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-cli-standalone-"))
// Windows can hold the server's files briefly after it exits; the fixture retries removal on EBUSY.
await using root = await tmpdir("opencode-cli-standalone-")
const owner = Bun.spawn([process.execPath, path.join(import.meta.dir, "fixture/standalone-owner.ts")], {
cwd: path.join(import.meta.dir, ".."),
env: isolatedEnv(root, { OPENCODE_SERVER_USERNAME: "custom" }),
env: isolatedEnv(root.path, { OPENCODE_SERVER_USERNAME: "custom" }),
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
@@ -34,7 +34,6 @@ test("standalone server exits when its owner is killed", async () => {
owner.kill("SIGKILL")
await owner.exited
if (running(pid)) process.kill(pid, "SIGKILL")
await fs.rm(root, { recursive: true, force: true })
}
})
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/client",
"version": "2.0.30",
"version": "2.0.31",
"type": "module",
"license": "MIT",
"repository": {
+13 -2
View File
@@ -168,7 +168,7 @@ export type ModelMaxTokensField = "max_completion_tokens" | "max_tokens"
export type ModelCacheFormat = "anthropic" | "alibaba"
export type ModelCapabilities = { tools: boolean; input: Array<string>; output: Array<string> }
export type ModelCapabilities = { tools: boolean; input: Array<string>; output: Array<string>; temperature?: boolean }
export type MoneyUSDPerMillionTokens = number
@@ -298,7 +298,9 @@ export type McpProtocol = "legacy" | "auto" | "2026-07-28"
export type ConfigWorktree = { directory: string }
export type ConfigModelCapabilities = { tools?: boolean; input?: Array<string>; output?: Array<string> }
export type ConfigModelReasoning =
| { supported: false }
| { supported: true; toggle?: boolean; effort?: Array<string>; budget?: { min?: number; max?: number } }
export type ConfigShellOption = { path: string; name: string; acceptable: boolean }
@@ -846,6 +848,14 @@ export type VcsInfo = { provider?: string; branch: VcsBranch }
export type WebSearchProvider = { id: WebSearchID; name: string }
export type ConfigModelCapabilities = {
tools?: boolean
input?: Array<string>
output?: Array<string>
temperature?: boolean
reasoning?: ConfigModelReasoning
}
export type SessionMessageLocationSwitched = {
id: SessionMessageID
metadata?: { [x: string]: JsonValue }
@@ -2274,6 +2284,7 @@ export type ConfigEntry =
modelID?: string
family?: string
name?: string
releaseDate?: string
compatibility?: ModelCompatibility
package?: string
settings?: ConfigModelSettings
+4 -1
View File
@@ -249,7 +249,10 @@ test("session methods retain decoded Effect inputs and outputs", async () => {
const created = yield* client.session.create({
location: Location.Ref.make({ directory: AbsolutePath.make("/tmp/project") }),
})
yield* client.session.view({ sessionID: Session.ID.make("ses_test"), idle: session.data.time.idle })
yield* client.session.view({
sessionID: Session.ID.make("ses_test"),
idle: DateTime.makeUnsafe(session.data.time.idle),
})
yield* client.session.switchAgent({ sessionID: Session.ID.make("ses_test"), agent: Agent.ID.make("build") })
yield* client.session.switchModel({
sessionID: Session.ID.make("ses_test"),
@@ -1,8 +1,15 @@
import { expect } from "bun:test"
import { mkdtemp, rename, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { waitForExit } from "./service-timing"
// Windows has no catchable SIGTERM: process.kill ends the target at once with exit code 1, so the
// service's SIGTERM handler (record the signal, unregister a lingering server, exit 0) runs only on POSIX.
export const catchesSigterm = process.platform !== "win32"
export const stopSignal = catchesSigterm ? "SIGTERM" : undefined
export const stoppedExitCode = catchesSigterm ? 0 : 1
export async function serviceFixture() {
const directory = await mkdtemp(join(tmpdir(), "opencode-client-service-"))
const registration = join(directory, "service.json")
@@ -64,6 +71,12 @@ export async function serviceFixture() {
track(pid: number) {
pids.add(pid)
},
// The signal the service recorded while shutting down, if its handler ran.
signal() {
return Bun.file(registration + ".signal")
.text()
.catch(() => undefined)
},
async waitForFile(file = registration) {
for (let attempt = 0; attempt < 600; attempt++) {
if (await Bun.file(file).exists()) return
@@ -92,7 +105,13 @@ export async function serviceFixture() {
}
}
export async function expectPortAvailable(url: string) {
const server = Bun.serve({ port: Number(new URL(url).port), fetch: () => new Response() })
await server.stop(true)
// The service listens on an ephemeral port. Once it stops, any process may reuse that port for an outgoing connection
// (Windows hands them out from 49152 up, and other suites run alongside), so binding it again proves nothing. What the
// tests need is that nothing accepts connections there anymore.
export async function expectNotListening(url: string) {
const outcome = await fetch(url).then(
(response) => `listening (${response.status})`,
() => "no response",
)
expect(outcome).toBe("no response")
}
@@ -39,7 +39,6 @@ describe("public import boundaries", () => {
const effectService = await bundleInputs("@opencode/client/effect/service", "bun")
expect(within(effectService.eager, effect).length).toBeGreaterThan(0)
expect(within(effectService.eager, protocol).length).toBeGreaterThan(0)
expect(within(effectService.all, core)).toEqual([])
expect(within(effectService.all, server)).toEqual([])
})
+46 -35
View File
@@ -1,6 +1,12 @@
import { expect, test } from "bun:test"
import { Service, type EnsureReason } from "../src/promise/service"
import { expectPortAvailable, serviceFixture } from "./fixture/service-fixture"
import {
catchesSigterm,
expectNotListening,
serviceFixture,
stopSignal,
stoppedExitCode,
} from "./fixture/service-fixture"
import { accelerate } from "./fixture/service-timing"
const ensure = accelerate(Service.ensure)
@@ -213,7 +219,7 @@ test("evicts an unresponsive registered service before starting its replacement"
fixture.track(replacement.pid)
expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3)
expect(await existing.exited).toBe(0)
expect(await existing.exited).toBe(stoppedExitCode)
expect(replacement.pid).not.toBe(original.pid)
expect(endpoint.url).toBe(replacement.url)
})
@@ -231,7 +237,7 @@ test("recovers when the starting service it waits for is stopped", async () => {
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect(await starting.exited).toBe(0)
expect(await starting.exited).toBe(stoppedExitCode)
expect(replacement.pid).not.toBe(starting.pid)
expect(endpoint.url).toBe(replacement.url)
})
@@ -267,7 +273,7 @@ test("stops the registered service even when terminal handoff fails", async () =
await Service.stop({ file: registration, pty: "handoff" })
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await fixture.signal()).toBe(stopSignal)
expect(await Bun.file(registration).exists()).toBe(false)
expect((await Bun.file(registration + ".pty-handoff").json()).handoff).toBeNull()
})
@@ -280,7 +286,7 @@ test("signals the registered service process", async () => {
await Service.stop({ file: registration })
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await fixture.signal()).toBe(stopSignal)
expect(await Bun.file(registration).exists()).toBe(false)
})
@@ -293,9 +299,9 @@ test("stop escalates when the registration disappears before the process exits",
await stop({ file: registration })
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await fixture.signal()).toBe(stopSignal)
expect(() => process.kill(original.pid, 0)).toThrow()
await expectPortAvailable(original.url)
await expectNotListening(original.url)
expect(await Bun.file(registration).exists()).toBe(false)
await existing.exited
}, 15_000)
@@ -315,34 +321,39 @@ test.skipIf(process.platform === "win32")(
15_000,
)
test("stop waits for the original process while preserving a newly registered successor", async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("lingering", "15000")
await fixture.waitForFile()
const original = await Bun.file(registration).json()
// Default timing keeps the grace period open long enough for the successor to register first.
const stopping = Service.stop({ file: registration })
try {
await fixture.waitForFile(registration + ".unregistered")
const successor = fixture.spawn("graceful")
// On Windows the original process cannot outlive SIGTERM, so no successor can register before it exits.
test.skipIf(!catchesSigterm)(
"stop waits for the original process while preserving a newly registered successor",
async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("lingering", "15000")
await fixture.waitForFile()
const replacement = await Bun.file(registration).json()
expect(existing.exitCode).toBe(null)
expect(replacement.pid).toBe(successor.pid)
const original = await Bun.file(registration).json()
// Default timing keeps the grace period open long enough for the successor to register first.
const stopping = Service.stop({ file: registration })
await stopping
try {
await fixture.waitForFile(registration + ".unregistered")
const successor = fixture.spawn("graceful")
await fixture.waitForFile()
const replacement = await Bun.file(registration).json()
expect(existing.exitCode).toBe(null)
expect(replacement.pid).toBe(successor.pid)
expect(() => process.kill(original.pid, 0)).toThrow()
await expectPortAvailable(original.url)
expect(await Bun.file(registration).json()).toEqual(replacement)
expect(await fetch(new URL("/api/info", replacement.url)).then((response) => response.json())).toMatchObject({
pid: successor.pid,
})
expect(successor.exitCode).toBe(null)
} finally {
existing.kill("SIGKILL")
await stopping
}
}, 20_000)
await stopping
expect(() => process.kill(original.pid, 0)).toThrow()
await expectNotListening(original.url)
expect(await Bun.file(registration).json()).toEqual(replacement)
expect(await fetch(new URL("/api/info", replacement.url)).then((response) => response.json())).toMatchObject({
pid: successor.pid,
})
expect(successor.exitCode).toBe(null)
} finally {
existing.kill("SIGKILL")
await stopping
}
},
20_000,
)
+6 -6
View File
@@ -41,17 +41,17 @@ test("exposes every standard HTTP API group", () => {
expect(Object.keys(client.message)).toEqual(["list"])
expect(Object.keys(client.integration)).toEqual(["list", "get", "wellknown", "connect", "oauth", "command"])
expect(Object.keys(client.integration.wellknown)).toEqual(["add"])
expect(Object.keys(client.integration.connect)).toEqual(["key"])
expect(Object.keys(client.integration.connect)).toEqual(["key", "external"])
expect(Object.keys(client.integration.oauth)).toEqual(["connect", "status", "complete", "cancel"])
expect(Object.keys(client.integration.command)).toEqual(["connect", "status", "cancel"])
expect(Object.keys(client.websearch)).toEqual(["providers", "query"])
expect(Object.keys(client.file)).toEqual(["read", "list", "find"])
expect(Object.keys(client.vcs)).toEqual(["get", "base", "status", "branches", "diff"])
expect(Object.keys(client.file)).toEqual(["read", "list", "find", "write"])
expect(Object.keys(client.vcs)).toEqual(["init", "get", "base", "status", "branch", "diff"])
expect(Object.keys(client.pty)).toEqual(["list", "create", "get", "update", "remove", "connect"])
expect(Object.keys(client.pty.connect)).toEqual(["token"])
expect(Object.keys(client.experimental)).toEqual(["persistentPty"])
expect(client.experimental.persistentPty.read).toBeFunction()
expect(Object.keys(client.shell)).toEqual(["list", "create", "get", "timeout", "output", "remove"])
expect(Object.keys(client.shell)).toEqual(["list", "create", "get", "output", "remove"])
expect(Object.keys(client.project)).toEqual(["list", "update"])
expect(Object.keys(client.worktree)).toEqual(["list", "create", "remove", "refresh"])
})
@@ -971,7 +971,7 @@ test("session methods use the public HTTP contract", async () => {
const context = await client.session.context({ sessionID: "ses_test" })
const log = []
for await (const item of client.session.log({ sessionID: "ses_test", after: 0 })) log.push(item)
const interrupted = await client.session.interrupt({ sessionID: "ses_test", continue: true })
const interrupted = await client.session.interrupt({ sessionID: "ses_test", resume: true })
const message = await client.session.message.get({ sessionID: "ses_test", messageID: "msg_model" })
expect(page.cursor.next).toBe("next")
@@ -999,7 +999,7 @@ test("session methods use the public HTTP contract", async () => {
["POST", "http://localhost:3000/api/experimental/session/ses_test/wait"],
["GET", "http://localhost:3000/api/session/ses_test/context"],
["GET", "http://localhost:3000/api/experimental/session/ses_test/log?after=0"],
["POST", "http://localhost:3000/api/session/ses_test/interrupt?continue=true"],
["POST", "http://localhost:3000/api/session/ses_test/interrupt?resume=true"],
["GET", "http://localhost:3000/api/session/ses_test/message/msg_model"],
])
const viewBody = requests.find((request) => request.url.endsWith("/api/session/ses_test/view"))?.init?.body
@@ -4,7 +4,7 @@ import { Effect } from "effect"
import { Service } from "../src/effect/service"
import { ensure, stop } from "../src/promise/service"
import type { EnsureOptions, EnsureReason, StopOptions } from "../src/service"
import { serviceFixture } from "./fixture/service-fixture"
import { serviceFixture, stopSignal, stoppedExitCode } from "./fixture/service-fixture"
import { accelerate } from "./fixture/service-timing"
const effect = accelerate(Service.ensure)
@@ -71,8 +71,8 @@ for (const client of clients) {
const replacement = await Bun.file(fixture.registration).json()
fixture.track(replacement.pid)
expect(await owner.exited).toBe(0)
expect(await Bun.file(fixture.registration + ".signal").text()).toBe("SIGTERM")
expect(await owner.exited).toBe(stoppedExitCode)
expect(await fixture.signal()).toBe(stopSignal)
expect(await Bun.file(fixture.registration + ".handoff-request").exists()).toBe(true)
expect(starts).toEqual(["version-mismatch"])
expect(replacement.pid).not.toBe(owner.pid)
@@ -87,8 +87,8 @@ for (const client of clients) {
await Bun.write(fixture.registration + ".missing-health", "")
await client.stop({ file: fixture.registration })
expect(await owner.exited).toBe(0)
expect(await Bun.file(fixture.registration + ".signal").text()).toBe("SIGTERM")
expect(await owner.exited).toBe(stoppedExitCode)
expect(await fixture.signal()).toBe(stopSignal)
expect(await Bun.file(fixture.registration).exists()).toBe(false)
})
}
+45 -34
View File
@@ -3,7 +3,13 @@ import { expect, test } from "bun:test"
import { Effect, FileSystem } from "effect"
import { writeFile } from "node:fs/promises"
import { Service, type EnsureReason } from "../src/effect/service"
import { expectPortAvailable, serviceFixture } from "./fixture/service-fixture"
import {
catchesSigterm,
expectNotListening,
serviceFixture,
stopSignal,
stoppedExitCode,
} from "./fixture/service-fixture"
import { accelerate } from "./fixture/service-timing"
const ensure = accelerate(Service.ensure)
@@ -95,7 +101,7 @@ test("replaces an incompatible registered service", async () => {
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect(await existing.exited).toBe(0)
expect(await existing.exited).toBe(stoppedExitCode)
expect(replacement.version).toBe("2.1.0-next.1")
expect(endpoint.url).toBe(replacement.url)
expect(starts).toEqual(["version-mismatch"])
@@ -127,7 +133,7 @@ test("recovers when the starting service it waits for is stopped", async () => {
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect(await starting.exited).toBe(0)
expect(await starting.exited).toBe(stoppedExitCode)
expect(replacement.pid).not.toBe(starting.pid)
expect(endpoint.url).toBe(replacement.url)
})
@@ -187,7 +193,7 @@ test("evicts an unresponsive registered service before starting its replacement"
fixture.track(replacement.pid)
expect((await Bun.file(registration + ".requests").text()).trim().split("\n")).toHaveLength(3)
expect(await existing.exited).toBe(0)
expect(await existing.exited).toBe(stoppedExitCode)
expect(replacement.pid).not.toBe(original.pid)
expect(endpoint.url).toBe(replacement.url)
expect(await status(endpoint.url)).toMatchObject({ version: "test", pid: replacement.pid })
@@ -201,7 +207,7 @@ test("signals an unresponsive registered service process", async () => {
await run(Service.stop({ file: registration }))
await process.exited
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await fixture.signal()).toBe(stopSignal)
expect(await Bun.file(registration).exists()).toBe(false)
})
@@ -214,9 +220,9 @@ test("stop escalates when the registration disappears before the process exits",
await run(stop({ file: registration }))
expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM")
expect(await fixture.signal()).toBe(stopSignal)
expect(() => process.kill(original.pid, 0)).toThrow()
await expectPortAvailable(original.url)
await expectNotListening(original.url)
expect(await Bun.file(registration).exists()).toBe(false)
await existing.exited
}, 15_000)
@@ -236,35 +242,40 @@ test.skipIf(process.platform === "win32")(
15_000,
)
test("stop waits for the original process while preserving a newly registered successor", async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("lingering", "15000")
await fixture.waitForFile()
const original = await Bun.file(registration).json()
// Default timing keeps the grace period open long enough for the successor to register first.
const stopping = run(Service.stop({ file: registration }))
try {
await fixture.waitForFile(registration + ".unregistered")
const successor = fixture.spawn("graceful")
// On Windows the original process cannot outlive SIGTERM, so no successor can register before it exits.
test.skipIf(!catchesSigterm)(
"stop waits for the original process while preserving a newly registered successor",
async () => {
await using fixture = await serviceFixture()
const registration = fixture.registration
const existing = fixture.spawn("lingering", "15000")
await fixture.waitForFile()
const replacement = await Bun.file(registration).json()
expect(existing.exitCode).toBe(null)
expect(replacement.pid).toBe(successor.pid)
const original = await Bun.file(registration).json()
// Default timing keeps the grace period open long enough for the successor to register first.
const stopping = run(Service.stop({ file: registration }))
await stopping
try {
await fixture.waitForFile(registration + ".unregistered")
const successor = fixture.spawn("graceful")
await fixture.waitForFile()
const replacement = await Bun.file(registration).json()
expect(existing.exitCode).toBe(null)
expect(replacement.pid).toBe(successor.pid)
expect(() => process.kill(original.pid, 0)).toThrow()
await expectPortAvailable(original.url)
expect(await Bun.file(registration).json()).toEqual(replacement)
expect(await status(replacement.url)).toMatchObject({ pid: successor.pid })
expect(successor.exitCode).toBe(null)
} finally {
existing.kill("SIGKILL")
await stopping
}
}, 20_000)
await stopping
expect(() => process.kill(original.pid, 0)).toThrow()
await expectNotListening(original.url)
expect(await Bun.file(registration).json()).toEqual(replacement)
expect(await status(replacement.url)).toMatchObject({ pid: successor.pid })
expect(successor.exitCode).toBe(null)
} finally {
existing.kill("SIGKILL")
await stopping
}
},
20_000,
)
test("signals an incompatible service before starting its replacement", async () => {
await using fixture = await serviceFixture()
@@ -281,7 +292,7 @@ test("signals an incompatible service before starting its replacement", async ()
const replacement = await Bun.file(registration).json()
fixture.track(replacement.pid)
expect(await existing.exited).toBe(0)
expect(await existing.exited).toBe(stoppedExitCode)
expect(endpoint.url).toBe(replacement.url)
})
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json.schemastore.org/package.json",
"name": "@opencode/codemode",
"version": "2.0.30",
"version": "2.0.31",
"description": "Effect-native confined code execution over schema-described tools",
"type": "module",
"license": "MIT",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/console-app",
"version": "2.0.30",
"version": "2.0.31",
"type": "module",
"license": "MIT",
"scripts": {
@@ -9,7 +9,8 @@
"dev:enterprise": "bun --watch script/dev-enterprise.ts",
"dev:remote": "bun sst shell --stage=dev bun dev",
"build": "bun ./script/generate-sitemap.ts && vite build && bun ../../schema/script/config-schema.ts ./.output/public/config.json",
"start": "vite start"
"start": "vite start",
"test": "bun test --only-failures"
},
"dependencies": {
"@cloudflare/vite-plugin": "1.15.2",
@@ -3,7 +3,6 @@ export const goModels = [
{ id: "kimi-k3", name: "Kimi K3", requests: 110, allowance: 15, featured: true },
{ id: "qwen3.8-max", name: "Qwen3.8 Max", requests: 160, allowance: 15 },
{ id: "grok-4.7", name: "Grok 4.7", requests: 169, allowance: 15 },
{ id: "grok-4.6", name: "Grok 4.6", requests: 169, allowance: 15 },
{ id: "glm-5.3", name: "GLM-5.3", requests: 220, allowance: 15 },
{
id: "gemini-4-argon-contributor",
@@ -24,7 +23,6 @@ export const goModels = [
{ id: "minimax-m3", name: "MiniMax M3", requests: 3200, allowance: 60, featured: true },
{ id: "mimo-v2.6-pro", name: "MiMo-V2.6-Pro", requests: 3250, allowance: 15 },
{ id: "mimo-v2.5-pro", name: "MiMo-V2.5-Pro", requests: 3250, allowance: 15 },
{ id: "minimax-m2.7", name: "MiniMax M2.7", requests: 3400, allowance: 60 },
{ id: "claude-haiku-5-5", name: "Claude Haiku 5.5", requests: 3850, allowance: 15, featured: true, fresh: true },
{ id: "qwen3.7-plus", name: "Qwen3.7 Plus", requests: 4300, allowance: 60, featured: true },
{ id: "gpt-6-luna", name: "GPT 6 Luna", requests: 4230, allowance: 15, featured: true },
@@ -81,8 +79,8 @@ export const goModels = [
limitedTime: true,
},
{
id: "cat-jam-free",
name: "Cat Jam Free",
id: "beam-free",
name: "Beam Free",
requests: Infinity,
allowance: Infinity,
featured: true,
@@ -96,7 +94,6 @@ const plusLimits: Record<string, [number, number]> = {
"kimi-k3": [440, 60],
"qwen3.8-max": [640, 60],
"grok-4.7": [676, 60],
"grok-4.6": [676, 60],
"glm-5.3": [1760, 120],
"gemini-4-argon-contributor": [1760, 240],
"glm-5.2": [2640, 180],
@@ -109,7 +106,6 @@ const plusLimits: Record<string, [number, number]> = {
"minimax-m3": [9600, 180],
"mimo-v2.6-pro": [13000, 60],
"mimo-v2.5-pro": [13000, 60],
"minimax-m2.7": [13600, 240],
"qwen3.7-plus": [12900, 180],
"gpt-6-luna": [16920, 60],
"claude-haiku-5-5": [15380, 60],
@@ -123,7 +119,7 @@ const plusLimits: Record<string, [number, number]> = {
"muse-spark-1.3-contributor": [90600, 120],
"muse-spark-1.2-contributor": [90600, 120],
"longcat-2.5-preview-free": [Infinity, Infinity],
"cat-jam-free": [Infinity, Infinity],
"beam-free": [Infinity, Infinity],
}
// A bonus multiplies a model's usual allowance, which is shown crossed out beside the current limits.
+2 -4
View File
@@ -34,9 +34,8 @@ const models = [
{ name: "Space Bunny", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "LongCat 2.5 Preview Free", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "Step 5 Preview", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "Cat Jam Free", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
{ name: "Beam Free", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
{ name: "Grok 4.7", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
{ name: "Grok 4.6", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
{ name: "GPT 6 Luna", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
{ name: "GPT 5.6 Luna", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
{ name: "Claude Haiku 5.5", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention30" },
@@ -55,7 +54,6 @@ const models = [
{ name: "Qwen3.8 Flash", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "Qwen3.7 Plus", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "MiniMax M3", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "MiniMax M2.7", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
{ name: "Muse Spark 1.3 Contributor", training: "go.faq.a5.used", retention: "go.faq.a5.notZdr" },
{ name: "Muse Spark 1.2 Contributor", training: "go.faq.a5.used", retention: "go.faq.a5.notZdr" },
{ name: "DeepSeek V4.1 Flash", training: "go.faq.a5.notUsed", retention: "go.faq.a5.retention0" },
@@ -304,7 +302,7 @@ export default function Home() {
</div>
<div data-slot="faq-retention-notes">
<p>
<strong>Grok 4.7/4.6:</strong> {i18n.t("go.faq.a5.grokRetention")}{" "}
<strong>Grok 4.7:</strong> {i18n.t("go.faq.a5.grokRetention")}{" "}
<a href="https://docs.x.ai/developers/faq/security#what-is-zero-data-retention-zdr">
{i18n.t("go.faq.a5.learnMore")}
</a>
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test"
import path from "node:path"
import { i18n } from "../src/i18n"
import { LOCALES } from "../src/lib/language"
@@ -15,7 +16,7 @@ describe("Console marketing navigation gate", () => {
"--eval",
'import { config } from "./src/config.ts"; console.log(config.consoleMarketingEnabled)',
],
cwd: new URL("..", import.meta.url).pathname,
cwd: path.join(import.meta.dir, ".."),
env: {
...Object.fromEntries(Object.entries(process.env).filter(([key]) => key !== "VITE_CONSOLE_MARKETING_ENABLED")),
...(value === undefined ? {} : { VITE_CONSOLE_MARKETING_ENABLED: value }),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode/console-function",
"version": "2.0.30",
"version": "2.0.31",
"$schema": "https://json.schemastore.org/package.json",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/package.json",
"version": "2.0.30",
"version": "2.0.31",
"name": "@opencode/core",
"type": "module",
"license": "MIT",
+2 -1
View File
@@ -35,7 +35,8 @@ const environment = {
}
const child = Bun.spawn({
cmd: [process.execPath, "test", "--only-failures", ...process.argv.slice(2)],
// The 30s default timeout matches cli and tui; npm.test's Git package installs ran past Bun's 5s default on Windows.
cmd: [process.execPath, "test", "--only-failures", "--timeout=30000", ...process.argv.slice(2)],
env: environment,
stdin: "inherit",
stdout: "inherit",
+25 -2
View File
@@ -90,6 +90,14 @@ export const Plugin = define({
}
next.set(item, { providerID, models: definitions })
}
for (const [item, definition] of next) {
for (const [id, config] of Object.entries(item.models ?? {})) {
if (config.limit === undefined) continue
providers.models.update(definition.providerID, id, (model) => {
model.limit = { ...model.limit, ...config.limit }
})
}
}
sources.defaultModel = Config.latest(loaded.entries, "model")
sources.models = next
})
@@ -113,6 +121,7 @@ export const Plugin = define({
if (config.family !== undefined) model.family = config.family
if (config.name) model.name = config.name
if (config.modelID !== undefined) model.modelID = config.modelID
if (config.releaseDate !== undefined) model.time = { released: Date.parse(config.releaseDate) }
if (config.compatibility !== undefined)
model.compatibility = { ...model.compatibility, ...config.compatibility }
if (config.package !== undefined) model.package = config.package
@@ -121,6 +130,15 @@ export const Plugin = define({
if (config.body !== undefined) model.body = Provider.mergeOverlay(model.body, config.body)
if (config.capabilities !== undefined)
model.capabilities = Model.mergeCapabilities(config.capabilities, model.capabilities)
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
// Configured reasoning replaces the base variants; configured variants still overlay them below.
if (config.capabilities?.reasoning !== undefined)
model.variants = [
...Variant.resolve(
{ ...model, package: model.package ?? models.provider.get(providerID)?.provider.package },
Variant.supports(config.capabilities.reasoning),
),
]
if (config.variants !== undefined) {
model.variants ??= []
for (const variant of config.variants) {
@@ -148,9 +166,14 @@ export const Plugin = define({
}))
}
if (config.disabled !== undefined) model.enabled = !config.disabled
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
})
if (config.variants === undefined && !source?.base)
// Inherited variants are spelled for the base model's package, so a package override needs fresh ones.
// A base without variants has no reasoning support to respell.
const repackaged =
source?.base !== undefined &&
source.base.variants.length > 0 &&
models.get(providerID, id)?.package !== source.base.package
if (config.variants === undefined && config.capabilities?.reasoning === undefined && (!source?.base || repackaged))
models.update(providerID, id, (model) => {
model.variants = [
...Variant.resolve({
+23 -22
View File
@@ -3,8 +3,8 @@ export * as ConfigVariable from "./variable.js"
import os from "os"
import path from "path"
import { Effect } from "effect"
import { type ParseError, parse } from "jsonc-parser"
import { FSUtil } from "@opencode/util/fs-util"
import { InvalidError } from "../v1/config/error.js"
type ParseSource =
| {
@@ -24,12 +24,17 @@ type SubstituteInput = ParseSource & {
/** Apply {env:VAR} and {file:path} substitutions to config text. */
export const substitute = Effect.fn("ConfigVariable.substitute")(function* (input: SubstituteInput) {
const text = input.text.replace(
/\{env:([^}]+)\}/g,
(_, varName: string) => (input.env?.[varName] ?? process.env[varName]) || "",
)
if (!text.includes("{file:")) return text
return yield* substituteFiles(input, text)
const env = (escape: boolean) =>
input.text.replace(/\{env:([^}]+)\}/g, (_, name: string) => {
const value = (input.env?.[name] ?? process.env[name]) || ""
return escape ? JSON.stringify(value).slice(1, -1) : value
})
// Escape only when raw values break the JSON (e.g. Windows paths), so configs that parse today keep their meaning.
const raw = yield* substituteFiles(input, env(false))
const errors: ParseError[] = []
if (input.text.includes("{env:")) parse(raw, errors, { allowTrailingComma: true })
if (!errors.length) return raw
return yield* substituteFiles(input, env(true))
})
const substituteFiles = Effect.fnUntraced(function* (input: SubstituteInput, text: string) {
@@ -55,24 +60,20 @@ const substituteFiles = Effect.fnUntraced(function* (input: SubstituteInput, tex
const filePath = token.slice("{file:".length, -1)
const expandedPath = filePath.startsWith("~/") ? path.join(os.homedir(), filePath.slice(2)) : filePath
const resolvedPath = path.isAbsolute(expandedPath) ? expandedPath : path.resolve(configDir, expandedPath)
const fileContent = yield* fs
.readFileStringSafe(resolvedPath)
.pipe(
Effect.mapError(
(error) =>
new InvalidError({ path: configSource, message: `bad file reference: "${token}"` }, { cause: error }),
),
)
// Like a missing {env:VAR}, a missing or unreadable file substitutes empty so one stale secret
// reference cannot take down every Location that loads this config.
if (fileContent === undefined)
yield* Effect.logWarning("config file reference is missing or unreadable", {
source: configSource,
reference: token,
path: resolvedPath,
})
const fileContent = yield* fs.readFileString(resolvedPath).pipe(
Effect.catch((cause) =>
Effect.logWarning("config file reference is missing or unreadable", {
source: configSource,
reference: token,
path: resolvedPath,
cause,
}).pipe(Effect.as("")),
),
)
out += JSON.stringify((fileContent ?? "").trim()).slice(1, -1)
out += JSON.stringify(fileContent.trim()).slice(1, -1)
cursor = index + token.length
}
+26 -6
View File
@@ -367,6 +367,22 @@ const layer = Layer.effect(
})
})
/**
* On Windows, Git exits non-zero instead of reusing a loose object that another process is finalizing at the
* same moment. Objects are content-addressed, so one of at most two retries finds that copy in place. Only a Git
* exit is retried, never a failure to start Git, and other platforms fail on the first attempt.
*/
const retryConcurrentObjectWrite = <A, R>(effect: Effect.Effect<A, OperationError, R>) =>
process.platform === "win32"
? effect.pipe(
Effect.retry({
times: 2,
schedule: Schedule.spaced("50 millis"),
while: (error) => error.cause === undefined,
}),
)
: effect
/**
* A new store is initialized in a temporary sibling directory and renamed into
* place, so processes racing to create the same store never observe or write a
@@ -505,11 +521,13 @@ const layer = Layer.effect(
{ concurrency: 8 },
)).filter((item): item is RelativePath => item !== undefined)
if (added.length)
yield* repositoryOperation(
"refresh",
input.repository,
["update-index", "--add", "--remove", "--replace", "-z", "--stdin"],
{ stdin: [...added, ...embedded].join("\0") + "\0", index: input.index },
yield* retryConcurrentObjectWrite(
repositoryOperation(
"refresh",
input.repository,
["update-index", "--add", "--remove", "--replace", "-z", "--stdin"],
{ stdin: [...added, ...embedded].join("\0") + "\0", index: input.index },
),
)
return { skipped }
})
@@ -561,7 +579,9 @@ const layer = Layer.effect(
})
const writeTree = Effect.fn("Git.tree.write")(function* (repository: Repository, index?: string) {
const tree = (yield* repositoryOperation("write_tree", repository, ["write-tree"], { index })).text.trim()
const tree = (yield* retryConcurrentObjectWrite(
repositoryOperation("write_tree", repository, ["write-tree"], { index }),
)).text.trim()
if (/^[0-9a-f]{40,64}$/.test(tree)) return TreeID.make(tree)
return yield* new OperationError({
operation: "write_tree",
+20 -1
View File
@@ -35,6 +35,7 @@ export const mergeCapabilities = (config: Partial<Capabilities>, base: Capabilit
tools: config.tools ?? fallback.tools,
input: [...(config.input ?? fallback.input)],
output: [...(config.output ?? fallback.output)],
temperature: config.temperature ?? base?.temperature,
}
}
@@ -222,7 +223,7 @@ const layer = Layer.effect(
const all = Array.from(byProvider.values())
.flatMap((models) => Array.from(models.values()))
.sort((left, right) => right.time.released - left.time.released)
cached = freeze({ data, all, available: all.filter((model) => model.enabled), byProvider }, true)
cached = freeze({ data, all, available: preferFree(all.filter((model) => model.enabled)), byProvider }, true)
return cached
}
})
@@ -286,6 +287,24 @@ const layer = Layer.effect(
export const node = makeLocationNode({ service: Service, layer, deps: [Provider.node, Bus.node, Location.node] })
// Signed out, only free OpenCode models are enabled. Clients default to the first available model, so keep
// these free models ahead of each new free launch instead of letting release order pick the default.
const PREFERRED_FREE = [
"big-pickle",
"deepseek-v4.1-flash-free",
"glm-5.3-flash-free",
"muse-spark-1.3-contributor-free",
]
function preferFree(models: Info[]) {
const freeOnly = models.every(
(model) => model.providerID === Provider.ID.opencode && !model.cost.some((cost) => cost.input > 0),
)
if (!freeOnly) return models
const picks = PREFERRED_FREE.flatMap((id) => models.find((model) => model.id === id) ?? [])
return [...picks, ...models.filter((model) => !picks.includes(model))]
}
export function supportsText(model: Pick<Info, "capabilities">) {
return (
(model.capabilities.input.length === 0 || model.capabilities.input.some((item) => item.startsWith("text"))) &&
+1
View File
@@ -233,6 +233,7 @@ function modelInfo(
tools: model.tool_call,
input: [...(model.modalities?.input ?? [])],
output: [...(model.modalities?.output ?? [])],
temperature: model.temperature,
},
variants: [...(input.variants ?? [])],
time: { released: released(model.release_date) },
+1 -1
View File
@@ -1 +1 @@
{"deepinfra":{"id":"deepinfra","env":["DEEPINFRA_API_KEY"],"npm":"@ai-sdk/deepinfra","name":"Deep Infra","doc":"https://deepinfra.com/models","models":{"anthropic/claude-fable-5":{"id":"anthropic/claude-fable-5","name":"Claude Fable 5","description":"Claude model for creative writing, analysis, and controlled agent workflows","family":"claude-fable","attachment":true,"reasoning":true,"reasoning_options":[{"type":"effort","values":["low","medium","high","xhigh","max"]}],"tool_call":true,"structured_output":true,"temperature":false,"knowledge":"2026-01-31","release_date":"2026-06-09","last_updated":"2026-06-09","modalities":{"input":["text","image","pdf"],"output":["text"]},"open_weights":false,"limit":{"context":1000000,"output":128000},"cost":{"input":10,"output":50},"canonical_model_id":"anthropic/claude-fable-5"},"tencent/Hy3":{"id":"tencent/Hy3","name":"Hy3","description":"Tencent Hy reasoning model for coding, instruction following, and agent tasks","family":"Hy","attachment":false,"reasoning":true,"reasoning_options":[],"tool_call":true,"structured_output":true,"temperature":true,"release_date":"2026-07-06","last_updated":"2026-07-06","modalities":{"input":["text"],"output":["text"]},"open_weights":true,"limit":{"context":262144,"input":192000,"output":128000},"status":"deprecated","cost":{"input":0.13,"output":0.53,"cache_read":0.033},"canonical_model_id":"tencent/hy3"},"tencent/Hy4-preview":{"id":"tencent/Hy4-preview","name":"Hy4 preview","description":"A next-generation productivity model with significantly enhanced Agent and complex task execution capabilities.","family":"Hy","attachment":false,"reasoning":true,"reasoning_options":[{"type":"effort","values":["none","high"]}],"tool_call":true,"structured_output":true,"temperature":true,"release_date":"2026-08-28","last_updated":"2026-08-28","modalities":{"input":["text"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":64000},"cost":{"input":0.834,"output":2.501,"cache_read":0.042},"canonical_model_id":"tencent/hy4-preview"},"meta-llama/Llama-3.3-70B-Instruct-Turbo":{"id":"meta-llama/Llama-3.3-70B-Instruct-Turbo","name":"Llama 3.3 70B Turbo","description":"Compact Llama instruction model for fast chat and local deployment","family":"llama","attachment":false,"reasoning":false,"tool_call":true,"structured_output":true,"release_date":"2024-12-06","last_updated":"2024-12-06","modalities":{"input":["text"],"output":["text"]},"open_weights":true,"limit":{"context":131072,"output":16384},"cost":{"input":0.1,"output":0.32}},"meta-llama/Llama-4-Scout-17B-16E-Instruct":{"id":"meta-llama/Llama-4-Scout-17B-16E-Instruct","name":"Llama 4 Scout 17B","description":"Open multimodal Llama model for long-context analysis and efficient agents","family":"llama","attachment":true,"reasoning":false,"tool_call":true,"structured_output":true,"release_date":"2025-04-05","last_updated":"2025-04-05","modalities":{"input":["text","image"],"output":["text"]},"open_weights":true,"limit":{"context":327680,"output":16384},"cost":{"input":0.1,"output":0.3}},"meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8":{"id":"meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8","name":"Llama 4 Maverick 17B FP8","description":"Open multimodal Llama model for strong reasoning and fast responses","family":"llama","attachment":true,"reasoning":false,"tool_call":false,"structured_output":true,"release_date":"2025-04-05","last_updated":"2025-04-05","modalities":{"input":["text","image"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":16384},"status":"deprecated","cost":{"input":0.2,"output":0.8}},"XiaomiMiMo/MiMo-V2.6-Pro":{"id":"XiaomiMiMo/MiMo-V2.6-Pro","name":"MiMo-V2.6-Pro","description":"Stronger MiMo Pro tier for multimodal reasoning and coding-agent execution","family":"mimo","attachment":true,"reasoning":true,"reasoning_options":[{"type":"toggle"}],"tool_call":true,"structured_output":true,"temperature":true,"release_date":"2026-09-22","last_updated":"2026-09-22","modalities":{"input":["text","image","audio","video"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":131072},"cost":{"input":0.43,"output":0.87,"cache_read":0.0036},"canonical_model_id":"xiaomi/mimo-v2.6-pro"},"XiaomiMiMo/MiMo-V2.5-Pro":{"id":"XiaomiMiMo/MiMo-V2.5-Pro","name":"MiMo-V2.5-Pro","description":"Stronger MiMo Pro tier for multimodal reasoning and coding-agent execution","family":"mimo","attachment":true,"reasoning":true,"reasoning_options":[{"type":"toggle"}],"tool_call":true,"interleaved":{"field":"reasoning_content"},"structured_output":true,"temperature":true,"knowledge":"2024-12","release_date":"2026-04-22","last_updated":"2026-04-22","modalities":{"input":["text","audio"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":16384},"status":"deprecated","cost":{"input":1,"output":3,"cache_read":0.2},"canonical_model_id":"xiaomi/mimo-v2.5-pro"},"XiaomiMiMo/MiMo-V2.6-Flash":{"id":"XiaomiMiMo/MiMo-V2.6-Flash","name":"MLine truncated
{"deepinfra":{"id":"deepinfra","env":["DEEPINFRA_API_KEY"],"npm":"@ai-sdk/deepinfra","name":"Deep Infra","doc":"https://deepinfra.com/models","models":{"anthropic/claude-fable-5":{"id":"anthropic/claude-fable-5","name":"Claude Fable 5","description":"Claude model for creative writing, analysis, and controlled agent workflows","family":"claude-fable","attachment":true,"reasoning":true,"reasoning_options":[{"type":"effort","values":["low","medium","high","xhigh","max"]}],"tool_call":true,"structured_output":true,"temperature":false,"knowledge":"2026-01-31","release_date":"2026-06-09","last_updated":"2026-06-09","modalities":{"input":["text","image","pdf"],"output":["text"]},"open_weights":false,"limit":{"context":1000000,"output":128000},"cost":{"input":10,"output":50},"canonical_model_id":"anthropic/claude-fable-5"},"tencent/Hy3":{"id":"tencent/Hy3","name":"Hy3","description":"Tencent Hy reasoning model for coding, instruction following, and agent tasks","family":"Hy","attachment":false,"reasoning":true,"reasoning_options":[],"tool_call":true,"structured_output":true,"temperature":true,"release_date":"2026-07-06","last_updated":"2026-07-06","modalities":{"input":["text"],"output":["text"]},"open_weights":true,"limit":{"context":262144,"input":192000,"output":128000},"status":"deprecated","cost":{"input":0.13,"output":0.53,"cache_read":0.033},"canonical_model_id":"tencent/hy3"},"tencent/Hy4-preview":{"id":"tencent/Hy4-preview","name":"Hy4 preview","description":"A next-generation productivity model with significantly enhanced Agent and complex task execution capabilities.","family":"Hy","attachment":false,"reasoning":true,"reasoning_options":[{"type":"effort","values":["none","high"]}],"tool_call":true,"structured_output":true,"temperature":true,"release_date":"2026-08-28","last_updated":"2026-08-28","modalities":{"input":["text"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":64000},"cost":{"input":0.834,"output":2.501,"cache_read":0.042},"canonical_model_id":"tencent/hy4-preview"},"meta-llama/Llama-3.3-70B-Instruct-Turbo":{"id":"meta-llama/Llama-3.3-70B-Instruct-Turbo","name":"Llama 3.3 70B Turbo","description":"Compact Llama instruction model for fast chat and local deployment","family":"llama","attachment":false,"reasoning":false,"tool_call":true,"structured_output":true,"release_date":"2024-12-06","last_updated":"2024-12-06","modalities":{"input":["text"],"output":["text"]},"open_weights":true,"limit":{"context":131072,"output":16384},"cost":{"input":0.1,"output":0.32}},"meta-llama/Llama-4-Scout-17B-16E-Instruct":{"id":"meta-llama/Llama-4-Scout-17B-16E-Instruct","name":"Llama 4 Scout 17B","description":"Open multimodal Llama model for long-context analysis and efficient agents","family":"llama","attachment":true,"reasoning":false,"tool_call":true,"structured_output":true,"release_date":"2025-04-05","last_updated":"2025-04-05","modalities":{"input":["text","image"],"output":["text"]},"open_weights":true,"limit":{"context":327680,"output":16384},"cost":{"input":0.1,"output":0.3}},"meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8":{"id":"meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8","name":"Llama 4 Maverick 17B FP8","description":"Open multimodal Llama model for strong reasoning and fast responses","family":"llama","attachment":true,"reasoning":false,"tool_call":false,"structured_output":true,"release_date":"2025-04-05","last_updated":"2025-04-05","modalities":{"input":["text","image"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":16384},"status":"deprecated","cost":{"input":0.2,"output":0.8}},"XiaomiMiMo/MiMo-V2.6-Pro":{"id":"XiaomiMiMo/MiMo-V2.6-Pro","name":"MiMo-V2.6-Pro","description":"Stronger MiMo Pro tier for multimodal reasoning and coding-agent execution","family":"mimo","attachment":true,"reasoning":true,"reasoning_options":[{"type":"toggle"}],"tool_call":true,"structured_output":true,"temperature":true,"release_date":"2026-09-22","last_updated":"2026-09-22","modalities":{"input":["text","image","audio","video"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":131072},"cost":{"input":0.43,"output":0.87,"cache_read":0.0036},"canonical_model_id":"xiaomi/mimo-v2.6-pro"},"XiaomiMiMo/MiMo-V2.5-Pro":{"id":"XiaomiMiMo/MiMo-V2.5-Pro","name":"MiMo-V2.5-Pro","description":"Stronger MiMo Pro tier for multimodal reasoning and coding-agent execution","family":"mimo","attachment":true,"reasoning":true,"reasoning_options":[{"type":"toggle"}],"tool_call":true,"interleaved":{"field":"reasoning_content"},"structured_output":true,"temperature":true,"knowledge":"2024-12","release_date":"2026-04-22","last_updated":"2026-04-22","modalities":{"input":["text","audio"],"output":["text"]},"open_weights":true,"limit":{"context":1048576,"output":16384},"status":"deprecated","cost":{"input":1,"output":3,"cache_read":0.2},"canonical_model_id":"xiaomi/mimo-v2.5-pro"},"XiaomiMiMo/MiMo-V2.6-Flash":{"id":"XiaomiMiMo/MiMo-V2.6-Flash","name":"MLine truncated
+7 -1
View File
@@ -7,12 +7,13 @@ import { Model } from "../model.js"
import { ModelsDev } from "../models-dev.js"
// These catalog entries require inference profiles on Bedrock Runtime.
// Opus/Sonnet 4.6 support in-region calls in eu-west-2 and must remain available.
// Opus/Sonnet 4.6 and Opus 5.5 support in-region calls in eu-west-2 and must remain available.
const BEDROCK_PROFILE_ONLY_IDS = [
"amazon.nova-2-lite-v1:0",
"anthropic.claude-fable-5",
"anthropic.claude-fable-5-1",
"anthropic.claude-haiku-4-5-20251001-v1:0",
"anthropic.claude-haiku-5-5",
"anthropic.claude-opus-4-1-20250805-v1:0",
"anthropic.claude-opus-4-5-20251101-v1:0",
"anthropic.claude-opus-4-7",
@@ -20,8 +21,13 @@ const BEDROCK_PROFILE_ONLY_IDS = [
"anthropic.claude-opus-5",
"anthropic.claude-sonnet-4-5-20250929-v1:0",
"anthropic.claude-sonnet-5",
"anthropic.claude-sonnet-5-5",
"deepseek.r1-v1:0",
"meta.llama4-maverick-17b-instruct-v1:0",
"meta.llama4-scout-17b-instruct-v1:0",
"mistral.pixtral-large-2502-v1:0",
"writer.palmyra-x4-v1:0",
"writer.palmyra-x5-v1:0",
]
export const ModelsDevPlugin = define({
+11 -1
View File
@@ -11,6 +11,7 @@ import { IntegrationConnection } from "../../integration/connection.js"
import { ManagedPolicy } from "../../managed-policy.js"
import { Model } from "../../model.js"
import { Provider } from "../../provider.js"
import { Variant } from "../../variant.js"
import { WebSearch } from "../../websearch.js"
import { ConfigPolicy } from "@opencode/schema/config/policy"
import { ConfigProvider } from "@opencode/schema/config/provider"
@@ -287,6 +288,7 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
if (config.family !== undefined) model.family = config.family
if (config.name !== undefined) model.name = config.name
if (config.modelID !== undefined) model.modelID = config.modelID
if (config.releaseDate !== undefined) model.time = { released: Date.parse(config.releaseDate) }
if (config.compatibility !== undefined)
model.compatibility = { ...model.compatibility, ...config.compatibility }
model.package = config.package ?? (item.package !== undefined ? undefined : model.package)
@@ -299,6 +301,15 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
)
model.headers = Provider.mergeHeaders(model.headers, config.headers)
model.body = Provider.mergeOverlay(model.body, config.body)
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
// The Console's reasoning replaces the base variants; its variants still overlay them below.
if (config.capabilities?.reasoning !== undefined)
model.variants = [
...Variant.resolve(
{ ...model, package: model.package ?? providers.get(providerID)?.provider.package },
Variant.supports(config.capabilities.reasoning),
),
]
for (const variant of config.variants ?? []) {
let existing = model.variants.find((item) => item.id === variant.id)
if (!existing) {
@@ -322,7 +333,6 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
},
}))
model.enabled = !config.disabled
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
})
}
const configured = providers.get(providerID)
+4 -1
View File
@@ -299,7 +299,10 @@ function sanitizeMessage(message: SessionMessage.Info): SessionMessage.Info {
summary: redact("compaction-summary", message.id, message.summary),
recent: redact("compaction-recent", message.id, message.recent),
...(message.status === "completed"
? { providerState: metadata("compaction-provider-state", message.id, message.providerState) }
? {
providerState: metadata("compaction-provider-state", message.id, message.providerState),
providerContext: undefined,
}
: {}),
}
}
+13
View File
@@ -1,5 +1,6 @@
export * as Variant from "./variant.js"
import { ConfigProvider } from "@opencode/schema/config/provider"
import { Model } from "./model.js"
import { Provider } from "./provider.js"
@@ -8,6 +9,18 @@ export type Support =
| { readonly type: "toggle" }
| { readonly type: "budget_tokens"; readonly min?: number; readonly max?: number }
/** Reasoning controls in models.dev v2's shape, where `default` is the provider default rather than a variant. */
export function supports(reasoning: ConfigProvider.Reasoning): readonly Support[] {
if (!reasoning.supported) return []
return [
...(reasoning.toggle ? [{ type: "toggle" as const }] : []),
...(reasoning.effort
? [{ type: "effort" as const, values: reasoning.effort.filter((value) => value !== "default") }]
: []),
...(reasoning.budget ? [{ type: "budget_tokens" as const, ...reasoning.budget }] : []),
]
}
type Variants = Model.Info["variants"]
type Overlay = Omit<Variants[number], "id">
+22 -2
View File
@@ -1,5 +1,5 @@
import { expect } from "bun:test"
import { Context, Effect, Fiber, RcMap, Schedule } from "effect"
import { Clock, Context, Duration, Effect, Fiber, Layer, RcMap, Schedule } from "effect"
import { Browser } from "@opencode/plugin-browser/rpc"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
@@ -21,6 +21,22 @@ import { offlineModels } from "./fixture/models"
import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
// LocationActivity measures idleness on this clock. Its sweep still sleeps in real time, but only the test moves the
// clock past the TTL, so slow plugin activation on a busy machine cannot evict the location before the browser
// attachment exists, as a short real TTL could.
const timeToLive = Duration.minutes(1)
const idle = { millis: 0 }
const live = Clock.Clock.defaultValue()
const activityClock: Clock.Clock = {
currentTimeMillisUnsafe: () => live.currentTimeMillisUnsafe() + idle.millis,
currentTimeMillis: Effect.sync(() => live.currentTimeMillisUnsafe() + idle.millis),
currentTimeNanosUnsafe: () => live.currentTimeNanosUnsafe() + BigInt(idle.millis) * 1_000_000n,
currentTimeNanos: Effect.sync(() => live.currentTimeNanosUnsafe() + BigInt(idle.millis) * 1_000_000n),
monotonicTimeNanosUnsafe: () => live.monotonicTimeNanosUnsafe(),
monotonicTimeNanos: live.monotonicTimeNanos,
sleep: (duration) => live.sleep(duration),
}
const it = testEffect(
AppNodeBuilder.build(
LayerNode.group([Database.node, Bus.node, Session.node, LocationServiceMap.node, LocationActivity.node]),
@@ -30,7 +46,9 @@ const it = testEffect(
LocationActivity.node.replace(
makeGlobalNode({
service: LocationActivity.Service,
layer: LocationActivity.layer({ timeToLive: "2 seconds", sweepInterval: "100 millis" }),
layer: LocationActivity.layer({ timeToLive, sweepInterval: "100 millis" }).pipe(
Layer.provide(Layer.succeed(Clock.Clock, activityClock)),
),
deps: [Bus.node, LocationServiceMap.node, SessionExecution.node, SessionStore.node],
}),
),
@@ -62,6 +80,8 @@ it.live(
}),
Effect.timeout("5 seconds"),
)
// The location has now been idle for its whole TTL; the next sweep evicts it.
idle.millis += Duration.toMillis(timeToLive)
// Real idle cleanup must end the long-lived request, not leave a second registry behind it.
expect(yield* Fiber.join(pending).pipe(Effect.timeout("10 seconds"))).toMatchObject({ type: "rpc.unavailable" })
+50
View File
@@ -12,6 +12,7 @@ import { Model } from "@opencode/core/model"
import { ModelResolver } from "@opencode/core/model-resolver"
import { Provider } from "@opencode/core/provider"
import { AbsolutePath } from "@opencode/core/schema"
import { Money } from "@opencode/schema/money"
import { location } from "./fixture/location"
import { testEffect } from "./lib/effect"
@@ -569,6 +570,55 @@ describe("Provider and Model", () => {
}),
)
it.effect("defaults to big-pickle when only free OpenCode models are available", () =>
Effect.gen(function* () {
const providers = yield* Provider.Service
const models = yield* Model.Service
yield* providers.transform((editor) => {
editor.update(Provider.ID.opencode, () => {})
;["muse-spark-1.3-contributor-free", "new-free", "deepseek-v4.1-flash-free", "big-pickle"].forEach(
(id, index) =>
editor.models.update(Provider.ID.opencode, Model.ID.make(id), (model) => {
model.time.released = 4000 - index * 1000
}),
)
})
expect((yield* models.available()).map((model) => model.id)).toEqual([
Model.ID.make("big-pickle"),
Model.ID.make("deepseek-v4.1-flash-free"),
Model.ID.make("muse-spark-1.3-contributor-free"),
Model.ID.make("new-free"),
])
expect((yield* models.default())?.id).toBe(Model.ID.make("big-pickle"))
}),
)
it.effect("keeps the newest default when a paid model is available", () =>
Effect.gen(function* () {
const providers = yield* Provider.Service
const models = yield* Model.Service
yield* providers.transform((editor) => {
editor.update(Provider.ID.opencode, () => {})
editor.models.update(Provider.ID.opencode, Model.ID.make("big-pickle"), (model) => {
model.time.released = 1000
})
editor.models.update(Provider.ID.opencode, Model.ID.make("paid"), (model) => {
model.time.released = 2000
model.cost = [
{
input: Money.USDPerMillionTokens.make(1),
output: Money.USDPerMillionTokens.make(1),
cache: { read: Money.USDPerMillionTokens.zero, write: Money.USDPerMillionTokens.zero },
},
]
})
})
expect((yield* models.default())?.id).toBe(Model.ID.make("paid"))
}),
)
it.effect("uses a transform-provided default model until that transform is replaced", () =>
Effect.gen(function* () {
const providers = yield* Provider.Service
+26 -3
View File
@@ -14,6 +14,8 @@ import { Credential } from "@opencode/core/credential"
import { ConfigV1 } from "../fixture/v1-config/config"
import { ConfigPermissionV1 } from "@opencode/core/v1/config/permission"
import { ConfigNormalize } from "@opencode/core/config/normalize"
import { ConfigVariable } from "@opencode/core/config/variable"
import { FSUtil } from "@opencode/util/fs-util"
import { Watcher } from "@opencode/core/filesystem/watcher"
import { Bus } from "@opencode/core/bus"
import { Global } from "@opencode/util/global"
@@ -1335,8 +1337,10 @@ describe("Config", () => {
const previous = {
token: process.env.OPENCODE_TEST_MCP_TOKEN,
missing: process.env.OPENCODE_TEST_MISSING,
flag: process.env.OPENCODE_TEST_FLAG,
}
process.env.OPENCODE_TEST_MCP_TOKEN = "secret"
process.env.OPENCODE_TEST_FLAG = "false"
process.env.OPENCODE_TEST_MCP_TOKEN = String.raw`C:\Users\new\"secret"`
delete process.env.OPENCODE_TEST_MISSING
return previous
}),
@@ -1353,6 +1357,7 @@ describe("Config", () => {
`{
// Ignored reference: {file:.}
"username": "user-{env:OPENCODE_TEST_MISSING}",
"snapshots": {env:OPENCODE_TEST_FLAG},
"mcp": {
"servers": {
"remote": {
@@ -1361,7 +1366,8 @@ describe("Config", () => {
"headers": {
"Authorization": "Bearer {env:OPENCODE_TEST_MCP_TOKEN}",
"X-Token": "{file:token.txt}",
"X-Missing": "Bearer {file:~/.opencode-test-missing/key}"
"X-Missing": "Bearer {file:~/.opencode-test-missing/key}",
"X-Folder": "{file:.}"
}
}
}
@@ -1375,13 +1381,15 @@ describe("Config", () => {
const config = yield* Config.Service
const document = (yield* config.entries()).find((entry) => entry.type === "document")
expect(document?.info.username).toBe("user-")
expect(document?.info.snapshots).toBe(false)
const remote = document?.info.mcp?.servers?.remote
expect(remote?.type).toBe("remote")
if (remote?.type !== "remote") return
expect(remote.headers).toEqual({
Authorization: "Bearer secret",
Authorization: String.raw`Bearer C:\Users\new\"secret"`,
"X-Token": 'file\n"token"',
"X-Missing": "Bearer ",
"X-Folder": "",
})
}).pipe(Effect.provide(testLayer(tmp.path)))
}),
@@ -1393,10 +1401,25 @@ describe("Config", () => {
else process.env.OPENCODE_TEST_MCP_TOKEN = previous.token
if (previous.missing === undefined) delete process.env.OPENCODE_TEST_MISSING
else process.env.OPENCODE_TEST_MISSING = previous.missing
if (previous.flag === undefined) delete process.env.OPENCODE_TEST_FLAG
else process.env.OPENCODE_TEST_FLAG = previous.flag
}),
),
)
it.effect("keeps env values unescaped when the config already parses", () =>
Effect.gen(function* () {
const text = yield* ConfigVariable.substitute({
type: "virtual",
source: "test",
dir: "/",
text: '{ "quoted": "{env:QUOTED}", "fragment": {env:FRAGMENT} }',
env: { QUOTED: String.raw`a\"b`, FRAGMENT: '{"k":"v"}' },
})
expect(JSON.parse(text)).toEqual({ quoted: 'a"b', fragment: { k: "v" } })
}).pipe(Effect.provide(AppNodeBuilder.build(FSUtil.node))),
)
it.live("does not load legacy config.json files", () =>
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
Effect.flatMap((tmp) =>
+147 -1
View File
@@ -49,7 +49,10 @@ describe("ConfigProviderPlugin.Plugin", () => {
settings: { compaction: { type: "native" } },
models: {
native: {},
local: { settings: { compaction: { type: "summary" } }, package: "@opencode/ai/providers/openai/chat" },
local: {
settings: { compaction: { type: "summary" } },
package: "@opencode/ai/providers/openai/chat",
},
unsupported: { package: "@opencode/ai/providers/openai/chat" },
},
},
@@ -696,6 +699,141 @@ describe("ConfigProviderPlugin.Plugin", () => {
}),
)
it.effect("respells inherited variants when config moves a catalog model to another package", () =>
Effect.gen(function* () {
const providers = yield* Provider.Service
const models = yield* Model.Service
const providerID = Provider.ID.make("bedrock")
const modelID = Model.ID.make("anthropic.claude-opus-5-5")
yield* providers.transform((editor) => {
editor.models.update(providerID, modelID, (model) => {
model.package = "@opencode/ai/providers/amazon-bedrock"
model.variants = [
{
id: Model.VariantID.make("high"),
body: { additionalModelRequestFields: { output_config: { effort: "high" } } },
},
]
})
})
yield* addPlugin([
new Document({
type: "document",
info: decode({
providers: {
bedrock: { models: { [modelID]: { package: "@opencode/ai/providers/amazon-bedrock/mantle" } } },
},
}),
}),
])
const model = required(yield* models.get(providerID, modelID))
expect(model.package).toBe("@opencode/ai/providers/amazon-bedrock/mantle/messages")
expect(model.variants.find((variant) => variant.id === "high")).toEqual({
id: Model.VariantID.make("high"),
settings: { effort: "high", thinking: { type: "adaptive", display: "summarized" } },
})
}),
)
it.effect("keeps a moved catalog model without reasoning variants free of variants", () =>
Effect.gen(function* () {
const providers = yield* Provider.Service
const models = yield* Model.Service
const providerID = Provider.ID.make("bedrock")
const modelID = Model.ID.make("anthropic.claude-plain")
yield* providers.transform((editor) => {
editor.models.update(providerID, modelID, (model) => {
model.package = "@opencode/ai/providers/amazon-bedrock"
})
})
yield* addPlugin([
new Document({
type: "document",
info: decode({
providers: {
bedrock: { models: { [modelID]: { package: "@opencode/ai/providers/amazon-bedrock/mantle" } } },
},
}),
}),
])
expect(required(yield* models.get(providerID, modelID)).variants).toEqual([])
}),
)
it.effect("builds variants from configured reasoning and overlays configured variants", () =>
Effect.gen(function* () {
const models = yield* Model.Service
const providerID = Provider.ID.make("custom")
yield* addPlugin([
new Document({
type: "document",
info: decode({
providers: {
custom: {
package: "aisdk:@ai-sdk/openai",
models: {
effort: {
capabilities: { reasoning: { supported: true, effort: ["default", "low", "high"] } },
variants: [{ id: "high", headers: { "x-tier": "high" } }],
},
fixed: { capabilities: { reasoning: { supported: true } } },
plain: { capabilities: { reasoning: { supported: false } } },
},
},
},
}),
}),
])
const effort = required(yield* models.get(providerID, Model.ID.make("effort")))
expect(effort.variants).toEqual([
{
id: Model.VariantID.make("low"),
settings: { reasoningEffort: "low", reasoningSummary: "auto", include: ["reasoning.encrypted_content"] },
},
{
id: Model.VariantID.make("high"),
settings: { reasoningEffort: "high", reasoningSummary: "auto", include: ["reasoning.encrypted_content"] },
headers: { "x-tier": "high" },
},
])
expect(required(yield* models.get(providerID, Model.ID.make("fixed"))).variants).toEqual([])
expect(required(yield* models.get(providerID, Model.ID.make("plain"))).variants).toEqual([])
}),
)
it.effect("applies configured release date, temperature support, and reasoning field", () =>
Effect.gen(function* () {
const models = yield* Model.Service
yield* addPlugin([
new Document({
type: "document",
info: decode({
providers: {
custom: {
package: "aisdk:@ai-sdk/openai-compatible",
models: {
reasoner: {
releaseDate: "2026-02-03",
capabilities: { temperature: false },
compatibility: { reasoningField: "reasoning_content" },
},
},
},
},
}),
}),
])
const model = required(yield* models.get(Provider.ID.make("custom"), Model.ID.make("reasoner")))
expect(model.time.released).toBe(Date.UTC(2026, 1, 3))
expect(model.capabilities.temperature).toBe(false)
expect(model.compatibility?.reasoningField).toBe("reasoning_content")
}),
)
it.effect("keeps configured model variant bodies unchanged", () =>
Effect.gen(function* () {
const models = yield* Model.Service
@@ -889,7 +1027,15 @@ describe("ConfigProviderPlugin.Plugin", () => {
model.variants = [{ id: Model.VariantID.make("fast"), settings: { effort: "high" } }]
})
})
let transformed: Model.Info["limit"] | undefined
yield* models.transform((editor) => {
const model = editor.get(providerID, modelID)
if (!model) return
transformed = { ...model.limit }
model.limit = { context: 10, output: 1 }
})
yield* addPlugin(entries)
expect(transformed).toEqual({ context: 100, output: 75 })
const provider = required(yield* providers.get(providerID))
const model = required(yield* models.get(providerID, modelID))
+3 -1
View File
@@ -309,7 +309,9 @@ describe("config plugin reloads", () => {
(yield* integrations.get(Integration.ID.make("second"))) !== undefined &&
(yield* references.list()).some((reference) => reference.name === "second") &&
(yield* providers.get(Provider.ID.make("first"))) === undefined &&
(yield* providers.get(Provider.ID.make("second"))) !== undefined
(yield* providers.get(Provider.ID.make("second"))) !== undefined &&
(yield* skills.list()).every((skill) => skill.id !== "first") &&
(yield* skills.list()).some((skill) => skill.id === "second")
)
}),
)
@@ -19,6 +19,7 @@ import { Location } from "@opencode/core/location"
import { Plugin } from "@opencode/core/plugin"
import { PluginSupervisor } from "@opencode/core/plugin/supervisor"
import { AbsolutePath } from "@opencode/core/schema"
import { initRepo } from "../fixture/git"
import { location } from "../fixture/location"
import { tmpdir } from "../fixture/tmpdir"
import { testEffect } from "../lib/effect"
@@ -267,12 +268,7 @@ function withTmp<A, E, R>(
return { tmp, vcs: { type: "hg" as const, store: AbsolutePath.make(path.join(tmp.path, ".hg")) } }
}
if (options?.vcs !== "git") return { tmp, vcs: undefined }
await $`git init`.cwd(tmp.path).quiet()
await $`git config core.fsmonitor false`.cwd(tmp.path).quiet()
await $`git config commit.gpgsign false`.cwd(tmp.path).quiet()
await $`git config user.email test@opencode.test`.cwd(tmp.path).quiet()
await $`git config user.name Test`.cwd(tmp.path).quiet()
await $`git commit --allow-empty -m root`.cwd(tmp.path).quiet()
await initRepo(tmp.path)
await options.init?.(tmp.path)
return { tmp, vcs: { type: "git" as const, store: AbsolutePath.make(path.join(tmp.path, ".git")) } }
}),
+18 -8
View File
@@ -10,13 +10,27 @@ import { tmpdir } from "./tmpdir"
const exec = promisify(execFile)
// Appended to the new repository's own config instead of running one `git config` process per key, which costs
// tens of milliseconds each on Windows. Repositories created by production code still have no identity.
const repositoryConfig = `[core]
fsmonitor = false
[commit]
gpgsign = false
[user]
email = test@opencode.test
name = Test
`
export async function initGit(directory: string, ...args: string[]) {
await $`git init ${args} ${directory}`.quiet()
await fs.appendFile(path.join(directory, ".git", "config"), repositoryConfig)
}
export async function gitRemote(root: string) {
const origin = path.join(root, "origin.git")
const source = path.join(root, "source")
await git(root, "init", "--bare", origin)
await git(root, "init", source)
await git(source, "config", "user.email", "test@example.com")
await git(source, "config", "user.name", "Test")
await initGit(source)
await fs.writeFile(path.join(source, "README.md"), "one\n")
await git(source, "add", "README.md")
await git(source, "commit", "-m", "initial")
@@ -48,11 +62,7 @@ export function read(file: string) {
}
export async function initRepo(directory: string) {
await $`git init`.cwd(directory).quiet()
await $`git config core.fsmonitor false`.cwd(directory).quiet()
await $`git config commit.gpgsign false`.cwd(directory).quiet()
await $`git config user.email test@opencode.test`.cwd(directory).quiet()
await $`git config user.name Test`.cwd(directory).quiet()
await initGit(directory)
await $`git commit --allow-empty -m root`.cwd(directory).quiet()
}
+10 -4
View File
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test"
import path from "path"
import { Cause, Clock, Duration, Effect, Exit, Fiber, Layer, Scope, Stream } from "effect"
import { TestClock } from "effect/testing"
import { Credential } from "@opencode/core/credential"
@@ -8,6 +9,7 @@ import { LayerNode } from "@opencode/util/effect/layer-node"
import { Bus } from "@opencode/core/bus"
import { Integration } from "@opencode/core/integration"
import { State } from "@opencode/core/state"
import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
const it = testEffect(AppNodeBuilder.build(LayerNode.group([Integration.node, Credential.node, Bus.node])))
@@ -31,17 +33,18 @@ const failingIt = testEffect(
AppNodeBuilder.build(LayerNode.group([Integration.node, Bus.node]), [Credential.node.replace(failingCredentialNode)]),
)
// Bounded by elapsed time rather than attempts, so a slow child process start on a busy machine still fits.
function eventually<A, E, R>(
effect: Effect.Effect<A, E, R>,
predicate: (value: A) => boolean,
remaining = 1000,
deadline = Date.now() + 10_000,
): Effect.Effect<A, E | Error, R> {
return Effect.gen(function* () {
const value = yield* effect
if (predicate(value)) return value
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
if (Date.now() > deadline) return yield* Effect.fail(new Error("Timed out waiting for value"))
yield* Effect.promise(() => Bun.sleep(1))
return yield* eventually(effect, predicate, remaining - 1)
return yield* eventually(effect, predicate, deadline)
})
}
@@ -224,6 +227,8 @@ describe("Integration", () => {
const credentials = yield* Credential.Service
const integrationID = Integration.ID.make("company")
const methodID = Integration.MethodID.make("login")
// The command prints its secret only after the test has seen it pending, however slow the machine is.
const release = path.join((yield* tmpdirScoped()).path, "release")
yield* integrations.transform((editor) =>
editor.method.update({
integrationID,
@@ -234,7 +239,7 @@ describe("Integration", () => {
command: [
process.execPath,
"-e",
'console.error("https://example.com/login"); await Bun.sleep(50); console.log("secret")',
`console.error("https://example.com/login"); while (!(await Bun.file(${JSON.stringify(release)}).exists())) await Bun.sleep(10); console.log("secret")`,
],
},
}),
@@ -246,6 +251,7 @@ describe("Integration", () => {
(status) => status.status === "pending" && status.message?.includes("https://example.com/login") === true,
)
expect(pending).toMatchObject({ status: "pending", message: "https://example.com/login\n" })
yield* Effect.promise(() => Bun.write(release, ""))
expect(
yield* eventually(
+5 -33
View File
@@ -5,7 +5,6 @@ import { describe, expect } from "bun:test"
import { Config } from "@opencode/schema/config"
import { Money } from "@opencode/schema/money"
import {
Cause,
DateTime,
Deferred,
Duration,
@@ -79,11 +78,10 @@ const itWithActivity = testEffect(
)
describe("LocationServiceMap", () => {
for (const failure of ["file", "permissions", "config reference"] as const) {
for (const failure of ["file", "permissions"] as const) {
for (const invalidate of [false, true]) {
// The file-path fixture boots on Windows rather than failing during
// discovery. The config-reference case covers repair on every OS.
// Windows does not enforce POSIX directory modes, and root bypasses them.
// discovery. Windows does not enforce POSIX directory modes, and root bypasses them.
const test =
(failure === "file" && process.platform === "win32") ||
(failure === "permissions" && (process.platform === "win32" || process.getuid?.() === 0))
@@ -102,20 +100,8 @@ describe("LocationServiceMap", () => {
yield* Effect.promise(() => fs.mkdir(directory, { mode: 0o000 }))
yield* Effect.addFinalizer(() => Effect.promise(() => fs.chmod(directory, 0o755)))
}
if (failure === "config reference") {
yield* Effect.promise(() => fs.mkdir(path.join(directory, "username.txt"), { recursive: true }))
yield* Effect.promise(() =>
fs.writeFile(path.join(directory, "opencode.json"), JSON.stringify({ username: "{file:username.txt}" })),
)
}
const first = yield* Effect.exit(load)
expect(Exit.isFailure(first)).toBe(true)
if (failure === "config reference" && Exit.isFailure(first)) {
expect(Cause.squash(first.cause)).toMatchObject({
name: "ConfigInvalidError",
data: { message: expect.stringContaining('bad file reference: "{file:username.txt}"') },
})
}
if (!invalidate) expect(yield* locations.contextEffectOption(ref).pipe(Effect.scoped)).toEqual(Option.none())
if (failure === "file") {
@@ -123,10 +109,6 @@ describe("LocationServiceMap", () => {
yield* Effect.promise(() => fs.mkdir(directory))
}
if (failure === "permissions") yield* Effect.promise(() => fs.chmod(directory, 0o755))
if (failure === "config reference") {
yield* Effect.promise(() => fs.rm(path.join(directory, "username.txt"), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(path.join(directory, "username.txt"), "test-user"))
}
expect((yield* Effect.promise(() => fs.stat(directory))).isDirectory()).toBe(true)
if (invalidate) yield* locations.invalidate(ref)
const repaired = yield* Effect.exit(load)
@@ -137,8 +119,8 @@ describe("LocationServiceMap", () => {
}
}
for (const failure of ["file", "missing", "config reference"] as const) {
// A file-path Location boots on Windows; use the missing config reference there.
for (const failure of ["file", "missing"] as const) {
// A file-path Location boots on Windows; the missing directory covers it there.
const test = failure === "file" && process.platform === "win32" ? it.live.skip : it.live
test(`keeps the repaired graph after concurrent ${failure} failures release`, () =>
Effect.gen(function* () {
@@ -147,12 +129,6 @@ describe("LocationServiceMap", () => {
const ref = Location.Ref.make({ directory: AbsolutePath.make(directory) })
const locations = yield* LocationServiceMap.Service
if (failure === "file") yield* Effect.promise(() => fs.writeFile(directory, "file"))
if (failure === "config reference") {
yield* Effect.promise(() => fs.mkdir(path.join(directory, "username.txt"), { recursive: true }))
yield* Effect.promise(() =>
fs.writeFile(path.join(directory, "opencode.json"), JSON.stringify({ username: "{file:username.txt}" })),
)
}
const scopes = yield* Effect.forEach(Array.from({ length: 8 }), () =>
Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void)),
@@ -164,11 +140,7 @@ describe("LocationServiceMap", () => {
)
expect(failures.every(Exit.isFailure)).toBe(true)
if (failure === "file") yield* Effect.promise(() => fs.rm(directory))
if (failure !== "config reference") yield* Effect.promise(() => fs.mkdir(directory))
if (failure === "config reference") {
yield* Effect.promise(() => fs.rm(path.join(directory, "username.txt"), { recursive: true }))
yield* Effect.promise(() => fs.writeFile(path.join(directory, "username.txt"), "test-user"))
}
yield* Effect.promise(() => fs.mkdir(directory))
const repaired = yield* locations.contextEffect(ref)
yield* Effect.forEach(scopes, (scope) => Scope.close(scope, Exit.void))
+2 -2
View File
@@ -61,7 +61,7 @@ const fixtureSnapshot = [
family: undefined,
package: undefined,
settings: { provider: "acme" },
capabilities: { tools: true, input: [], output: [] },
capabilities: { tools: true, input: [], output: [], temperature: true },
variants: [],
time: { released: Date.parse("2026-01-01") },
cost: [
@@ -123,7 +123,7 @@ const fixture2Snapshot = [
family: undefined,
package: undefined,
settings: { provider: "beta" },
capabilities: { tools: false, input: [], output: [] },
capabilities: { tools: false, input: [], output: [], temperature: false },
variants: [],
time: { released: Date.parse("2026-02-01") },
cost: [
@@ -583,6 +583,58 @@ describe("OpencodePlugin", () => {
),
)
it.live("builds Console model variants from its reasoning and applies its release date", () =>
Effect.acquireUseRelease(
Effect.sync(() =>
Bun.serve({
port: 0,
fetch: () =>
Response.json({
providers: {
remote: {
name: "Remote",
package: "aisdk:@ai-sdk/openai",
models: {
reasoner: {
releaseDate: "2026-02-03",
capabilities: { reasoning: { supported: true, effort: ["default", "low", "high"] } },
variants: [{ id: "high", headers: { "x-tier": "high" } }],
},
},
},
},
}),
}),
),
(server) =>
Effect.gen(function* () {
const credentials = yield* Credential.Service
const models = yield* Model.Service
yield* credentials.create({
integrationID: Integration.ID.make("opencode"),
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
})
yield* addPlugin()
const reasoner = required(yield* models.get(Provider.ID.make("remote"), Model.ID.make("reasoner")))
expect(reasoner.time.released).toBe(Date.UTC(2026, 1, 3))
expect(reasoner.variants).toEqual([
{
id: Model.VariantID.make("low"),
settings: { reasoningEffort: "low", reasoningSummary: "auto", include: ["reasoning.encrypted_content"] },
},
{
id: Model.VariantID.make("high"),
settings: { reasoningEffort: "high", reasoningSummary: "auto", include: ["reasoning.encrypted_content"] },
headers: { "x-tier": "high" },
},
])
}),
(server) => Effect.promise(() => server.stop(true)),
),
)
it.effect("refreshes hosted search with Console config, retains it on failure, and skips unchanged snapshots", () =>
Effect.acquireUseRelease(
Effect.sync(() => {
@@ -28,7 +28,7 @@ import { advance } from "../lib/clock"
import { testEffect } from "../lib/effect"
// Real Location boot with plugin-directory discovery, so local plugin files are loaded and reloaded.
setDefaultTimeout(15_000)
setDefaultTimeout(30_000)
// Package resolution can be held open so overlapping activations become observable.
const npm = {
+29 -21
View File
@@ -10,12 +10,19 @@ import { LayerNode } from "@opencode/util/effect/layer-node"
import { AppProcess } from "@opencode/util/process"
import { testEffect } from "../lib/effect"
// Every test spawns a real child, so all of them use the live clock. The spawner's 1s post-exit capture deadline
// never fires under TestClock, and a child whose close event arrives late would hang until the test timeout.
const it = testEffect(LayerNode.compile(AppProcess.node))
const NODE = process.execPath
const MISSING_CWD = path.join(tmpdir(), `opencode-missing-cwd-${randomUUID()}`)
const cmd = (...args: string[]) => ChildProcess.make(NODE, args)
// The child registers its SIGTERM handler before it announces readiness, and publishes the pid with a rename, so a
// test that signals it right after reading "ready" never races the handler or reads a partly written file.
const settleOnSigterm = (ready: string, settled: string) =>
`const fs=require('fs');process.on('SIGTERM',()=>{fs.writeFileSync(${JSON.stringify(settled)},'settled');process.exit(0)});fs.writeFileSync(${JSON.stringify(ready + ".tmp")},String(process.pid));fs.renameSync(${JSON.stringify(ready + ".tmp")},${JSON.stringify(ready)});setInterval(()=>{},60000)`
const waitForFile = (file: string) =>
Effect.promise(async () => {
while (true) {
@@ -31,7 +38,7 @@ const waitForFile = (file: string) =>
describe("AppProcess", () => {
describe("run", () => {
it.effect(
it.live(
"captures stdout and exit code zero",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -54,14 +61,15 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"captures stdout and stderr in emission order",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
const script = [
'process.stdout.write("out 1\\n")',
'setTimeout(() => process.stderr.write("err 1\\n"), 10)',
'setTimeout(() => process.stdout.write("out 2\\n"), 20)',
// Gaps wide enough that a busy test machine still reads each write before the next one.
'setTimeout(() => process.stderr.write("err 1\\n"), 100)',
'setTimeout(() => process.stdout.write("out 2\\n"), 200)',
].join(";")
const result = yield* svc.run(cmd("-e", script), { combineOutput: true })
expect(result.output?.toString("utf8")).toBe("out 1\nerr 1\nout 2\n")
@@ -70,7 +78,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"non-zero exit returns RunResult; caller can require success",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -79,7 +87,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"requireSuccess fails on non-zero exit",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -92,7 +100,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"requireSuccess succeeds on exit 0",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -101,7 +109,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"requireExitIn allowlists multiple exit codes",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -116,7 +124,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"truncates stdout when maxOutputBytes is set",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -129,7 +137,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"truncates stderr when maxErrorBytes is set",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -142,7 +150,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"result includes command description",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -159,7 +167,7 @@ describe("AppProcess", () => {
(directory) => {
const ready = path.join(directory, "ready")
const settled = path.join(directory, "settled")
const script = `const fs=require('fs');fs.writeFileSync(${JSON.stringify(ready)},String(process.pid));process.on('SIGTERM',()=>{fs.writeFileSync(${JSON.stringify(settled)},'settled');process.exit(0)});setInterval(()=>{},60000)`
const script = settleOnSigterm(ready, settled)
return Effect.gen(function* () {
const svc = yield* AppProcess.Service
const exit = yield* Effect.exit(svc.run(cmd("-e", script), { timeout: "250 millis" }))
@@ -180,7 +188,7 @@ describe("AppProcess", () => {
(directory) => {
const ready = path.join(directory, "ready")
const settled = path.join(directory, "settled")
const script = `const fs=require('fs');fs.writeFileSync(${JSON.stringify(ready)},String(process.pid));process.on('SIGTERM',()=>{fs.writeFileSync(${JSON.stringify(settled)},'settled');process.exit(0)});setInterval(()=>{},60000)`
const script = settleOnSigterm(ready, settled)
return Effect.gen(function* () {
const svc = yield* AppProcess.Service
const fiber = yield* svc.run(cmd("-e", script)).pipe(Effect.forkChild)
@@ -197,7 +205,7 @@ describe("AppProcess", () => {
})
describe("inherited platform methods", () => {
it.effect(
it.live(
"string returns stdout as string",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -206,7 +214,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"lines returns the platform's array of lines",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -219,7 +227,7 @@ describe("AppProcess", () => {
describe("run with stdin option", () => {
const echoStdin = "process.stdin.on('data', c => process.stdout.write(c))"
it.effect(
it.live(
"feeds a string to stdin and returns it on stdout",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -229,7 +237,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"feeds a Uint8Array to stdin",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -240,7 +248,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"feeds a Stream of Uint8Array chunks to stdin",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -252,7 +260,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"completes correctly with empty input",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -262,7 +270,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"carries existing Command options like env",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
@@ -275,7 +283,7 @@ describe("AppProcess", () => {
}),
)
it.effect(
it.live(
"carries existing Command options like cwd",
Effect.gen(function* () {
const svc = yield* AppProcess.Service
+2 -5
View File
@@ -12,6 +12,7 @@ import { ProjectSchema } from "@opencode/core/project/schema"
import { ProjectTable } from "@opencode/core/project/sql"
import { AbsolutePath } from "@opencode/core/schema"
import { Hash } from "@opencode/util/hash"
import { initGit } from "./fixture/git"
import { tmpdir } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
@@ -326,11 +327,7 @@ function real(value: string) {
}
async function initRepo(dir: string, opts?: { commit?: boolean; remote?: string }) {
await $`git init`.cwd(dir).quiet()
await $`git config core.fsmonitor false`.cwd(dir).quiet()
await $`git config commit.gpgsign false`.cwd(dir).quiet()
await $`git config user.email test@opencode.test`.cwd(dir).quiet()
await $`git config user.name Test`.cwd(dir).quiet()
await initGit(dir)
if (opts?.commit) await $`git commit --allow-empty -m root`.cwd(dir).quiet()
if (opts?.remote) await $`git remote add origin ${opts.remote}`.cwd(dir).quiet()
}
+2 -1
View File
@@ -8,7 +8,8 @@ describe("Provider", () => {
const providers = path.join(import.meta.dir, "../../ai/src/providers")
const entrypoints = await Promise.all(
Array.from(new Bun.Glob("**/*.ts").scanSync(providers)).map(async (file) => {
const specifier = `@opencode/ai/providers/${file.replace(/\.ts$/, "")}`
// Bun.Glob yields native separators, and package specifiers always use "/".
const specifier = `@opencode/ai/providers/${file.replace(/\.ts$/, "").replaceAll(path.sep, "/")}`
const module = await import(specifier)
return typeof module.model === "function" ? specifier : undefined
}),
+1 -1
View File
@@ -16,7 +16,7 @@ import { testEffect } from "./lib/effect"
const it = testEffect(Layer.empty)
// Cold Git setup and cloning can exceed Bun's five-second default on Windows.
setDefaultTimeout(15_000)
setDefaultTimeout(30_000)
describe("RepositoryCache", () => {
it.live("persists the daily throttle across cache recreation and serializes competing refreshes", () =>
@@ -18,7 +18,7 @@ import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
// Real Location boot with plugin discovery, so the first request races the initial plugin activation.
setDefaultTimeout(15_000)
setDefaultTimeout(30_000)
const it = testEffect(
AppNodeBuilder.build(
+3 -8
View File
@@ -36,6 +36,7 @@ import { Workspace } from "@opencode/core/workspace"
import { Expected } from "./lib/session-message"
import { testEffect } from "./lib/effect"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import { initGit } from "./fixture/git"
import { offlineModels } from "./fixture/models"
import { promptLocationNode } from "./fixture/prompt-location"
import { globalProjectNode } from "./lib/project"
@@ -158,11 +159,7 @@ describe("Session.create", () => {
.pipe(Effect.orDie)
if (!before) return yield* Effect.die(new Error("created session not found"))
yield* Effect.promise(async () => {
await $`git init -q`.cwd(directory)
await $`git config user.email test@example.com`.cwd(directory)
await $`git config user.name Test`.cwd(directory)
})
yield* Effect.promise(() => initGit(directory))
const unborn = yield* projects.resolve(ref.directory)
const unbornRoot = yield* session.get(created.id)
const unbornNested = yield* session.get(child.id)
@@ -269,9 +266,7 @@ describe("Session.create", () => {
yield* Effect.promise(async () => {
for (const root of [nested, outer]) {
await $`git init -q`.cwd(root)
await $`git config user.email test@example.com`.cwd(root)
await $`git config user.name Test`.cwd(root)
await initGit(root)
await $`git commit --allow-empty -qm initial`.cwd(root)
}
})
+1 -5
View File
@@ -293,11 +293,7 @@ describe("Session.move", () => {
replacements: [
...bindings,
...(broken
? [
Config.node.replace(
Config.configured({ project: false, global: false, content: config }),
),
]
? [Config.node.replace(Layer.effect(Config.Service, Effect.die("broken config")))]
: []),
],
}),
+1 -1
View File
@@ -19,7 +19,7 @@ import { tmpdirScoped } from "./fixture/tmpdir"
import { testEffect } from "./lib/effect"
// Every test boots a real Location, so shell start waits for cold plugin activation before spawning.
setDefaultTimeout(15_000)
setDefaultTimeout(30_000)
class ExecutionControl extends Context.Service<
ExecutionControl,
+17 -3
View File
@@ -2,7 +2,7 @@ import { $ } from "bun"
import { describe, expect } from "bun:test"
import fs from "fs/promises"
import path from "path"
import { Deferred, Effect, Fiber, Layer } from "effect"
import { Deferred, Effect, Fiber, Layer, Logger } from "effect"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Git } from "@opencode/core/git"
import { Global } from "@opencode/util/global"
@@ -185,8 +185,22 @@ describe("Snapshot", () => {
),
)
}).pipe(Effect.provide(snapshotLayer(tmp.path, project)))
const results = yield* Effect.all([writer(0), writer(1), writer(2)], { concurrency: "unbounded" })
expect(results.flat().every((tree) => tree !== undefined)).toBe(true)
// capture() reports a failure only as a logged warning, so collect warnings to show the cause on failure.
const warnings: string[] = []
const results = yield* Effect.all([writer(0), writer(1), writer(2)], { concurrency: "unbounded" }).pipe(
Effect.provide(
Logger.layer([
Logger.make((entry) => {
if (entry.logLevel === "Warn" || entry.logLevel === "Error")
warnings.push(Bun.inspect(entry.message, { depth: 8 }))
}),
]),
),
)
expect(
results.flat().every((tree) => tree !== undefined),
warnings.join("\n"),
).toBe(true)
}),
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
),
+12
View File
@@ -544,3 +544,15 @@ test("spells Google Interactions variants as thinking levels", () => {
{ id: "high", settings: { thinkingLevel: "high", thinkingSummaries: "auto" } },
])
})
test("reads models.dev v2 reasoning as variant support", () => {
expect(Variant.supports({ supported: false })).toEqual([])
expect(Variant.supports({ supported: true })).toEqual([])
expect(
Variant.supports({ supported: true, toggle: true, effort: ["default", "low"], budget: { min: 1024, max: 8000 } }),
).toEqual([
{ type: "toggle" },
{ type: "effort", values: ["low"] },
{ type: "budget_tokens", min: 1024, max: 8000 },
])
})
+3 -10
View File
@@ -17,6 +17,7 @@ import { VcsGitPlugin } from "@opencode/core/plugin/vcs/git"
import type { VcsDefinition, VcsDiffInput } from "@opencode/plugin/effect/vcs"
import { FileSystem } from "@opencode/schema/filesystem"
import { VcsEvent } from "@opencode/schema/vcs-event"
import { initGit } from "./fixture/git"
import { location } from "./fixture/location"
import { tmpdir } from "./fixture/tmpdir"
import { it, testEffect } from "./lib/effect"
@@ -61,7 +62,7 @@ const withTmp = <A, E, R>(f: (directory: string) => Effect.Effect<A, E, R>) =>
const withGit = <A, E, R>(f: (directory: string) => Effect.Effect<A, E, R>, input: { scope?: string } = {}) =>
withTmp((directory) =>
Effect.promise(async () => {
await initRepo(directory)
await initGit(directory, "-b", "main")
if (input.scope) await fs.mkdir(path.join(directory, input.scope), { recursive: true })
}).pipe(
Effect.andThen(
@@ -78,14 +79,6 @@ const withGit = <A, E, R>(f: (directory: string) => Effect.Effect<A, E, R>, inpu
),
)
async function initRepo(directory: string) {
await $`git init -b main`.cwd(directory).quiet()
await $`git config core.fsmonitor false`.cwd(directory).quiet()
await $`git config commit.gpgsign false`.cwd(directory).quiet()
await $`git config user.email test@opencode.test`.cwd(directory).quiet()
await $`git config user.name Test`.cwd(directory).quiet()
}
async function commitAll(directory: string, message: string) {
await $`git add -A`.cwd(directory).quiet()
await $`git commit -m ${message}`.cwd(directory).quiet()
@@ -586,7 +579,7 @@ describe("Vcs", () => {
Effect.gen(function* () {
const count = 40
yield* Effect.promise(async () => {
await initRepo(directory)
await initGit(directory, "-b", "main")
await fs.writeFile(path.join(directory, "keep.txt"), "one\n")
await fs.writeFile(path.join(directory, ".gitignore"), "*.log\n")
await commitAll(directory, "initial")
+7
View File
@@ -40,6 +40,13 @@ CLI preparation uses these channel rules:
default. `bun dev --download-server <version>` instead downloads that CLI version for local development. Neither path
requires `OPENCODE_CLI_DIST` or runs the production prebuild.
## Beta channel
Every push to the `beta` branch publishes OpenCode Beta (`ai.opencode.desktop.beta`) as version `0.0.0-beta-<run>` to
the `beta` update channel. Beta publishes only the desktop app and `beta.opencode.ai`; the CLI and SDK packages ship
from `dev`. Install it from `https://opencode.ai/download/beta/<platform>`, for example `darwin-aarch64-dmg` or
`windows-x64-nsis`. Installed builds update in place on every platform.
## Startup benchmark
`bun run bench:startup` measures a **packaged** build from process spawn to the restored tab being ready and the
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@opencode/desktop",
"private": true,
"version": "2.0.30",
"version": "2.0.31",
"type": "module",
"license": "MIT",
"homepage": "https://opencode.ai",
@@ -1,270 +0,0 @@
#!/usr/bin/env bun
import { $ } from "bun"
import path from "node:path"
import { parseArgs } from "node:util"
const { values } = parseArgs({
args: Bun.argv.slice(2),
options: {
"dry-run": { type: "boolean", default: false },
},
})
const dryRun = values["dry-run"]
const repo = process.env.GH_REPO
if (!repo) throw new Error("GH_REPO is required")
const releaseId = process.env.OPENCODE_RELEASE
if (!releaseId) throw new Error("OPENCODE_RELEASE is required")
const version = process.env.OPENCODE_VERSION
if (!version) throw new Error("OPENCODE_VERSION is required")
const dir = process.env.LATEST_YML_DIR
if (!dir) throw new Error("LATEST_YML_DIR is required")
const root = dir
const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN
if (!token) throw new Error("GH_TOKEN or GITHUB_TOKEN is required")
const rel = await fetch(`https://api.github.com/repos/${repo}/releases/${releaseId}`, {
headers: {
Authorization: `token ${token}`,
Accept: "application/vnd.github+json",
},
})
if (!rel.ok) {
throw new Error(`Failed to fetch release: ${rel.status} ${rel.statusText}`)
}
type Asset = {
name: string
url: string
}
type Release = {
assets?: Asset[]
}
const assets = ((await rel.json()) as Release).assets ?? []
const amap = new Map(assets.map((item) => [item.name, item]))
type Item = {
url: string
}
type Yml = {
version: string
files: Item[]
}
function parse(text: string): Yml {
const lines = text.split("\n")
let version = ""
const files: Item[] = []
let url = ""
const flush = () => {
if (!url) return
files.push({ url })
url = ""
}
for (const line of lines) {
const trim = line.trim()
if (line.startsWith("version:")) {
version = line.slice("version:".length).trim()
continue
}
if (trim.startsWith("- url:")) {
flush()
url = trim.slice("- url:".length).trim()
continue
}
const indented = line.startsWith(" ") || line.startsWith("\t")
if (!indented) flush()
}
flush()
return { version, files }
}
async function read(sub: string, file: string) {
const item = Bun.file(path.join(root, sub, file))
if (!(await item.exists())) return undefined
return parse(await item.text())
}
function pick(list: Item[], exts: string[]) {
for (const ext of exts) {
const found = list.find((item) => item.url.split("?")[0]?.toLowerCase().endsWith(ext))
if (found) return found.url
}
}
function link(raw: string) {
if (raw.startsWith("https://") || raw.startsWith("http://")) return raw
return `https://github.com/${repo}/releases/download/v${version}/${raw}`
}
async function sign(url: string, key: string) {
const name = decodeURIComponent(new URL(url).pathname.split("/").pop() ?? key)
const asset = amap.get(name)
const res = await fetch(asset?.url ?? url, {
headers: {
Authorization: `token ${token}`,
...(asset ? { Accept: "application/octet-stream" } : {}),
},
})
if (!res.ok) {
throw new Error(`Failed to fetch file ${name}: ${res.status} ${res.statusText} (${asset?.url ?? url})`)
}
const tmp = process.env.RUNNER_TEMP ?? "/tmp"
const file = path.join(tmp, name)
await Bun.write(file, await res.arrayBuffer())
await $`bunx @tauri-apps/cli signer sign ${file}`
const sigFile = Bun.file(`${file}.sig`)
if (!(await sigFile.exists())) throw new Error(`Signature file not found for ${name}`)
return (await sigFile.text()).trim()
}
const add = async (data: Record<string, { url: string; signature: string }>, key: string, raw: string | undefined) => {
if (!raw) return
if (data[key]) return
const url = link(raw)
data[key] = { url, signature: await sign(url, key) }
}
const alias = (data: Record<string, { url: string; signature: string }>, key: string, src: string) => {
if (data[key]) return
if (!data[src]) return
data[key] = data[src]
}
const winx = await read("latest-yml-x86_64-pc-windows-msvc", "latest.yml")
const wina = await read("latest-yml-aarch64-pc-windows-msvc", "latest.yml")
const macx = await read("latest-yml-x86_64-apple-darwin", "latest-mac.yml")
const maca = await read("latest-yml-aarch64-apple-darwin", "latest-mac.yml")
const linx = await read("latest-yml-x86_64-unknown-linux-gnu", "latest-linux.yml")
const lina = await read("latest-yml-aarch64-unknown-linux-gnu", "latest-linux-arm64.yml")
const yver = winx?.version ?? wina?.version ?? macx?.version ?? maca?.version ?? linx?.version ?? lina?.version
if (yver && yver !== version) throw new Error(`latest.yml version mismatch: expected ${version}, got ${yver}`)
const out: Record<string, { url: string; signature: string }> = {}
const winxexe = pick(winx?.files ?? [], [".exe"])
const winaexe = pick(wina?.files ?? [], [".exe"])
const macxTarGz = "opencode-desktop-mac-x64.app.tar.gz"
const macaTarGz = "opencode-desktop-mac-arm64.app.tar.gz"
const linxDeb = pick(linx?.files ?? [], [".deb"])
const linxRpm = pick(linx?.files ?? [], [".rpm"])
const linxAppImage = pick(linx?.files ?? [], [".appimage"])
const linaDeb = pick(lina?.files ?? [], [".deb"])
const linaRpm = pick(lina?.files ?? [], [".rpm"])
const linaAppImage = pick(lina?.files ?? [], [".appimage"])
await add(out, "windows-x86_64-nsis", winxexe)
await add(out, "windows-aarch64-nsis", winaexe)
await add(out, "darwin-x86_64-app", macxTarGz)
await add(out, "darwin-aarch64-app", macaTarGz)
await add(out, "linux-x86_64-deb", linxDeb)
await add(out, "linux-x86_64-rpm", linxRpm)
await add(out, "linux-x86_64-appimage", linxAppImage)
await add(out, "linux-aarch64-deb", linaDeb)
await add(out, "linux-aarch64-rpm", linaRpm)
await add(out, "linux-aarch64-appimage", linaAppImage)
alias(out, "windows-x86_64", "windows-x86_64-nsis")
alias(out, "windows-aarch64", "windows-aarch64-nsis")
alias(out, "darwin-x86_64", "darwin-x86_64-app")
alias(out, "darwin-aarch64", "darwin-aarch64-app")
alias(out, "linux-x86_64", "linux-x86_64-deb")
alias(out, "linux-aarch64", "linux-aarch64-deb")
const platforms = Object.fromEntries(
Object.keys(out)
.sort()
.map((key) => [key, out[key]]),
)
if (!Object.keys(platforms).length) throw new Error("No updater files found in latest.yml artifacts")
const data = {
version,
notes: "",
pub_date: new Date().toISOString(),
platforms,
}
const tmp = process.env.RUNNER_TEMP ?? "/tmp"
const file = path.join(tmp, "latest.json")
await Bun.write(file, JSON.stringify(data, null, 2))
const tag = `v${version}`
if (dryRun) {
console.log(`dry-run: wrote latest.json for ${tag} to ${file}`)
process.exit(0)
}
await $`gh release upload ${tag} ${file} --clobber --repo ${repo}`
console.log(`finalized latest.json for ${tag}`)
@@ -1,142 +0,0 @@
#!/usr/bin/env bun
import { $ } from "bun"
import path from "path"
const dir = process.env.LATEST_YML_DIR!
if (!dir) throw new Error("LATEST_YML_DIR is required")
const repo = process.env.GH_REPO
if (!repo) throw new Error("GH_REPO is required")
const version = process.env.OPENCODE_VERSION
if (!version) throw new Error("OPENCODE_VERSION is required")
type FileEntry = {
url: string
sha512: string
size: number
blockMapSize?: number
}
type LatestYml = {
version: string
files: FileEntry[]
releaseDate: string
}
function parse(content: string): LatestYml {
const lines = content.split("\n")
let version = ""
let releaseDate = ""
const files: FileEntry[] = []
let current: Partial<FileEntry> | undefined
const flush = () => {
if (current?.url && current.sha512 && current.size) files.push(current as FileEntry)
current = undefined
}
for (const line of lines) {
const indented = line.startsWith(" ") || line.startsWith(" -")
if (line.startsWith("version:")) version = line.slice("version:".length).trim()
else if (line.startsWith("releaseDate:"))
releaseDate = line.slice("releaseDate:".length).trim().replace(/^'|'$/g, "")
else if (line.trim().startsWith("- url:")) {
flush()
current = { url: line.trim().slice("- url:".length).trim() }
} else if (indented && current && line.trim().startsWith("sha512:"))
current.sha512 = line.trim().slice("sha512:".length).trim()
else if (indented && current && line.trim().startsWith("size:"))
current.size = Number(line.trim().slice("size:".length).trim())
else if (indented && current && line.trim().startsWith("blockMapSize:"))
current.blockMapSize = Number(line.trim().slice("blockMapSize:".length).trim())
else if (!indented && current) flush()
}
flush()
return { version, files, releaseDate }
}
function serialize(data: LatestYml) {
const lines = [`version: ${data.version}`, "files:"]
for (const file of data.files) {
lines.push(` - url: ${file.url}`)
lines.push(` sha512: ${file.sha512}`)
lines.push(` size: ${file.size}`)
if (file.blockMapSize) lines.push(` blockMapSize: ${file.blockMapSize}`)
}
lines.push(`releaseDate: '${data.releaseDate}'`)
return lines.join("\n") + "\n"
}
async function read(subdir: string, filename: string): Promise<LatestYml | undefined> {
const file = Bun.file(path.join(dir, subdir, filename))
if (!(await file.exists())) return undefined
return parse(await file.text())
}
const output: Record<string, string> = {}
// Windows: merge arm64 + x64 into single file
const winX64 = await read("latest-yml-x86_64-pc-windows-msvc", "latest.yml")
const winArm64 = await read("latest-yml-aarch64-pc-windows-msvc", "latest.yml")
if (winX64 || winArm64) {
const base = winArm64 ?? winX64!
output["latest.yml"] = serialize({
version: base.version,
files: [...(winArm64?.files ?? []), ...(winX64?.files ?? [])],
releaseDate: base.releaseDate,
})
}
// Linux x64: pass through
const linuxX64 = await read("latest-yml-x86_64-unknown-linux-gnu", "latest-linux.yml")
if (linuxX64) output["latest-linux.yml"] = serialize(linuxX64)
// Linux arm64: pass through
const linuxArm64 = await read("latest-yml-aarch64-unknown-linux-gnu", "latest-linux-arm64.yml")
if (linuxArm64) output["latest-linux-arm64.yml"] = serialize(linuxArm64)
// macOS: merge arm64 + x64 into single file
const macX64 = await read("latest-yml-x86_64-apple-darwin", "latest-mac.yml")
const macArm64 = await read("latest-yml-aarch64-apple-darwin", "latest-mac.yml")
if (macX64 || macArm64) {
const base = macArm64 ?? macX64!
output["latest-mac.yml"] = serialize({
version: base.version,
files: [...(macArm64?.files ?? []), ...(macX64?.files ?? [])],
releaseDate: base.releaseDate,
})
}
// Upload to release
const tag = `v${version}`
const tmp = process.env.RUNNER_TEMP ?? "/tmp"
for (const [filename, content] of Object.entries(output)) {
const filepath = path.join(tmp, filename)
await Bun.write(filepath, content)
await $`gh release upload ${tag} ${filepath} --clobber --repo ${repo}`
console.log(`uploaded ${filename}`)
}
console.log("finalized latest yml files")
@@ -1,61 +0,0 @@
import { afterEach, describe, expect, test } from "bun:test"
import { focusWindow, showWindow } from "../windows/focus"
const originalPlatform = process.platform
afterEach(() => {
Object.defineProperty(process, "platform", { value: originalPlatform })
})
function fakeWindow(minimized: boolean, events: string[]) {
return {
isMinimized: () => minimized,
restore: () => {
events.push("win.restore")
},
show: () => {
events.push("win.show")
},
focus: () => {
events.push("win.focus")
},
}
}
describe("window show and focus handlers", () => {
test.each([
{ minimized: false, expected: ["win.show"] },
{ minimized: true, expected: ["win.restore", "win.show"] },
])("showWindow with minimized=$minimized restores before showing", ({ minimized, expected }) => {
const events: string[] = []
showWindow(fakeWindow(minimized, events))
expect(events).toEqual(expected)
showWindow(null)
expect(events).toEqual(expected)
})
test.each([
{ platform: "darwin" as const, minimized: false, expected: ["app.focus:steal", "win.focus"] },
{ platform: "darwin" as const, minimized: true, expected: ["win.restore", "app.focus:steal", "win.focus"] },
{ platform: "linux" as const, minimized: false, expected: ["win.focus"] },
{ platform: "linux" as const, minimized: true, expected: ["win.restore", "win.focus"] },
{ platform: "win32" as const, minimized: true, expected: ["win.restore", "win.focus"] },
])(
"focusWindow on $platform with minimized=$minimized restores and activates the app before focusing",
({ platform, minimized, expected }) => {
Object.defineProperty(process, "platform", { value: platform })
const events: string[] = []
const app = {
focus: (options?: { steal: boolean }) => {
events.push(options?.steal ? "app.focus:steal" : "app.focus")
},
}
focusWindow(fakeWindow(minimized, events), app)
expect(events).toEqual(expected)
focusWindow(null, app)
expect(events).toEqual(expected)
},
)
})
@@ -1,9 +1,8 @@
import { app, BrowserWindow } from "electron"
import { BrowserWindow } from "electron"
import { Effect } from "effect"
import { WindowRpcs } from "../../shared/ipc-rpc"
import { IpcPortHandoff } from "../ipc-transport"
import { getPinchZoomEnabled, setPinchZoomEnabled, setTitlebar, setWindowThemeReady, updateTitlebar } from "../windows"
import { focusWindow, showWindow } from "../windows/focus"
import { sender } from "./context"
export const windowHandlers = WindowRpcs.toLayer(
@@ -23,9 +22,9 @@ export const windowHandlers = WindowRpcs.toLayer(
WindowGetFullscreen: (_args, context) =>
Effect.sync(() => BrowserWindow.fromWebContents(sender(handoff, context))?.isFullScreen() ?? false),
WindowSetFocus: (_args, context) =>
Effect.sync(() => focusWindow(BrowserWindow.fromWebContents(sender(handoff, context)), app)),
Effect.sync(() => BrowserWindow.fromWebContents(sender(handoff, context))?.focus()),
WindowShow: (_args, context) =>
Effect.sync(() => showWindow(BrowserWindow.fromWebContents(sender(handoff, context)))),
Effect.sync(() => BrowserWindow.fromWebContents(sender(handoff, context))?.show()),
WindowGetZoomFactor: (_args, context) => Effect.sync(() => sender(handoff, context).getZoomFactor()),
WindowSetZoomFactor: ({ factor }, context) =>
Effect.sync(() => {
@@ -1,22 +0,0 @@
import type { App, BrowserWindow } from "electron"
export type FocusableWindow = Pick<BrowserWindow, "isMinimized" | "restore" | "show" | "focus">
export function showWindow(win: Pick<FocusableWindow, "isMinimized" | "restore" | "show"> | null | undefined) {
if (!win) return
if (win.isMinimized()) win.restore()
win.show()
}
export function focusWindow(
win: Pick<FocusableWindow, "isMinimized" | "restore" | "focus"> | null | undefined,
app: Pick<App, "focus">,
) {
if (!win) return
if (win.isMinimized()) win.restore()
if (process.platform === "darwin") app.focus({ steal: true })
win.focus()
}
@@ -1,129 +0,0 @@
import { afterEach, describe, expect, test } from "bun:test"
import { createDesktopNotify } from "./notifications"
const originalNotification = globalThis.Notification
const created: FakeNotification[] = []
const events: string[] = []
class FakeNotification extends EventTarget implements Notification {
static readonly permission: NotificationPermission = "granted"
static async requestPermission(): Promise<NotificationPermission> {
return "granted"
}
onclick: ((this: Notification, ev: Event) => void) | null = null
onclose: ((this: Notification, ev: Event) => void) | null = null
onerror: ((this: Notification, ev: Event) => void) | null = null
onshow: ((this: Notification, ev: Event) => void) | null = null
readonly body: string
readonly data = null
readonly dir: NotificationDirection = "auto"
readonly icon: string
readonly lang = ""
readonly silent: boolean | null
readonly tag = ""
readonly title: string
constructor(title: string, options?: NotificationOptions) {
super()
this.title = title
this.body = options?.body ?? ""
this.icon = options?.icon ?? ""
this.silent = options?.silent ?? null
events.push(`created:${title}:${this.body}`)
created.push(this)
}
close() {
events.push("notification.close")
this.onclose?.call(this, new Event("close"))
}
}
afterEach(() => {
created.length = 0
events.length = 0
globalThis.Notification = originalNotification
})
describe("desktop notifications", () => {
test("shows and focuses the window on click, runs the callback, and closes the notification", async () => {
globalThis.Notification = FakeNotification
const notify = createDesktopNotify({
getWindowFocused: async () => false,
showWindow: async () => {
events.push("api.showWindow")
},
setWindowFocus: async () => {
events.push("api.setWindowFocus")
},
})
await notify("Response ready", "Refactor auth flow", () => {
events.push("session.select")
})
const notification = created[0]
expect(notification).toBeDefined()
notification?.onclick?.call(notification, new Event("click"))
expect(events).toEqual([
"created:Response ready:Refactor auth flow",
"api.showWindow",
"api.setWindowFocus",
"session.select",
"notification.close",
])
expect(notification?.onclick).toBeNull()
expect(notification?.onclose).toBeNull()
expect(notification?.onerror).toBeNull()
})
test.each([{ event: "close" as const }, { event: "error" as const }])(
"releases the Notification handlers when $event fires without a click",
async ({ event }) => {
globalThis.Notification = FakeNotification
const notify = createDesktopNotify({
getWindowFocused: async () => false,
showWindow: async () => {},
setWindowFocus: async () => {},
})
await notify("Session error")
const notification = created[0]
expect(notification).toBeDefined()
if (event === "close") {
notification?.onclose?.call(notification, new Event("close"))
} else {
notification?.onerror?.call(notification, new Event("error"))
}
expect(notification?.onclick).toBeNull()
expect(notification?.onclose).toBeNull()
expect(notification?.onerror).toBeNull()
},
)
test("suppresses desktop notifications while the window is already focused", async () => {
globalThis.Notification = FakeNotification
const notify = createDesktopNotify({
getWindowFocused: async () => true,
showWindow: async () => {},
setWindowFocus: async () => {},
})
await notify("Response ready", "Active session")
expect(events).toEqual([])
expect(created).toEqual([])
})
})
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff. Show more