mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-15 07:48:24 -04:00
Compare commits
87 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad741cbea0 | |||
| cbc40a5981 | |||
| b9b210a864 | |||
| d473b7e971 | |||
| f5783c4313 | |||
| 9439a5647e | |||
| 2bfe81ee5c | |||
| fcf1bb010c | |||
| 08b6d9c6dc | |||
| 0293a8bb80 | |||
| 850dbb93eb | |||
| 48e867ee20 | |||
| b5ebc541b9 | |||
| bd7a4cec90 | |||
| 63af295a17 | |||
| 04954a9620 | |||
| fb63fd79a3 | |||
| 2e04b66eab | |||
| f0b7c8c374 | |||
| be6f59035a | |||
| 27ab51f490 | |||
| bca723e8fe | |||
| 1ac39718d8 | |||
| 190319fb56 | |||
| 3154f0a61c | |||
| 0b686b8178 | |||
| 4cba56171b | |||
| 66342acd31 | |||
| 88dae67549 | |||
| 0ec42582f3 | |||
| 4f82248a68 | |||
| 5e069aab97 | |||
| 5325b2ec99 | |||
| 2a98920922 | |||
| 5ea92ea6cb | |||
| a18528a7ee | |||
| ced125a974 | |||
| 655fe20beb | |||
| dd0c258e23 | |||
| 791e27d289 | |||
| fac0aec69f | |||
| ca26e639f6 | |||
| 0b5d54f2cb | |||
| 1b408cf06b | |||
| 8e102d19ed | |||
| 721b2406e9 | |||
| 4a6a18cd79 | |||
| c10b5880cc | |||
| e6bf83084c | |||
| 6722ee22ee | |||
| 870a5731ac | |||
| 7910ce5d36 | |||
| 6ad171dba9 | |||
| cb5674edc7 | |||
| b99de4118e | |||
| 040700dbc4 | |||
| 4d5da9697e | |||
| a28648f530 | |||
| 4d81e2d4d9 | |||
| 21e72cbf42 | |||
| 5f277d1e62 | |||
| d67e877e28 | |||
| d4e51e04b3 | |||
| 070c1679e4 | |||
| 406d216cd2 | |||
| 5dc8b4ef29 | |||
| 2f41d89163 | |||
| b2eae867a1 | |||
| 3c2fda4d91 | |||
| 2678ceb45e | |||
| 58a4cd00b6 | |||
| 0faa191b6d | |||
| 58cf092105 | |||
| 0ff8bfe1d9 | |||
| ceb79c786a | |||
| b1a15d559b | |||
| 124a8abf9b | |||
| 85c2bb342b | |||
| 4c57e39466 | |||
| 0cdd4e4e16 | |||
| a9b01be0c2 | |||
| 528daf5490 | |||
| 0e176d3ac3 | |||
| 27f359852e | |||
| 173128d431 | |||
| e8ee1e239f | |||
| 656fa191c1 |
+1
-8
@@ -10,10 +10,6 @@
|
|||||||
adamdotdevin
|
adamdotdevin
|
||||||
-agusbasari29 AI PR slop
|
-agusbasari29 AI PR slop
|
||||||
ariane-emory
|
ariane-emory
|
||||||
-atharvau AI review spamming literally every PR
|
|
||||||
-borealbytes
|
|
||||||
-danieljoshuanazareth
|
|
||||||
-danieljoshuanazareth
|
|
||||||
edemaine
|
edemaine
|
||||||
-florianleibert
|
-florianleibert
|
||||||
fwang
|
fwang
|
||||||
@@ -21,11 +17,8 @@ iamdavidhill
|
|||||||
jayair
|
jayair
|
||||||
kitlangton
|
kitlangton
|
||||||
kommander
|
kommander
|
||||||
-opencode2026
|
|
||||||
-opencodeengineer bot that spams issues
|
|
||||||
r44vc0rp
|
r44vc0rp
|
||||||
rekram1-node
|
rekram1-node
|
||||||
-robinmordasiewicz
|
|
||||||
-spider-yamet clawdbot/llm psychosis, spam pinging the team
|
-spider-yamet clawdbot/llm psychosis, spam pinging the team
|
||||||
thdxr
|
thdxr
|
||||||
-toastythebot
|
-OpenCode2026
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
name: close-issues
|
|
||||||
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
- cron: "0 2 * * *" # Daily at 2:00 AM
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
close:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
issues: write
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: oven-sh/setup-bun@v2
|
|
||||||
with:
|
|
||||||
bun-version: latest
|
|
||||||
|
|
||||||
- name: Close stale issues
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ github.token }}
|
|
||||||
run: bun script/github/close-issues.ts
|
|
||||||
@@ -11,7 +11,7 @@ concurrency: ${{ github.workflow }}-${{ github.ref }}
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
sync-locales:
|
sync-locales:
|
||||||
if: false
|
if: github.actor != 'opencode-agent[bot]'
|
||||||
#if: github.actor != 'opencode-agent[bot]'
|
|
||||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -35,7 +34,7 @@ jobs:
|
|||||||
- name: Compute changed English docs
|
- name: Compute changed English docs
|
||||||
id: changes
|
id: changes
|
||||||
run: |
|
run: |
|
||||||
FILES=$(git diff --name-only "${{ github.event.before }}" "${{ github.sha }}" -- ':(glob)packages/web/src/content/docs/*.mdx' || true)
|
FILES=$(git diff --name-only "${{ github.event.before }}" "${{ github.sha }}" -- 'packages/web/src/content/docs/*.mdx' || true)
|
||||||
if [ -z "$FILES" ]; then
|
if [ -z "$FILES" ]; then
|
||||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||||
echo "No English docs changed in push range"
|
echo "No English docs changed in push range"
|
||||||
|
|||||||
@@ -17,10 +17,6 @@ on:
|
|||||||
- "patches/**"
|
- "patches/**"
|
||||||
- ".github/workflows/nix-hashes.yml"
|
- ".github/workflows/nix-hashes.yml"
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Native runners required: bun install cross-compilation flags (--os/--cpu)
|
# Native runners required: bun install cross-compilation flags (--os/--cpu)
|
||||||
# do not produce byte-identical node_modules as native installs.
|
# do not produce byte-identical node_modules as native installs.
|
||||||
@@ -60,7 +56,7 @@ jobs:
|
|||||||
nix build ".#packages.${SYSTEM}.node_modules_updater" --no-link 2>&1 | tee "$BUILD_LOG" || true
|
nix build ".#packages.${SYSTEM}.node_modules_updater" --no-link 2>&1 | tee "$BUILD_LOG" || true
|
||||||
|
|
||||||
# Extract hash from build log with portability
|
# Extract hash from build log with portability
|
||||||
HASH="$(nix run --inputs-from . nixpkgs#gnugrep -- -oP 'got:\s*\Ksha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)"
|
HASH="$(grep -oE 'sha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | tail -n1 || true)"
|
||||||
|
|
||||||
if [ -z "$HASH" ]; then
|
if [ -z "$HASH" ]; then
|
||||||
echo "::error::Failed to compute hash for ${SYSTEM}"
|
echo "::error::Failed to compute hash for ${SYSTEM}"
|
||||||
|
|||||||
@@ -98,129 +98,15 @@ jobs:
|
|||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: opencode-cli
|
name: opencode-cli
|
||||||
path: |
|
path: packages/opencode/dist
|
||||||
packages/opencode/dist/opencode-darwin*
|
|
||||||
packages/opencode/dist/opencode-linux*
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: opencode-cli-windows
|
|
||||||
path: packages/opencode/dist/opencode-windows*
|
|
||||||
outputs:
|
outputs:
|
||||||
version: ${{ needs.version.outputs.version }}
|
version: ${{ needs.version.outputs.version }}
|
||||||
|
|
||||||
sign-cli-windows:
|
|
||||||
needs:
|
|
||||||
- build-cli
|
|
||||||
- version
|
|
||||||
runs-on: blacksmith-4vcpu-windows-2025
|
|
||||||
if: github.repository == 'anomalyco/opencode'
|
|
||||||
env:
|
|
||||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
|
||||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
|
||||||
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
|
||||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
|
||||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
|
|
||||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: opencode-cli-windows
|
|
||||||
path: packages/opencode/dist
|
|
||||||
|
|
||||||
- name: Setup git committer
|
|
||||||
id: committer
|
|
||||||
uses: ./.github/actions/setup-git-committer
|
|
||||||
with:
|
|
||||||
opencode-app-id: ${{ vars.OPENCODE_APP_ID }}
|
|
||||||
opencode-app-secret: ${{ secrets.OPENCODE_APP_SECRET }}
|
|
||||||
|
|
||||||
- name: Azure login
|
|
||||||
uses: azure/login@v2
|
|
||||||
with:
|
|
||||||
client-id: ${{ env.AZURE_CLIENT_ID }}
|
|
||||||
tenant-id: ${{ env.AZURE_TENANT_ID }}
|
|
||||||
subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }}
|
|
||||||
|
|
||||||
- uses: azure/artifact-signing-action@v1
|
|
||||||
with:
|
|
||||||
endpoint: ${{ env.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
|
||||||
signing-account-name: ${{ env.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
|
||||||
certificate-profile-name: ${{ env.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
|
|
||||||
files: |
|
|
||||||
${{ github.workspace }}\packages\opencode\dist\opencode-windows-arm64\bin\opencode.exe
|
|
||||||
${{ github.workspace }}\packages\opencode\dist\opencode-windows-x64\bin\opencode.exe
|
|
||||||
${{ github.workspace }}\packages\opencode\dist\opencode-windows-x64-baseline\bin\opencode.exe
|
|
||||||
exclude-environment-credential: true
|
|
||||||
exclude-workload-identity-credential: true
|
|
||||||
exclude-managed-identity-credential: true
|
|
||||||
exclude-shared-token-cache-credential: true
|
|
||||||
exclude-visual-studio-credential: true
|
|
||||||
exclude-visual-studio-code-credential: true
|
|
||||||
exclude-azure-cli-credential: false
|
|
||||||
exclude-azure-powershell-credential: true
|
|
||||||
exclude-azure-developer-cli-credential: true
|
|
||||||
exclude-interactive-browser-credential: true
|
|
||||||
|
|
||||||
- name: Verify Windows CLI signatures
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$files = @(
|
|
||||||
"${{ github.workspace }}\packages\opencode\dist\opencode-windows-arm64\bin\opencode.exe",
|
|
||||||
"${{ github.workspace }}\packages\opencode\dist\opencode-windows-x64\bin\opencode.exe",
|
|
||||||
"${{ github.workspace }}\packages\opencode\dist\opencode-windows-x64-baseline\bin\opencode.exe"
|
|
||||||
)
|
|
||||||
|
|
||||||
foreach ($file in $files) {
|
|
||||||
$sig = Get-AuthenticodeSignature $file
|
|
||||||
if ($sig.Status -ne "Valid") {
|
|
||||||
throw "Invalid signature for ${file}: $($sig.Status)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- name: Repack Windows CLI archives
|
|
||||||
working-directory: packages/opencode/dist
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
Compress-Archive -Path "opencode-windows-arm64\bin\*" -DestinationPath "opencode-windows-arm64.zip" -Force
|
|
||||||
Compress-Archive -Path "opencode-windows-x64\bin\*" -DestinationPath "opencode-windows-x64.zip" -Force
|
|
||||||
Compress-Archive -Path "opencode-windows-x64-baseline\bin\*" -DestinationPath "opencode-windows-x64-baseline.zip" -Force
|
|
||||||
|
|
||||||
- name: Upload signed Windows CLI release assets
|
|
||||||
if: needs.version.outputs.release != ''
|
|
||||||
shell: pwsh
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ steps.committer.outputs.token }}
|
|
||||||
run: |
|
|
||||||
gh release upload "v${{ needs.version.outputs.version }}" `
|
|
||||||
"${{ github.workspace }}\packages\opencode\dist\opencode-windows-arm64.zip" `
|
|
||||||
"${{ github.workspace }}\packages\opencode\dist\opencode-windows-x64.zip" `
|
|
||||||
"${{ github.workspace }}\packages\opencode\dist\opencode-windows-x64-baseline.zip" `
|
|
||||||
--clobber `
|
|
||||||
--repo "${{ needs.version.outputs.repo }}"
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: opencode-cli-signed-windows
|
|
||||||
path: |
|
|
||||||
packages/opencode/dist/opencode-windows-arm64
|
|
||||||
packages/opencode/dist/opencode-windows-x64
|
|
||||||
packages/opencode/dist/opencode-windows-x64-baseline
|
|
||||||
|
|
||||||
build-tauri:
|
build-tauri:
|
||||||
needs:
|
needs:
|
||||||
- build-cli
|
- build-cli
|
||||||
- version
|
- version
|
||||||
continue-on-error: false
|
continue-on-error: false
|
||||||
env:
|
|
||||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
|
||||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
|
||||||
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
|
||||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
|
||||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
|
|
||||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -266,14 +152,6 @@ jobs:
|
|||||||
|
|
||||||
- uses: ./.github/actions/setup-bun
|
- uses: ./.github/actions/setup-bun
|
||||||
|
|
||||||
- name: Azure login
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
uses: azure/login@v2
|
|
||||||
with:
|
|
||||||
client-id: ${{ env.AZURE_CLIENT_ID }}
|
|
||||||
tenant-id: ${{ env.AZURE_TENANT_ID }}
|
|
||||||
subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }}
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: "24"
|
node-version: "24"
|
||||||
@@ -312,7 +190,6 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
|
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
|
||||||
GITHUB_TOKEN: ${{ steps.committer.outputs.token }}
|
GITHUB_TOKEN: ${{ steps.committer.outputs.token }}
|
||||||
OPENCODE_CLI_ARTIFACT: ${{ (runner.os == 'Windows' && 'opencode-cli-windows') || 'opencode-cli' }}
|
|
||||||
RUST_TARGET: ${{ matrix.settings.target }}
|
RUST_TARGET: ${{ matrix.settings.target }}
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
GITHUB_RUN_ID: ${{ github.run_id }}
|
GITHUB_RUN_ID: ${{ github.run_id }}
|
||||||
@@ -369,34 +246,11 @@ jobs:
|
|||||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||||
APPLE_API_KEY_PATH: ${{ runner.temp }}/apple-api-key.p8
|
APPLE_API_KEY_PATH: ${{ runner.temp }}/apple-api-key.p8
|
||||||
|
|
||||||
- name: Verify signed Windows desktop artifacts
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$files = @(
|
|
||||||
"${{ github.workspace }}\packages\desktop\src-tauri\sidecars\opencode-cli-${{ matrix.settings.target }}.exe"
|
|
||||||
)
|
|
||||||
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop\src-tauri\target\${{ matrix.settings.target }}\release\bundle\nsis\*.exe" | Select-Object -ExpandProperty FullName
|
|
||||||
|
|
||||||
foreach ($file in $files) {
|
|
||||||
$sig = Get-AuthenticodeSignature $file
|
|
||||||
if ($sig.Status -ne "Valid") {
|
|
||||||
throw "Invalid signature for ${file}: $($sig.Status)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
build-electron:
|
build-electron:
|
||||||
needs:
|
needs:
|
||||||
- build-cli
|
- build-cli
|
||||||
- version
|
- version
|
||||||
continue-on-error: false
|
continue-on-error: false
|
||||||
env:
|
|
||||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
|
||||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
|
||||||
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
|
||||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
|
||||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE }}
|
|
||||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -438,14 +292,6 @@ jobs:
|
|||||||
|
|
||||||
- uses: ./.github/actions/setup-bun
|
- uses: ./.github/actions/setup-bun
|
||||||
|
|
||||||
- name: Azure login
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
uses: azure/login@v2
|
|
||||||
with:
|
|
||||||
client-id: ${{ env.AZURE_CLIENT_ID }}
|
|
||||||
tenant-id: ${{ env.AZURE_TENANT_ID }}
|
|
||||||
subscription-id: ${{ env.AZURE_SUBSCRIPTION_ID }}
|
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: "24"
|
node-version: "24"
|
||||||
@@ -480,7 +326,6 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
|
OPENCODE_VERSION: ${{ needs.version.outputs.version }}
|
||||||
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
|
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
|
||||||
OPENCODE_CLI_ARTIFACT: ${{ (runner.os == 'Windows' && 'opencode-cli-windows') || 'opencode-cli' }}
|
|
||||||
RUST_TARGET: ${{ matrix.settings.target }}
|
RUST_TARGET: ${{ matrix.settings.target }}
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
GITHUB_RUN_ID: ${{ github.run_id }}
|
GITHUB_RUN_ID: ${{ github.run_id }}
|
||||||
@@ -513,22 +358,6 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
|
OPENCODE_CHANNEL: ${{ (github.ref_name == 'beta' && 'beta') || 'prod' }}
|
||||||
|
|
||||||
- name: Verify signed Windows Electron artifacts
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
shell: pwsh
|
|
||||||
run: |
|
|
||||||
$files = @()
|
|
||||||
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop-electron\dist\*.exe" | Select-Object -ExpandProperty FullName
|
|
||||||
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop-electron\dist\*unpacked\*.exe" | Select-Object -ExpandProperty FullName
|
|
||||||
$files += Get-ChildItem "${{ github.workspace }}\packages\desktop-electron\dist\*unpacked\resources\opencode-cli.exe" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName
|
|
||||||
|
|
||||||
foreach ($file in $files | Select-Object -Unique) {
|
|
||||||
$sig = Get-AuthenticodeSignature $file
|
|
||||||
if ($sig.Status -ne "Valid") {
|
|
||||||
throw "Invalid signature for ${file}: $($sig.Status)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: opencode-electron-${{ matrix.settings.target }}
|
name: opencode-electron-${{ matrix.settings.target }}
|
||||||
@@ -544,7 +373,6 @@ jobs:
|
|||||||
needs:
|
needs:
|
||||||
- version
|
- version
|
||||||
- build-cli
|
- build-cli
|
||||||
- sign-cli-windows
|
|
||||||
- build-tauri
|
- build-tauri
|
||||||
- build-electron
|
- build-electron
|
||||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
@@ -583,16 +411,6 @@ jobs:
|
|||||||
name: opencode-cli
|
name: opencode-cli
|
||||||
path: packages/opencode/dist
|
path: packages/opencode/dist
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: opencode-cli-windows
|
|
||||||
path: packages/opencode/dist
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: opencode-cli-signed-windows
|
|
||||||
path: packages/opencode/dist
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
if: needs.version.outputs.release
|
if: needs.version.outputs.release
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
name: sign-cli
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- brendan/desktop-signpath
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
actions: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
sign-cli:
|
||||||
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
|
if: github.repository == 'anomalyco/opencode'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-tags: true
|
||||||
|
|
||||||
|
- uses: ./.github/actions/setup-bun
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
./packages/opencode/script/build.ts
|
||||||
|
|
||||||
|
- name: Upload unsigned Windows CLI
|
||||||
|
id: upload_unsigned_windows_cli
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: unsigned-opencode-windows-cli
|
||||||
|
path: packages/opencode/dist/opencode-windows-x64/bin/opencode.exe
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Submit SignPath signing request
|
||||||
|
id: submit_signpath_signing_request
|
||||||
|
uses: signpath/github-action-submit-signing-request@v1
|
||||||
|
with:
|
||||||
|
api-token: ${{ secrets.SIGNPATH_API_KEY }}
|
||||||
|
organization-id: ${{ secrets.SIGNPATH_ORGANIZATION_ID }}
|
||||||
|
project-slug: ${{ secrets.SIGNPATH_PROJECT_SLUG }}
|
||||||
|
signing-policy-slug: ${{ secrets.SIGNPATH_SIGNING_POLICY_SLUG }}
|
||||||
|
artifact-configuration-slug: ${{ secrets.SIGNPATH_ARTIFACT_CONFIGURATION_SLUG }}
|
||||||
|
github-artifact-id: ${{ steps.upload_unsigned_windows_cli.outputs.artifact-id }}
|
||||||
|
wait-for-completion: true
|
||||||
|
output-artifact-directory: signed-opencode-cli
|
||||||
|
|
||||||
|
- name: Upload signed Windows CLI
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: signed-opencode-windows-cli
|
||||||
|
path: signed-opencode-cli/*.exe
|
||||||
|
if-no-files-found: error
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
name: stale-issues
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "30 1 * * *" # Daily at 1:30 AM
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
DAYS_BEFORE_STALE: 90
|
||||||
|
DAYS_BEFORE_CLOSE: 7
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
stale:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
issues: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/stale@v10
|
||||||
|
with:
|
||||||
|
days-before-stale: ${{ env.DAYS_BEFORE_STALE }}
|
||||||
|
days-before-close: ${{ env.DAYS_BEFORE_CLOSE }}
|
||||||
|
stale-issue-label: "stale"
|
||||||
|
close-issue-message: |
|
||||||
|
[automated] Closing due to ${{ env.DAYS_BEFORE_STALE }}+ days of inactivity.
|
||||||
|
|
||||||
|
Feel free to reopen if you still need this!
|
||||||
|
stale-issue-message: |
|
||||||
|
[automated] This issue has had no activity for ${{ env.DAYS_BEFORE_STALE }} days.
|
||||||
|
|
||||||
|
It will be closed in ${{ env.DAYS_BEFORE_CLOSE }} days if there's no new activity.
|
||||||
|
remove-stale-when-updated: true
|
||||||
|
exempt-issue-labels: "pinned,security,feature-request,on-hold"
|
||||||
|
start-date: "2025-12-27"
|
||||||
@@ -50,17 +50,20 @@ jobs:
|
|||||||
|
|
||||||
e2e:
|
e2e:
|
||||||
name: e2e (${{ matrix.settings.name }})
|
name: e2e (${{ matrix.settings.name }})
|
||||||
|
needs: unit
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
settings:
|
settings:
|
||||||
- name: linux
|
- name: linux
|
||||||
host: blacksmith-4vcpu-ubuntu-2404
|
host: blacksmith-4vcpu-ubuntu-2404
|
||||||
|
playwright: bunx playwright install --with-deps
|
||||||
- name: windows
|
- name: windows
|
||||||
host: blacksmith-4vcpu-windows-2025
|
host: blacksmith-4vcpu-windows-2025
|
||||||
|
playwright: bunx playwright install
|
||||||
runs-on: ${{ matrix.settings.host }}
|
runs-on: ${{ matrix.settings.host }}
|
||||||
env:
|
env:
|
||||||
PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.playwright-browsers
|
PLAYWRIGHT_BROWSERS_PATH: 0
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -73,36 +76,14 @@ jobs:
|
|||||||
- name: Setup Bun
|
- name: Setup Bun
|
||||||
uses: ./.github/actions/setup-bun
|
uses: ./.github/actions/setup-bun
|
||||||
|
|
||||||
- name: Read Playwright version
|
|
||||||
id: playwright-version
|
|
||||||
run: |
|
|
||||||
version=$(node -e 'console.log(require("./packages/app/package.json").devDependencies["@playwright/test"])')
|
|
||||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: Cache Playwright browsers
|
|
||||||
id: playwright-cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ${{ github.workspace }}/.playwright-browsers
|
|
||||||
key: ${{ runner.os }}-${{ runner.arch }}-playwright-${{ steps.playwright-version.outputs.version }}-chromium
|
|
||||||
|
|
||||||
- name: Install Playwright system dependencies
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
working-directory: packages/app
|
|
||||||
run: bunx playwright install-deps chromium
|
|
||||||
|
|
||||||
- name: Install Playwright browsers
|
- name: Install Playwright browsers
|
||||||
if: steps.playwright-cache.outputs.cache-hit != 'true'
|
|
||||||
working-directory: packages/app
|
working-directory: packages/app
|
||||||
run: bunx playwright install chromium
|
run: ${{ matrix.settings.playwright }}
|
||||||
|
|
||||||
- name: Run app e2e tests
|
- name: Run app e2e tests
|
||||||
run: bun --cwd packages/app test:e2e:local
|
run: bun --cwd packages/app test:e2e:local
|
||||||
env:
|
env:
|
||||||
CI: true
|
CI: true
|
||||||
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
|
|
||||||
OPENCODE_E2E_MODEL: opencode/claude-haiku-4-5
|
|
||||||
OPENCODE_E2E_REQUIRE_PAID: "true"
|
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
|
|
||||||
- name: Upload Playwright artifacts
|
- name: Upload Playwright artifacts
|
||||||
|
|||||||
@@ -33,6 +33,6 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
issue-id: ${{ github.event.issue.number }}
|
issue-id: ${{ github.event.issue.number }}
|
||||||
comment-id: ${{ github.event.comment.id }}
|
comment-id: ${{ github.event.comment.id }}
|
||||||
roles: admin,maintain,write
|
roles: admin,maintain
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ steps.committer.outputs.token }}
|
GITHUB_TOKEN: ${{ steps.committer.outputs.token }}
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ target
|
|||||||
|
|
||||||
# Local dev files
|
# Local dev files
|
||||||
opencode-dev
|
opencode-dev
|
||||||
UPCOMING_CHANGELOG.md
|
|
||||||
logs/
|
logs/
|
||||||
*.bun-build
|
*.bun-build
|
||||||
tsconfig.tsbuildinfo
|
tsconfig.tsbuildinfo
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
description: ALWAYS use this when writing docs
|
||||||
|
color: "#38A3EE"
|
||||||
|
---
|
||||||
|
|
||||||
|
You are an expert technical documentation writer
|
||||||
|
|
||||||
|
You are not verbose
|
||||||
|
|
||||||
|
Use a relaxed and friendly tone
|
||||||
|
|
||||||
|
The title of the page should be a word or a 2-3 word phrase
|
||||||
|
|
||||||
|
The description should be one short line, should not start with "The", should
|
||||||
|
avoid repeating the title of the page, should be 5-10 words long
|
||||||
|
|
||||||
|
Chunks of text should not be more than 2 sentences long
|
||||||
|
|
||||||
|
Each section is separated by a divider of 3 dashes
|
||||||
|
|
||||||
|
The section titles are short with only the first letter of the word capitalized
|
||||||
|
|
||||||
|
The section titles are in the imperative mood
|
||||||
|
|
||||||
|
The section titles should not repeat the term used in the page title, for
|
||||||
|
example, if the page title is "Models", avoid using a section title like "Add
|
||||||
|
new models". This might be unavoidable in some cases, but try to avoid it.
|
||||||
|
|
||||||
|
Check out the /packages/web/src/content/docs/docs/index.mdx as an example.
|
||||||
|
|
||||||
|
For JS or TS code snippets remove trailing semicolons and any trailing commas
|
||||||
|
that might not be needed.
|
||||||
|
|
||||||
|
If you are making a commit prefix the commit message with `docs:`
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
---
|
|
||||||
model: opencode/gpt-5.4
|
|
||||||
---
|
|
||||||
|
|
||||||
Create `UPCOMING_CHANGELOG.md` from the structured changelog input below.
|
|
||||||
If `UPCOMING_CHANGELOG.md` already exists, ignore its current contents completely.
|
|
||||||
Do not preserve, merge, or reuse text from the existing file.
|
|
||||||
|
|
||||||
The input already contains the exact commit range since the last non-draft release.
|
|
||||||
The commits are already filtered to the release-relevant packages and grouped into
|
|
||||||
the release sections. Do not fetch GitHub releases, PRs, or build your own commit list.
|
|
||||||
The input may also include a `## Community Contributors Input` section.
|
|
||||||
|
|
||||||
Before writing any entry you keep, inspect the real diff with
|
|
||||||
`git show --stat --format='' <hash>` or `git show --format='' <hash>` so you can
|
|
||||||
understand the actual code changes and not just the commit message (they may be misleading).
|
|
||||||
Do not use `git log` or author metadata when deciding attribution.
|
|
||||||
|
|
||||||
Rules:
|
|
||||||
|
|
||||||
- Write the final file with sections in this order:
|
|
||||||
`## Core`, `## TUI`, `## Desktop`, `## SDK`, `## Extensions`
|
|
||||||
- Only include sections that have at least one notable entry
|
|
||||||
- Keep one bullet per commit you keep
|
|
||||||
- Skip commits that are entirely internal, CI, tests, refactors, or otherwise not user-facing
|
|
||||||
- Start each bullet with a capital letter
|
|
||||||
- Prefer what changed for users over what code changed internally
|
|
||||||
- Do not copy raw commit prefixes like `fix:` or `feat:` or trailing PR numbers like `(#123)`
|
|
||||||
- Community attribution is deterministic: only preserve an existing `(@username)` suffix from the changelog input
|
|
||||||
- If an input bullet has no `(@username)` suffix, do not add one
|
|
||||||
- Never add a new `(@username)` suffix from `git show`, commit authors, names, or email addresses
|
|
||||||
- If no notable entries remain and there is no contributor block, write exactly `No notable changes.`
|
|
||||||
- If no notable entries remain but there is a contributor block, omit all release sections and return only the contributor block
|
|
||||||
- If the input contains `## Community Contributors Input`, append the block below that heading to the end of the final file verbatim
|
|
||||||
- Do not add, remove, rewrite, or reorder contributor names or commit titles in that block
|
|
||||||
- Do not derive the thank-you section from the main summary bullets
|
|
||||||
- Do not include the heading `## Community Contributors Input` in the final file
|
|
||||||
- Focus on writing the least words to get your point across - users will skim read the changelog, so we should be precise
|
|
||||||
|
|
||||||
**Importantly, the changelog is for users (who are at least slightly technical), they may use the TUI, Desktop, SDK, Plugins and so forth. Be thorough in understanding flow on effects may not be immediately apparent. e.g. a package upgrade looks internal but may patch a bug. Or a refactor may also stabilise some race condition that fixes bugs for users. The PR title/body + commit message will give you the authors context, usually containing the outcome not just technical detail**
|
|
||||||
|
|
||||||
<changelog_input>
|
|
||||||
|
|
||||||
!`bun script/raw-changelog.ts $ARGUMENTS`
|
|
||||||
|
|
||||||
</changelog_input>
|
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://opencode.ai/theme.json",
|
|
||||||
"defs": {
|
|
||||||
"nord0": "#2E3440",
|
|
||||||
"nord1": "#3B4252",
|
|
||||||
"nord2": "#434C5E",
|
|
||||||
"nord3": "#4C566A",
|
|
||||||
"nord4": "#D8DEE9",
|
|
||||||
"nord5": "#E5E9F0",
|
|
||||||
"nord6": "#ECEFF4",
|
|
||||||
"nord7": "#8FBCBB",
|
|
||||||
"nord8": "#88C0D0",
|
|
||||||
"nord9": "#81A1C1",
|
|
||||||
"nord10": "#5E81AC",
|
|
||||||
"nord11": "#BF616A",
|
|
||||||
"nord12": "#D08770",
|
|
||||||
"nord13": "#EBCB8B",
|
|
||||||
"nord14": "#A3BE8C",
|
|
||||||
"nord15": "#B48EAD"
|
|
||||||
},
|
|
||||||
"theme": {
|
|
||||||
"primary": {
|
|
||||||
"dark": "nord10",
|
|
||||||
"light": "nord9"
|
|
||||||
},
|
|
||||||
"secondary": {
|
|
||||||
"dark": "nord9",
|
|
||||||
"light": "nord9"
|
|
||||||
},
|
|
||||||
"accent": {
|
|
||||||
"dark": "nord7",
|
|
||||||
"light": "nord7"
|
|
||||||
},
|
|
||||||
"error": {
|
|
||||||
"dark": "nord11",
|
|
||||||
"light": "nord11"
|
|
||||||
},
|
|
||||||
"warning": {
|
|
||||||
"dark": "nord12",
|
|
||||||
"light": "nord12"
|
|
||||||
},
|
|
||||||
"success": {
|
|
||||||
"dark": "nord14",
|
|
||||||
"light": "nord14"
|
|
||||||
},
|
|
||||||
"info": {
|
|
||||||
"dark": "nord8",
|
|
||||||
"light": "nord10"
|
|
||||||
},
|
|
||||||
"text": {
|
|
||||||
"dark": "nord6",
|
|
||||||
"light": "nord0"
|
|
||||||
},
|
|
||||||
"textMuted": {
|
|
||||||
"dark": "#8B95A7",
|
|
||||||
"light": "nord1"
|
|
||||||
},
|
|
||||||
"background": {
|
|
||||||
"dark": "nord0",
|
|
||||||
"light": "nord6"
|
|
||||||
},
|
|
||||||
"backgroundPanel": {
|
|
||||||
"dark": "nord1",
|
|
||||||
"light": "nord5"
|
|
||||||
},
|
|
||||||
"backgroundElement": {
|
|
||||||
"dark": "nord2",
|
|
||||||
"light": "nord4"
|
|
||||||
},
|
|
||||||
"border": {
|
|
||||||
"dark": "nord2",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"borderActive": {
|
|
||||||
"dark": "nord3",
|
|
||||||
"light": "nord2"
|
|
||||||
},
|
|
||||||
"borderSubtle": {
|
|
||||||
"dark": "nord2",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"diffAdded": {
|
|
||||||
"dark": "nord14",
|
|
||||||
"light": "nord14"
|
|
||||||
},
|
|
||||||
"diffRemoved": {
|
|
||||||
"dark": "nord11",
|
|
||||||
"light": "nord11"
|
|
||||||
},
|
|
||||||
"diffContext": {
|
|
||||||
"dark": "#8B95A7",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"diffHunkHeader": {
|
|
||||||
"dark": "#8B95A7",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"diffHighlightAdded": {
|
|
||||||
"dark": "nord14",
|
|
||||||
"light": "nord14"
|
|
||||||
},
|
|
||||||
"diffHighlightRemoved": {
|
|
||||||
"dark": "nord11",
|
|
||||||
"light": "nord11"
|
|
||||||
},
|
|
||||||
"diffAddedBg": {
|
|
||||||
"dark": "#36413C",
|
|
||||||
"light": "#E6EBE7"
|
|
||||||
},
|
|
||||||
"diffRemovedBg": {
|
|
||||||
"dark": "#43393D",
|
|
||||||
"light": "#ECE6E8"
|
|
||||||
},
|
|
||||||
"diffContextBg": {
|
|
||||||
"dark": "nord1",
|
|
||||||
"light": "nord5"
|
|
||||||
},
|
|
||||||
"diffLineNumber": {
|
|
||||||
"dark": "nord2",
|
|
||||||
"light": "nord4"
|
|
||||||
},
|
|
||||||
"diffAddedLineNumberBg": {
|
|
||||||
"dark": "#303A35",
|
|
||||||
"light": "#DDE4DF"
|
|
||||||
},
|
|
||||||
"diffRemovedLineNumberBg": {
|
|
||||||
"dark": "#3C3336",
|
|
||||||
"light": "#E4DDE0"
|
|
||||||
},
|
|
||||||
"markdownText": {
|
|
||||||
"dark": "nord4",
|
|
||||||
"light": "nord0"
|
|
||||||
},
|
|
||||||
"markdownHeading": {
|
|
||||||
"dark": "nord8",
|
|
||||||
"light": "nord10"
|
|
||||||
},
|
|
||||||
"markdownLink": {
|
|
||||||
"dark": "nord9",
|
|
||||||
"light": "nord9"
|
|
||||||
},
|
|
||||||
"markdownLinkText": {
|
|
||||||
"dark": "nord7",
|
|
||||||
"light": "nord7"
|
|
||||||
},
|
|
||||||
"markdownCode": {
|
|
||||||
"dark": "nord14",
|
|
||||||
"light": "nord14"
|
|
||||||
},
|
|
||||||
"markdownBlockQuote": {
|
|
||||||
"dark": "#8B95A7",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"markdownEmph": {
|
|
||||||
"dark": "nord12",
|
|
||||||
"light": "nord12"
|
|
||||||
},
|
|
||||||
"markdownStrong": {
|
|
||||||
"dark": "nord13",
|
|
||||||
"light": "nord13"
|
|
||||||
},
|
|
||||||
"markdownHorizontalRule": {
|
|
||||||
"dark": "#8B95A7",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"markdownListItem": {
|
|
||||||
"dark": "nord8",
|
|
||||||
"light": "nord10"
|
|
||||||
},
|
|
||||||
"markdownListEnumeration": {
|
|
||||||
"dark": "nord7",
|
|
||||||
"light": "nord7"
|
|
||||||
},
|
|
||||||
"markdownImage": {
|
|
||||||
"dark": "nord9",
|
|
||||||
"light": "nord9"
|
|
||||||
},
|
|
||||||
"markdownImageText": {
|
|
||||||
"dark": "nord7",
|
|
||||||
"light": "nord7"
|
|
||||||
},
|
|
||||||
"markdownCodeBlock": {
|
|
||||||
"dark": "nord4",
|
|
||||||
"light": "nord0"
|
|
||||||
},
|
|
||||||
"syntaxComment": {
|
|
||||||
"dark": "#8B95A7",
|
|
||||||
"light": "nord3"
|
|
||||||
},
|
|
||||||
"syntaxKeyword": {
|
|
||||||
"dark": "nord9",
|
|
||||||
"light": "nord9"
|
|
||||||
},
|
|
||||||
"syntaxFunction": {
|
|
||||||
"dark": "nord8",
|
|
||||||
"light": "nord8"
|
|
||||||
},
|
|
||||||
"syntaxVariable": {
|
|
||||||
"dark": "nord7",
|
|
||||||
"light": "nord7"
|
|
||||||
},
|
|
||||||
"syntaxString": {
|
|
||||||
"dark": "nord14",
|
|
||||||
"light": "nord14"
|
|
||||||
},
|
|
||||||
"syntaxNumber": {
|
|
||||||
"dark": "nord15",
|
|
||||||
"light": "nord15"
|
|
||||||
},
|
|
||||||
"syntaxType": {
|
|
||||||
"dark": "nord7",
|
|
||||||
"light": "nord7"
|
|
||||||
},
|
|
||||||
"syntaxOperator": {
|
|
||||||
"dark": "nord9",
|
|
||||||
"light": "nord9"
|
|
||||||
},
|
|
||||||
"syntaxPunctuation": {
|
|
||||||
"dark": "nord4",
|
|
||||||
"light": "nord0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,891 +0,0 @@
|
|||||||
/** @jsxImportSource @opentui/solid */
|
|
||||||
import { useKeyboard, useTerminalDimensions, type JSX } from "@opentui/solid"
|
|
||||||
import { RGBA, VignetteEffect } from "@opentui/core"
|
|
||||||
import type {
|
|
||||||
TuiKeybindSet,
|
|
||||||
TuiPlugin,
|
|
||||||
TuiPluginApi,
|
|
||||||
TuiPluginMeta,
|
|
||||||
TuiPluginModule,
|
|
||||||
TuiSlotPlugin,
|
|
||||||
} from "@opencode-ai/plugin/tui"
|
|
||||||
|
|
||||||
const tabs = ["overview", "counter", "help"]
|
|
||||||
const bind = {
|
|
||||||
modal: "ctrl+shift+m",
|
|
||||||
screen: "ctrl+shift+o",
|
|
||||||
home: "escape,ctrl+h",
|
|
||||||
left: "left,h",
|
|
||||||
right: "right,l",
|
|
||||||
up: "up,k",
|
|
||||||
down: "down,j",
|
|
||||||
alert: "a",
|
|
||||||
confirm: "c",
|
|
||||||
prompt: "p",
|
|
||||||
select: "s",
|
|
||||||
modal_accept: "enter,return",
|
|
||||||
modal_close: "escape",
|
|
||||||
dialog_close: "escape",
|
|
||||||
local: "x",
|
|
||||||
local_push: "enter,return",
|
|
||||||
local_close: "q,backspace",
|
|
||||||
host: "z",
|
|
||||||
}
|
|
||||||
|
|
||||||
const pick = (value: unknown, fallback: string) => {
|
|
||||||
if (typeof value !== "string") return fallback
|
|
||||||
if (!value.trim()) return fallback
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
const num = (value: unknown, fallback: number) => {
|
|
||||||
if (typeof value !== "number") return fallback
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
const rec = (value: unknown) => {
|
|
||||||
if (!value || typeof value !== "object" || Array.isArray(value)) return
|
|
||||||
return Object.fromEntries(Object.entries(value))
|
|
||||||
}
|
|
||||||
|
|
||||||
type Cfg = {
|
|
||||||
label: string
|
|
||||||
route: string
|
|
||||||
vignette: number
|
|
||||||
keybinds: Record<string, unknown> | undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
type Route = {
|
|
||||||
modal: string
|
|
||||||
screen: string
|
|
||||||
}
|
|
||||||
|
|
||||||
type State = {
|
|
||||||
tab: number
|
|
||||||
count: number
|
|
||||||
source: string
|
|
||||||
note: string
|
|
||||||
selected: string
|
|
||||||
local: number
|
|
||||||
}
|
|
||||||
|
|
||||||
const cfg = (options: Record<string, unknown> | undefined) => {
|
|
||||||
return {
|
|
||||||
label: pick(options?.label, "smoke"),
|
|
||||||
route: pick(options?.route, "workspace-smoke"),
|
|
||||||
vignette: Math.max(0, num(options?.vignette, 0.35)),
|
|
||||||
keybinds: rec(options?.keybinds),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const names = (input: Cfg) => {
|
|
||||||
return {
|
|
||||||
modal: `${input.route}.modal`,
|
|
||||||
screen: `${input.route}.screen`,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Keys = TuiKeybindSet
|
|
||||||
const ui = {
|
|
||||||
panel: "#1d1d1d",
|
|
||||||
border: "#4a4a4a",
|
|
||||||
text: "#f0f0f0",
|
|
||||||
muted: "#a5a5a5",
|
|
||||||
accent: "#5f87ff",
|
|
||||||
}
|
|
||||||
|
|
||||||
type Color = RGBA | string
|
|
||||||
|
|
||||||
const ink = (map: Record<string, unknown>, name: string, fallback: string): Color => {
|
|
||||||
const value = map[name]
|
|
||||||
if (typeof value === "string") return value
|
|
||||||
if (value instanceof RGBA) return value
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
const look = (map: Record<string, unknown>) => {
|
|
||||||
return {
|
|
||||||
panel: ink(map, "backgroundPanel", ui.panel),
|
|
||||||
border: ink(map, "border", ui.border),
|
|
||||||
text: ink(map, "text", ui.text),
|
|
||||||
muted: ink(map, "textMuted", ui.muted),
|
|
||||||
accent: ink(map, "primary", ui.accent),
|
|
||||||
selected: ink(map, "selectedListItemText", ui.text),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const tone = (api: TuiPluginApi) => {
|
|
||||||
return look(api.theme.current)
|
|
||||||
}
|
|
||||||
|
|
||||||
type Skin = {
|
|
||||||
panel: Color
|
|
||||||
border: Color
|
|
||||||
text: Color
|
|
||||||
muted: Color
|
|
||||||
accent: Color
|
|
||||||
selected: Color
|
|
||||||
}
|
|
||||||
|
|
||||||
const Btn = (props: { txt: string; run: () => void; skin: Skin; on?: boolean }) => {
|
|
||||||
return (
|
|
||||||
<box
|
|
||||||
onMouseUp={() => {
|
|
||||||
props.run()
|
|
||||||
}}
|
|
||||||
backgroundColor={props.on ? props.skin.accent : props.skin.border}
|
|
||||||
paddingLeft={1}
|
|
||||||
paddingRight={1}
|
|
||||||
>
|
|
||||||
<text fg={props.on ? props.skin.selected : props.skin.text}>{props.txt}</text>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const parse = (params: Record<string, unknown> | undefined) => {
|
|
||||||
const tab = typeof params?.tab === "number" ? params.tab : 0
|
|
||||||
const count = typeof params?.count === "number" ? params.count : 0
|
|
||||||
const source = typeof params?.source === "string" ? params.source : "unknown"
|
|
||||||
const note = typeof params?.note === "string" ? params.note : ""
|
|
||||||
const selected = typeof params?.selected === "string" ? params.selected : ""
|
|
||||||
const local = typeof params?.local === "number" ? params.local : 0
|
|
||||||
return {
|
|
||||||
tab: Math.max(0, Math.min(tab, tabs.length - 1)),
|
|
||||||
count,
|
|
||||||
source,
|
|
||||||
note,
|
|
||||||
selected,
|
|
||||||
local: Math.max(0, local),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const current = (api: TuiPluginApi, route: Route) => {
|
|
||||||
const value = api.route.current
|
|
||||||
const ok = Object.values(route).includes(value.name)
|
|
||||||
if (!ok) return parse(undefined)
|
|
||||||
if (!("params" in value)) return parse(undefined)
|
|
||||||
return parse(value.params)
|
|
||||||
}
|
|
||||||
|
|
||||||
const opts = [
|
|
||||||
{
|
|
||||||
title: "Overview",
|
|
||||||
value: 0,
|
|
||||||
description: "Switch to overview tab",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "Counter",
|
|
||||||
value: 1,
|
|
||||||
description: "Switch to counter tab",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: "Help",
|
|
||||||
value: 2,
|
|
||||||
description: "Switch to help tab",
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const host = (api: TuiPluginApi, input: Cfg, skin: Skin) => {
|
|
||||||
api.ui.dialog.setSize("medium")
|
|
||||||
api.ui.dialog.replace(() => (
|
|
||||||
<box paddingBottom={1} paddingLeft={2} paddingRight={2} gap={1} flexDirection="column">
|
|
||||||
<text fg={skin.text}>
|
|
||||||
<b>{input.label} host overlay</b>
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>Using api.ui.dialog stack with built-in backdrop</text>
|
|
||||||
<text fg={skin.muted}>esc closes · depth {api.ui.dialog.depth}</text>
|
|
||||||
<box flexDirection="row" gap={1}>
|
|
||||||
<Btn txt="close" run={() => api.ui.dialog.clear()} skin={skin} on />
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
const warn = (api: TuiPluginApi, route: Route, value: State) => {
|
|
||||||
const DialogAlert = api.ui.DialogAlert
|
|
||||||
api.ui.dialog.setSize("medium")
|
|
||||||
api.ui.dialog.replace(() => (
|
|
||||||
<DialogAlert
|
|
||||||
title="Smoke alert"
|
|
||||||
message="Testing built-in alert dialog"
|
|
||||||
onConfirm={() => api.route.navigate(route.screen, { ...value, source: "alert" })}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
const check = (api: TuiPluginApi, route: Route, value: State) => {
|
|
||||||
const DialogConfirm = api.ui.DialogConfirm
|
|
||||||
api.ui.dialog.setSize("medium")
|
|
||||||
api.ui.dialog.replace(() => (
|
|
||||||
<DialogConfirm
|
|
||||||
title="Smoke confirm"
|
|
||||||
message="Apply +1 to counter?"
|
|
||||||
onConfirm={() => api.route.navigate(route.screen, { ...value, count: value.count + 1, source: "confirm" })}
|
|
||||||
onCancel={() => api.route.navigate(route.screen, { ...value, source: "confirm-cancel" })}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
const entry = (api: TuiPluginApi, route: Route, value: State) => {
|
|
||||||
const DialogPrompt = api.ui.DialogPrompt
|
|
||||||
api.ui.dialog.setSize("medium")
|
|
||||||
api.ui.dialog.replace(() => (
|
|
||||||
<DialogPrompt
|
|
||||||
title="Smoke prompt"
|
|
||||||
value={value.note}
|
|
||||||
onConfirm={(note) => {
|
|
||||||
api.ui.dialog.clear()
|
|
||||||
api.route.navigate(route.screen, { ...value, note, source: "prompt" })
|
|
||||||
}}
|
|
||||||
onCancel={() => {
|
|
||||||
api.ui.dialog.clear()
|
|
||||||
api.route.navigate(route.screen, value)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
const picker = (api: TuiPluginApi, route: Route, value: State) => {
|
|
||||||
const DialogSelect = api.ui.DialogSelect
|
|
||||||
api.ui.dialog.setSize("medium")
|
|
||||||
api.ui.dialog.replace(() => (
|
|
||||||
<DialogSelect
|
|
||||||
title="Smoke select"
|
|
||||||
options={opts}
|
|
||||||
current={value.tab}
|
|
||||||
onSelect={(item) => {
|
|
||||||
api.ui.dialog.clear()
|
|
||||||
api.route.navigate(route.screen, {
|
|
||||||
...value,
|
|
||||||
tab: typeof item.value === "number" ? item.value : value.tab,
|
|
||||||
selected: item.title,
|
|
||||||
source: "select",
|
|
||||||
})
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
const Screen = (props: {
|
|
||||||
api: TuiPluginApi
|
|
||||||
input: Cfg
|
|
||||||
route: Route
|
|
||||||
keys: Keys
|
|
||||||
meta: TuiPluginMeta
|
|
||||||
params?: Record<string, unknown>
|
|
||||||
}) => {
|
|
||||||
const dim = useTerminalDimensions()
|
|
||||||
const value = parse(props.params)
|
|
||||||
const skin = tone(props.api)
|
|
||||||
const set = (local: number, base?: State) => {
|
|
||||||
const next = base ?? current(props.api, props.route)
|
|
||||||
props.api.route.navigate(props.route.screen, { ...next, local: Math.max(0, local), source: "local" })
|
|
||||||
}
|
|
||||||
const push = (base?: State) => {
|
|
||||||
const next = base ?? current(props.api, props.route)
|
|
||||||
set(next.local + 1, next)
|
|
||||||
}
|
|
||||||
const open = () => {
|
|
||||||
const next = current(props.api, props.route)
|
|
||||||
if (next.local > 0) return
|
|
||||||
set(1, next)
|
|
||||||
}
|
|
||||||
const pop = (base?: State) => {
|
|
||||||
const next = base ?? current(props.api, props.route)
|
|
||||||
const local = Math.max(0, next.local - 1)
|
|
||||||
set(local, next)
|
|
||||||
}
|
|
||||||
const show = () => {
|
|
||||||
setTimeout(() => {
|
|
||||||
open()
|
|
||||||
}, 0)
|
|
||||||
}
|
|
||||||
useKeyboard((evt) => {
|
|
||||||
if (props.api.route.current.name !== props.route.screen) return
|
|
||||||
const next = current(props.api, props.route)
|
|
||||||
if (props.api.ui.dialog.open) {
|
|
||||||
if (props.keys.match("dialog_close", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.ui.dialog.clear()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (next.local > 0) {
|
|
||||||
if (evt.name === "escape" || props.keys.match("local_close", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
pop(next)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("local_push", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
push(next)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("home", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate("home")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("left", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate(props.route.screen, { ...next, tab: (next.tab - 1 + tabs.length) % tabs.length })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("right", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate(props.route.screen, { ...next, tab: (next.tab + 1) % tabs.length })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("up", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate(props.route.screen, { ...next, count: next.count + 1 })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("down", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate(props.route.screen, { ...next, count: next.count - 1 })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("modal", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate(props.route.modal, next)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("local", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
open()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("host", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
host(props.api, props.input, skin)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("alert", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
warn(props.api, props.route, next)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("confirm", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
check(props.api, props.route, next)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("prompt", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
entry(props.api, props.route, next)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("select", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
picker(props.api, props.route, next)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<box width={dim().width} height={dim().height} backgroundColor={skin.panel} position="relative">
|
|
||||||
<box
|
|
||||||
flexDirection="column"
|
|
||||||
width="100%"
|
|
||||||
height="100%"
|
|
||||||
paddingTop={1}
|
|
||||||
paddingBottom={1}
|
|
||||||
paddingLeft={2}
|
|
||||||
paddingRight={2}
|
|
||||||
>
|
|
||||||
<box flexDirection="row" justifyContent="space-between" paddingBottom={1}>
|
|
||||||
<text fg={skin.text}>
|
|
||||||
<b>{props.input.label} screen</b>
|
|
||||||
<span style={{ fg: skin.muted }}> plugin route</span>
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>{props.keys.print("home")} home</text>
|
|
||||||
</box>
|
|
||||||
|
|
||||||
<box flexDirection="row" gap={1} paddingBottom={1}>
|
|
||||||
{tabs.map((item, i) => {
|
|
||||||
const on = value.tab === i
|
|
||||||
return (
|
|
||||||
<Btn
|
|
||||||
txt={item}
|
|
||||||
run={() => props.api.route.navigate(props.route.screen, { ...value, tab: i })}
|
|
||||||
skin={skin}
|
|
||||||
on={on}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</box>
|
|
||||||
|
|
||||||
<box
|
|
||||||
border
|
|
||||||
borderColor={skin.border}
|
|
||||||
paddingTop={1}
|
|
||||||
paddingBottom={1}
|
|
||||||
paddingLeft={2}
|
|
||||||
paddingRight={2}
|
|
||||||
flexGrow={1}
|
|
||||||
>
|
|
||||||
{value.tab === 0 ? (
|
|
||||||
<box flexDirection="column" gap={1}>
|
|
||||||
<text fg={skin.text}>Route: {props.route.screen}</text>
|
|
||||||
<text fg={skin.muted}>plugin state: {props.meta.state}</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
first: {props.meta.state === "first" ? "yes" : "no"} · updated:{" "}
|
|
||||||
{props.meta.state === "updated" ? "yes" : "no"} · loads: {props.meta.load_count}
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>plugin source: {props.meta.source}</text>
|
|
||||||
<text fg={skin.muted}>source: {value.source}</text>
|
|
||||||
<text fg={skin.muted}>note: {value.note || "(none)"}</text>
|
|
||||||
<text fg={skin.muted}>selected: {value.selected || "(none)"}</text>
|
|
||||||
<text fg={skin.muted}>local stack depth: {value.local}</text>
|
|
||||||
<text fg={skin.muted}>host stack open: {props.api.ui.dialog.open ? "yes" : "no"}</text>
|
|
||||||
</box>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{value.tab === 1 ? (
|
|
||||||
<box flexDirection="column" gap={1}>
|
|
||||||
<text fg={skin.text}>Counter: {value.count}</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
{props.keys.print("up")} / {props.keys.print("down")} change value
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{value.tab === 2 ? (
|
|
||||||
<box flexDirection="column" gap={1}>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
{props.keys.print("modal")} modal | {props.keys.print("alert")} alert | {props.keys.print("confirm")}{" "}
|
|
||||||
confirm | {props.keys.print("prompt")} prompt | {props.keys.print("select")} select
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
{props.keys.print("local")} local stack | {props.keys.print("host")} host stack
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
local open: {props.keys.print("local_push")} push nested · esc or {props.keys.print("local_close")}{" "}
|
|
||||||
close
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>{props.keys.print("home")} returns home</text>
|
|
||||||
</box>
|
|
||||||
) : null}
|
|
||||||
</box>
|
|
||||||
|
|
||||||
<box flexDirection="row" gap={1} paddingTop={1}>
|
|
||||||
<Btn txt="go home" run={() => props.api.route.navigate("home")} skin={skin} />
|
|
||||||
<Btn txt="modal" run={() => props.api.route.navigate(props.route.modal, value)} skin={skin} on />
|
|
||||||
<Btn txt="local overlay" run={show} skin={skin} />
|
|
||||||
<Btn txt="host overlay" run={() => host(props.api, props.input, skin)} skin={skin} />
|
|
||||||
<Btn txt="alert" run={() => warn(props.api, props.route, value)} skin={skin} />
|
|
||||||
<Btn txt="confirm" run={() => check(props.api, props.route, value)} skin={skin} />
|
|
||||||
<Btn txt="prompt" run={() => entry(props.api, props.route, value)} skin={skin} />
|
|
||||||
<Btn txt="select" run={() => picker(props.api, props.route, value)} skin={skin} />
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
|
|
||||||
<box
|
|
||||||
visible={value.local > 0}
|
|
||||||
width={dim().width}
|
|
||||||
height={dim().height}
|
|
||||||
alignItems="center"
|
|
||||||
position="absolute"
|
|
||||||
zIndex={3000}
|
|
||||||
paddingTop={dim().height / 4}
|
|
||||||
left={0}
|
|
||||||
top={0}
|
|
||||||
backgroundColor={RGBA.fromInts(0, 0, 0, 160)}
|
|
||||||
onMouseUp={() => {
|
|
||||||
pop()
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<box
|
|
||||||
onMouseUp={(evt) => {
|
|
||||||
evt.stopPropagation()
|
|
||||||
}}
|
|
||||||
width={60}
|
|
||||||
maxWidth={dim().width - 2}
|
|
||||||
backgroundColor={skin.panel}
|
|
||||||
border
|
|
||||||
borderColor={skin.border}
|
|
||||||
paddingTop={1}
|
|
||||||
paddingBottom={1}
|
|
||||||
paddingLeft={2}
|
|
||||||
paddingRight={2}
|
|
||||||
gap={1}
|
|
||||||
flexDirection="column"
|
|
||||||
>
|
|
||||||
<text fg={skin.text}>
|
|
||||||
<b>{props.input.label} local overlay</b>
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>Plugin-owned stack depth: {value.local}</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
{props.keys.print("local_push")} push nested · {props.keys.print("local_close")} pop/close
|
|
||||||
</text>
|
|
||||||
<box flexDirection="row" gap={1}>
|
|
||||||
<Btn txt="push" run={push} skin={skin} on />
|
|
||||||
<Btn txt="pop" run={pop} skin={skin} />
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const Modal = (props: {
|
|
||||||
api: TuiPluginApi
|
|
||||||
input: Cfg
|
|
||||||
route: Route
|
|
||||||
keys: Keys
|
|
||||||
params?: Record<string, unknown>
|
|
||||||
}) => {
|
|
||||||
const Dialog = props.api.ui.Dialog
|
|
||||||
const value = parse(props.params)
|
|
||||||
const skin = tone(props.api)
|
|
||||||
|
|
||||||
useKeyboard((evt) => {
|
|
||||||
if (props.api.route.current.name !== props.route.modal) return
|
|
||||||
|
|
||||||
if (props.keys.match("modal_accept", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate(props.route.screen, { ...value, source: "modal" })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.keys.match("modal_close", evt)) {
|
|
||||||
evt.preventDefault()
|
|
||||||
evt.stopPropagation()
|
|
||||||
props.api.route.navigate("home")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return (
|
|
||||||
<box width="100%" height="100%" backgroundColor={skin.panel}>
|
|
||||||
<Dialog onClose={() => props.api.route.navigate("home")}>
|
|
||||||
<box paddingBottom={1} paddingLeft={2} paddingRight={2} gap={1} flexDirection="column">
|
|
||||||
<text fg={skin.text}>
|
|
||||||
<b>{props.input.label} modal</b>
|
|
||||||
</text>
|
|
||||||
<text fg={skin.muted}>{props.keys.print("modal")} modal command</text>
|
|
||||||
<text fg={skin.muted}>{props.keys.print("screen")} screen command</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
{props.keys.print("modal_accept")} opens screen · {props.keys.print("modal_close")} closes
|
|
||||||
</text>
|
|
||||||
<box flexDirection="row" gap={1}>
|
|
||||||
<Btn
|
|
||||||
txt="open screen"
|
|
||||||
run={() => props.api.route.navigate(props.route.screen, { ...value, source: "modal" })}
|
|
||||||
skin={skin}
|
|
||||||
on
|
|
||||||
/>
|
|
||||||
<Btn txt="cancel" run={() => props.api.route.navigate("home")} skin={skin} />
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
</Dialog>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const home = (api: TuiPluginApi, input: Cfg) => ({
|
|
||||||
slots: {
|
|
||||||
home_logo(ctx) {
|
|
||||||
const map = ctx.theme.current
|
|
||||||
const skin = look(map)
|
|
||||||
const art = [
|
|
||||||
" $$\\",
|
|
||||||
" $$ |",
|
|
||||||
" $$$$$$$\\ $$$$$$\\$$$$\\ $$$$$$\\ $$ | $$\\ $$$$$$\\",
|
|
||||||
"$$ _____|$$ _$$ _$$\\ $$ __$$\\ $$ | $$ |$$ __$$\\",
|
|
||||||
"\\$$$$$$\\ $$ / $$ / $$ |$$ / $$ |$$$$$$ / $$$$$$$$ |",
|
|
||||||
" \\____$$\\ $$ | $$ | $$ |$$ | $$ |$$ _$$< $$ ____|",
|
|
||||||
"$$$$$$$ |$$ | $$ | $$ |\\$$$$$$ |$$ | \\$$\\ \\$$$$$$$\\",
|
|
||||||
"\\_______/ \\__| \\__| \\__| \\______/ \\__| \\__| \\_______|",
|
|
||||||
]
|
|
||||||
const fill = [
|
|
||||||
skin.accent,
|
|
||||||
skin.muted,
|
|
||||||
ink(map, "info", ui.accent),
|
|
||||||
skin.text,
|
|
||||||
ink(map, "success", ui.accent),
|
|
||||||
ink(map, "warning", ui.accent),
|
|
||||||
ink(map, "secondary", ui.accent),
|
|
||||||
ink(map, "error", ui.accent),
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
|
||||||
<box flexDirection="column">
|
|
||||||
{art.map((line, i) => (
|
|
||||||
<text fg={fill[i]}>{line}</text>
|
|
||||||
))}
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
home_prompt(ctx, value) {
|
|
||||||
const skin = look(ctx.theme.current)
|
|
||||||
type Prompt = (props: {
|
|
||||||
workspaceID?: string
|
|
||||||
hint?: JSX.Element
|
|
||||||
placeholders?: {
|
|
||||||
normal?: string[]
|
|
||||||
shell?: string[]
|
|
||||||
}
|
|
||||||
}) => JSX.Element
|
|
||||||
if (!("Prompt" in api.ui)) return null
|
|
||||||
const view = api.ui.Prompt
|
|
||||||
if (typeof view !== "function") return null
|
|
||||||
const Prompt = view as Prompt
|
|
||||||
const normal = [
|
|
||||||
`[SMOKE] route check for ${input.label}`,
|
|
||||||
"[SMOKE] confirm home_prompt slot override",
|
|
||||||
"[SMOKE] verify api.ui.Prompt rendering",
|
|
||||||
]
|
|
||||||
const shell = ["printf '[SMOKE] home prompt\n'", "git status --short", "bun --version"]
|
|
||||||
const Hint = (
|
|
||||||
<box flexShrink={0} flexDirection="row" gap={1}>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
<span style={{ fg: skin.accent }}>•</span> smoke home prompt
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
|
|
||||||
return <Prompt workspaceID={value.workspace_id} hint={Hint} placeholders={{ normal, shell }} />
|
|
||||||
},
|
|
||||||
home_bottom(ctx) {
|
|
||||||
const skin = look(ctx.theme.current)
|
|
||||||
const text = "extra content in the unified home bottom slot"
|
|
||||||
|
|
||||||
return (
|
|
||||||
<box width="100%" maxWidth={75} alignItems="center" paddingTop={1} flexShrink={0} gap={1}>
|
|
||||||
<box
|
|
||||||
border
|
|
||||||
borderColor={skin.border}
|
|
||||||
backgroundColor={skin.panel}
|
|
||||||
paddingTop={1}
|
|
||||||
paddingBottom={1}
|
|
||||||
paddingLeft={2}
|
|
||||||
paddingRight={2}
|
|
||||||
width="100%"
|
|
||||||
>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
<span style={{ fg: skin.accent }}>{input.label}</span> {text}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const block = (input: Cfg, order: number, title: string, text: string): TuiSlotPlugin => ({
|
|
||||||
order,
|
|
||||||
slots: {
|
|
||||||
sidebar_content(ctx, value) {
|
|
||||||
const skin = look(ctx.theme.current)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<box
|
|
||||||
border
|
|
||||||
borderColor={skin.border}
|
|
||||||
backgroundColor={skin.panel}
|
|
||||||
paddingTop={1}
|
|
||||||
paddingBottom={1}
|
|
||||||
paddingLeft={2}
|
|
||||||
paddingRight={2}
|
|
||||||
flexDirection="column"
|
|
||||||
gap={1}
|
|
||||||
>
|
|
||||||
<text fg={skin.accent}>
|
|
||||||
<b>{title}</b>
|
|
||||||
</text>
|
|
||||||
<text fg={skin.text}>{text}</text>
|
|
||||||
<text fg={skin.muted}>
|
|
||||||
{input.label} order {order} · session {value.session_id.slice(0, 8)}
|
|
||||||
</text>
|
|
||||||
</box>
|
|
||||||
)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const slot = (api: TuiPluginApi, input: Cfg): TuiSlotPlugin[] => [
|
|
||||||
home(api, input),
|
|
||||||
block(input, 50, "Smoke above", "renders above internal sidebar blocks"),
|
|
||||||
block(input, 250, "Smoke between", "renders between internal sidebar blocks"),
|
|
||||||
block(input, 650, "Smoke below", "renders below internal sidebar blocks"),
|
|
||||||
]
|
|
||||||
|
|
||||||
const reg = (api: TuiPluginApi, input: Cfg, keys: Keys) => {
|
|
||||||
const route = names(input)
|
|
||||||
api.command.register(() => [
|
|
||||||
{
|
|
||||||
title: `${input.label} modal`,
|
|
||||||
value: "plugin.smoke.modal",
|
|
||||||
keybind: keys.get("modal"),
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
api.route.navigate(route.modal, { source: "command" })
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} screen`,
|
|
||||||
value: "plugin.smoke.screen",
|
|
||||||
keybind: keys.get("screen"),
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke-screen",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
api.route.navigate(route.screen, { source: "command", tab: 0, count: 0 })
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} alert dialog`,
|
|
||||||
value: "plugin.smoke.alert",
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke-alert",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
warn(api, route, current(api, route))
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} confirm dialog`,
|
|
||||||
value: "plugin.smoke.confirm",
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke-confirm",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
check(api, route, current(api, route))
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} prompt dialog`,
|
|
||||||
value: "plugin.smoke.prompt",
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke-prompt",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
entry(api, route, current(api, route))
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} select dialog`,
|
|
||||||
value: "plugin.smoke.select",
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke-select",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
picker(api, route, current(api, route))
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} host overlay`,
|
|
||||||
value: "plugin.smoke.host",
|
|
||||||
category: "Plugin",
|
|
||||||
slash: {
|
|
||||||
name: "smoke-host",
|
|
||||||
},
|
|
||||||
onSelect: () => {
|
|
||||||
host(api, input, tone(api))
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} go home`,
|
|
||||||
value: "plugin.smoke.home",
|
|
||||||
category: "Plugin",
|
|
||||||
enabled: api.route.current.name !== "home",
|
|
||||||
onSelect: () => {
|
|
||||||
api.route.navigate("home")
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: `${input.label} toast`,
|
|
||||||
value: "plugin.smoke.toast",
|
|
||||||
category: "Plugin",
|
|
||||||
onSelect: () => {
|
|
||||||
api.ui.toast({
|
|
||||||
variant: "info",
|
|
||||||
title: "Smoke",
|
|
||||||
message: "Plugin toast works",
|
|
||||||
duration: 2000,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
},
|
|
||||||
])
|
|
||||||
}
|
|
||||||
|
|
||||||
const tui: TuiPlugin = async (api, options, meta) => {
|
|
||||||
if (options?.enabled === false) return
|
|
||||||
|
|
||||||
await api.theme.install("./smoke-theme.json")
|
|
||||||
api.theme.set("smoke-theme")
|
|
||||||
|
|
||||||
const value = cfg(options ?? undefined)
|
|
||||||
const route = names(value)
|
|
||||||
const keys = api.keybind.create(bind, value.keybinds)
|
|
||||||
const fx = new VignetteEffect(value.vignette)
|
|
||||||
const post = fx.apply.bind(fx)
|
|
||||||
api.renderer.addPostProcessFn(post)
|
|
||||||
api.lifecycle.onDispose(() => {
|
|
||||||
api.renderer.removePostProcessFn(post)
|
|
||||||
})
|
|
||||||
|
|
||||||
api.route.register([
|
|
||||||
{
|
|
||||||
name: route.screen,
|
|
||||||
render: ({ params }) => <Screen api={api} input={value} route={route} keys={keys} meta={meta} params={params} />,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: route.modal,
|
|
||||||
render: ({ params }) => <Modal api={api} input={value} route={route} keys={keys} params={params} />,
|
|
||||||
},
|
|
||||||
])
|
|
||||||
|
|
||||||
reg(api, value, keys)
|
|
||||||
for (const item of slot(api, value)) {
|
|
||||||
api.slots.register(item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const plugin: TuiPluginModule & { id: string } = {
|
|
||||||
id: "tui-smoke",
|
|
||||||
tui,
|
|
||||||
}
|
|
||||||
|
|
||||||
export default plugin
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
smoke-theme.json
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://opencode.ai/tui.json",
|
|
||||||
"plugin": [
|
|
||||||
[
|
|
||||||
"./plugins/tui-smoke.tsx",
|
|
||||||
{
|
|
||||||
"enabled": false,
|
|
||||||
"label": "workspace",
|
|
||||||
"keybinds": {
|
|
||||||
"modal": "ctrl+alt+m",
|
|
||||||
"screen": "ctrl+alt+o",
|
|
||||||
"home": "escape,ctrl+shift+h",
|
|
||||||
"dialog_close": "escape,q"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
github-policies:
|
||||||
|
runners:
|
||||||
|
allowed_groups:
|
||||||
|
- "GitHub Actions"
|
||||||
|
- "blacksmith runners 01kbd5v56sg8tz7rea39b7ygpt"
|
||||||
@@ -128,7 +128,7 @@ If you are working on a project that's related to OpenCode and is using "opencod
|
|||||||
|
|
||||||
#### How is this different from Claude Code?
|
#### How is this different from Claude Code?
|
||||||
|
|
||||||
It's very similar to Claude Code in terms of capability. Here are the key differences:
|
It's very similar to Claude Code in terms of capability. Here are the key differences::
|
||||||
|
|
||||||
- 100% open source
|
- 100% open source
|
||||||
- Not coupled to any provider. Although we recommend the models we provide through [OpenCode Zen](https://opencode.ai/zen), OpenCode can be used with Claude, OpenAI, Google, or even local models. As models evolve, the gaps between them will close and pricing will drop, so being provider-agnostic is important.
|
- Not coupled to any provider. Although we recommend the models we provide through [OpenCode Zen](https://opencode.ai/zen), OpenCode can be used with Claude, OpenAI, Google, or even local models. As models evolve, the gaps between them will close and pricing will drop, so being provider-agnostic is important.
|
||||||
|
|||||||
+1
-1
@@ -137,4 +137,4 @@ OpenCode 内置两种 Agent,可用 `Tab` 键快速切换:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=738j8655-cd59-4633-a30a-1124e0096789&qr_code=true) | [X.com](https://x.com/opencode)
|
**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=de8k6664-1b5e-43f2-8efd-21d6772647b5&qr_code=true) | [X.com](https://x.com/opencode)
|
||||||
|
|||||||
+1
-1
@@ -137,4 +137,4 @@ OpenCode 內建了兩種 Agent,您可以使用 `Tab` 鍵快速切換。
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=738j8655-cd59-4633-a30a-1124e0096789&qr_code=true) | [X.com](https://x.com/opencode)
|
**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=de8k6664-1b5e-43f2-8efd-21d6772647b5&qr_code=true) | [X.com](https://x.com/opencode)
|
||||||
|
|||||||
Generated
+3
-3
@@ -2,11 +2,11 @@
|
|||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1773909469,
|
"lastModified": 1772091128,
|
||||||
"narHash": "sha256-vglVrLfHjFIzIdV9A27Ugul6rh3I1qHbbitGW7dk420=",
|
"narHash": "sha256-TnrYykX8Mf/Ugtkix6V+PjW7miU2yClA6uqWl/v6KWM=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "7149c06513f335be57f26fcbbbe34afda923882b",
|
"rev": "3f0336406035444b4a24b942788334af5f906259",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -496,6 +496,7 @@ async function subscribeSessionEvents() {
|
|||||||
|
|
||||||
const TOOL: Record<string, [string, string]> = {
|
const TOOL: Record<string, [string, string]> = {
|
||||||
todowrite: ["Todo", "\x1b[33m\x1b[1m"],
|
todowrite: ["Todo", "\x1b[33m\x1b[1m"],
|
||||||
|
todoread: ["Todo", "\x1b[33m\x1b[1m"],
|
||||||
bash: ["Bash", "\x1b[31m\x1b[1m"],
|
bash: ["Bash", "\x1b[31m\x1b[1m"],
|
||||||
edit: ["Edit", "\x1b[32m\x1b[1m"],
|
edit: ["Edit", "\x1b[32m\x1b[1m"],
|
||||||
glob: ["Glob", "\x1b[34m\x1b[1m"],
|
glob: ["Glob", "\x1b[34m\x1b[1m"],
|
||||||
|
|||||||
+4
-4
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"nodeModules": {
|
"nodeModules": {
|
||||||
"x86_64-linux": "sha256-bjfe8/aD0hvUQQEfaNdmKV/Y3dzpf8oz1OUJdgf61WI=",
|
"x86_64-linux": "sha256-yfA50QKqylmaioxi+6d++W8Xv4Wix1hl3hEF6Zz7Ue0=",
|
||||||
"aarch64-linux": "sha256-iU9v+ekSCB/qTUG+pOOpSMhPh+0hWnWU5jzDNllEkxU=",
|
"aarch64-linux": "sha256-b5sO7V+/zzJClHHKjkSz+9AUBYC8cb7S3m5ab1kpAyk=",
|
||||||
"aarch64-darwin": "sha256-SgNydQLeAjbX0J49f2VKcgKg2Y30pK826R2qQJBMWE4=",
|
"aarch64-darwin": "sha256-V66nmRX6kAjrc41ARVeuTElWK7KD8qG/DVk9K7Fu+J8=",
|
||||||
"x86_64-darwin": "sha256-/rzwNuI9x55qi0UcU7QvPUTupErmkt62T09g1omXkQk="
|
"x86_64-darwin": "sha256-cFyh60WESiqZ5XWZi1+g3F/beSDL1+UPG8KhRivhK8w="
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ let
|
|||||||
in
|
in
|
||||||
stdenvNoCC.mkDerivation {
|
stdenvNoCC.mkDerivation {
|
||||||
pname = "opencode-node_modules";
|
pname = "opencode-node_modules";
|
||||||
version = "${packageJson.version}+${lib.replaceString "-" "." rev}";
|
version = "${packageJson.version}-${rev}";
|
||||||
|
|
||||||
src = lib.fileset.toSource {
|
src = lib.fileset.toSource {
|
||||||
root = ../.;
|
root = ../.;
|
||||||
@@ -54,7 +54,6 @@ stdenvNoCC.mkDerivation {
|
|||||||
--filter '!./' \
|
--filter '!./' \
|
||||||
--filter './packages/opencode' \
|
--filter './packages/opencode' \
|
||||||
--filter './packages/desktop' \
|
--filter './packages/desktop' \
|
||||||
--filter './packages/app' \
|
|
||||||
--frozen-lockfile \
|
--frozen-lockfile \
|
||||||
--ignore-scripts \
|
--ignore-scripts \
|
||||||
--no-progress
|
--no-progress
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
stdenvNoCC,
|
stdenvNoCC,
|
||||||
callPackage,
|
callPackage,
|
||||||
bun,
|
bun,
|
||||||
nodejs,
|
|
||||||
sysctl,
|
sysctl,
|
||||||
makeBinaryWrapper,
|
makeBinaryWrapper,
|
||||||
models-dev,
|
models-dev,
|
||||||
@@ -20,7 +19,6 @@ stdenvNoCC.mkDerivation (finalAttrs: {
|
|||||||
|
|
||||||
nativeBuildInputs = [
|
nativeBuildInputs = [
|
||||||
bun
|
bun
|
||||||
nodejs # for patchShebangs node_modules
|
|
||||||
installShellFiles
|
installShellFiles
|
||||||
makeBinaryWrapper
|
makeBinaryWrapper
|
||||||
models-dev
|
models-dev
|
||||||
@@ -31,8 +29,6 @@ stdenvNoCC.mkDerivation (finalAttrs: {
|
|||||||
runHook preConfigure
|
runHook preConfigure
|
||||||
|
|
||||||
cp -R ${finalAttrs.node_modules}/. .
|
cp -R ${finalAttrs.node_modules}/. .
|
||||||
patchShebangs node_modules
|
|
||||||
patchShebangs packages/*/node_modules
|
|
||||||
|
|
||||||
runHook postConfigure
|
runHook postConfigure
|
||||||
'';
|
'';
|
||||||
|
|||||||
+6
-10
@@ -4,7 +4,7 @@
|
|||||||
"description": "AI-powered development tool",
|
"description": "AI-powered development tool",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "bun@1.3.11",
|
"packageManager": "bun@1.3.10",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun run --cwd packages/opencode --conditions=browser src/index.ts",
|
"dev": "bun run --cwd packages/opencode --conditions=browser src/index.ts",
|
||||||
"dev:desktop": "bun --cwd packages/desktop tauri dev",
|
"dev:desktop": "bun --cwd packages/desktop tauri dev",
|
||||||
@@ -25,8 +25,8 @@
|
|||||||
"packages/slack"
|
"packages/slack"
|
||||||
],
|
],
|
||||||
"catalog": {
|
"catalog": {
|
||||||
"@effect/platform-node": "4.0.0-beta.43",
|
"@effect/platform-node": "4.0.0-beta.35",
|
||||||
"@types/bun": "1.3.11",
|
"@types/bun": "1.3.9",
|
||||||
"@octokit/rest": "22.0.0",
|
"@octokit/rest": "22.0.0",
|
||||||
"@hono/zod-validator": "0.4.2",
|
"@hono/zod-validator": "0.4.2",
|
||||||
"ulid": "3.0.1",
|
"ulid": "3.0.1",
|
||||||
@@ -45,15 +45,14 @@
|
|||||||
"dompurify": "3.3.1",
|
"dompurify": "3.3.1",
|
||||||
"drizzle-kit": "1.0.0-beta.19-d95b7a4",
|
"drizzle-kit": "1.0.0-beta.19-d95b7a4",
|
||||||
"drizzle-orm": "1.0.0-beta.19-d95b7a4",
|
"drizzle-orm": "1.0.0-beta.19-d95b7a4",
|
||||||
"effect": "4.0.0-beta.43",
|
"effect": "4.0.0-beta.35",
|
||||||
"ai": "6.0.138",
|
"ai": "5.0.124",
|
||||||
"hono": "4.10.7",
|
"hono": "4.10.7",
|
||||||
"hono-openapi": "1.1.2",
|
"hono-openapi": "1.1.2",
|
||||||
"fuzzysort": "3.1.0",
|
"fuzzysort": "3.1.0",
|
||||||
"luxon": "3.6.1",
|
"luxon": "3.6.1",
|
||||||
"marked": "17.0.1",
|
"marked": "17.0.1",
|
||||||
"marked-shiki": "1.2.1",
|
"marked-shiki": "1.2.1",
|
||||||
"remend": "1.3.0",
|
|
||||||
"@playwright/test": "1.51.0",
|
"@playwright/test": "1.51.0",
|
||||||
"typescript": "5.8.2",
|
"typescript": "5.8.2",
|
||||||
"@typescript/native-preview": "7.0.0-dev.20251207.1",
|
"@typescript/native-preview": "7.0.0-dev.20251207.1",
|
||||||
@@ -104,7 +103,6 @@
|
|||||||
"protobufjs",
|
"protobufjs",
|
||||||
"tree-sitter",
|
"tree-sitter",
|
||||||
"tree-sitter-bash",
|
"tree-sitter-bash",
|
||||||
"tree-sitter-powershell",
|
|
||||||
"web-tree-sitter",
|
"web-tree-sitter",
|
||||||
"electron"
|
"electron"
|
||||||
],
|
],
|
||||||
@@ -114,8 +112,6 @@
|
|||||||
},
|
},
|
||||||
"patchedDependencies": {
|
"patchedDependencies": {
|
||||||
"@standard-community/standard-openapi@0.2.9": "patches/@standard-community%2Fstandard-openapi@0.2.9.patch",
|
"@standard-community/standard-openapi@0.2.9": "patches/@standard-community%2Fstandard-openapi@0.2.9.patch",
|
||||||
"solid-js@1.9.10": "patches/solid-js@1.9.10.patch",
|
"@openrouter/ai-sdk-provider@1.5.4": "patches/@openrouter%2Fai-sdk-provider@1.5.4.patch"
|
||||||
"@ai-sdk/provider-utils@4.0.21": "patches/@ai-sdk%2Fprovider-utils@4.0.21.patch",
|
|
||||||
"@ai-sdk/anthropic@3.0.64": "patches/@ai-sdk%2Fanthropic@3.0.64.patch"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-175
@@ -9,7 +9,6 @@ import { createSdk, modKey, resolveDirectory, serverUrl } from "./utils"
|
|||||||
import {
|
import {
|
||||||
dropdownMenuTriggerSelector,
|
dropdownMenuTriggerSelector,
|
||||||
dropdownMenuContentSelector,
|
dropdownMenuContentSelector,
|
||||||
projectSwitchSelector,
|
|
||||||
projectMenuTriggerSelector,
|
projectMenuTriggerSelector,
|
||||||
projectCloseMenuSelector,
|
projectCloseMenuSelector,
|
||||||
projectWorkspacesToggleSelector,
|
projectWorkspacesToggleSelector,
|
||||||
@@ -24,16 +23,6 @@ import {
|
|||||||
workspaceMenuTriggerSelector,
|
workspaceMenuTriggerSelector,
|
||||||
} from "./selectors"
|
} from "./selectors"
|
||||||
|
|
||||||
const phase = new WeakMap<Page, "test" | "cleanup">()
|
|
||||||
|
|
||||||
export function setHealthPhase(page: Page, value: "test" | "cleanup") {
|
|
||||||
phase.set(page, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function healthPhase(page: Page) {
|
|
||||||
return phase.get(page) ?? "test"
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function defocus(page: Page) {
|
export async function defocus(page: Page) {
|
||||||
await page
|
await page
|
||||||
.evaluate(() => {
|
.evaluate(() => {
|
||||||
@@ -175,9 +164,9 @@ export async function runTerminal(page: Page, input: { cmd: string; token: strin
|
|||||||
await expect.poll(() => terminalHas(page, { term, token: input.token }), { timeout }).toBe(true)
|
await expect.poll(() => terminalHas(page, { term, token: input.token }), { timeout }).toBe(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openPalette(page: Page, key = "K") {
|
export async function openPalette(page: Page) {
|
||||||
await defocus(page)
|
await defocus(page)
|
||||||
await page.keyboard.press(`${modKey}+${key}`)
|
await page.keyboard.press(`${modKey}+P`)
|
||||||
|
|
||||||
const dialog = page.getByRole("dialog")
|
const dialog = page.getByRole("dialog")
|
||||||
await expect(dialog).toBeVisible()
|
await expect(dialog).toBeVisible()
|
||||||
@@ -207,49 +196,9 @@ export async function closeDialog(page: Page, dialog: Locator) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function isSidebarClosed(page: Page) {
|
export async function isSidebarClosed(page: Page) {
|
||||||
const button = await waitSidebarButton(page, "isSidebarClosed")
|
|
||||||
return (await button.getAttribute("aria-expanded")) !== "true"
|
|
||||||
}
|
|
||||||
|
|
||||||
async function errorBoundaryText(page: Page) {
|
|
||||||
const title = page.getByRole("heading", { name: /something went wrong/i }).first()
|
|
||||||
if (!(await title.isVisible().catch(() => false))) return
|
|
||||||
|
|
||||||
const description = await page
|
|
||||||
.getByText(/an error occurred while loading the application\./i)
|
|
||||||
.first()
|
|
||||||
.textContent()
|
|
||||||
.catch(() => "")
|
|
||||||
const detail = await page
|
|
||||||
.getByRole("textbox", { name: /error details/i })
|
|
||||||
.first()
|
|
||||||
.inputValue()
|
|
||||||
.catch(async () =>
|
|
||||||
(
|
|
||||||
(await page
|
|
||||||
.getByRole("textbox", { name: /error details/i })
|
|
||||||
.first()
|
|
||||||
.textContent()
|
|
||||||
.catch(() => "")) ?? ""
|
|
||||||
).trim(),
|
|
||||||
)
|
|
||||||
|
|
||||||
return [title ? "Error boundary" : "", description ?? "", detail ?? ""].filter(Boolean).join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function assertHealthy(page: Page, context: string) {
|
|
||||||
const text = await errorBoundaryText(page)
|
|
||||||
if (!text) return
|
|
||||||
console.log(`[e2e:error-boundary][${context}]\n${text}`)
|
|
||||||
throw new Error(`Error boundary during ${context}\n${text}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function waitSidebarButton(page: Page, context: string) {
|
|
||||||
const button = page.getByRole("button", { name: /toggle sidebar/i }).first()
|
const button = page.getByRole("button", { name: /toggle sidebar/i }).first()
|
||||||
const boundary = page.getByRole("heading", { name: /something went wrong/i }).first()
|
await expect(button).toBeVisible()
|
||||||
await button.or(boundary).first().waitFor({ state: "visible", timeout: 10_000 })
|
return (await button.getAttribute("aria-expanded")) !== "true"
|
||||||
await assertHealthy(page, context)
|
|
||||||
return button
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function toggleSidebar(page: Page) {
|
export async function toggleSidebar(page: Page) {
|
||||||
@@ -260,7 +209,7 @@ export async function toggleSidebar(page: Page) {
|
|||||||
export async function openSidebar(page: Page) {
|
export async function openSidebar(page: Page) {
|
||||||
if (!(await isSidebarClosed(page))) return
|
if (!(await isSidebarClosed(page))) return
|
||||||
|
|
||||||
const button = await waitSidebarButton(page, "openSidebar")
|
const button = page.getByRole("button", { name: /toggle sidebar/i }).first()
|
||||||
await button.click()
|
await button.click()
|
||||||
|
|
||||||
const opened = await expect(button)
|
const opened = await expect(button)
|
||||||
@@ -277,7 +226,7 @@ export async function openSidebar(page: Page) {
|
|||||||
export async function closeSidebar(page: Page) {
|
export async function closeSidebar(page: Page) {
|
||||||
if (await isSidebarClosed(page)) return
|
if (await isSidebarClosed(page)) return
|
||||||
|
|
||||||
const button = await waitSidebarButton(page, "closeSidebar")
|
const button = page.getByRole("button", { name: /toggle sidebar/i }).first()
|
||||||
await button.click()
|
await button.click()
|
||||||
|
|
||||||
const closed = await expect(button)
|
const closed = await expect(button)
|
||||||
@@ -292,7 +241,6 @@ export async function closeSidebar(page: Page) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function openSettings(page: Page) {
|
export async function openSettings(page: Page) {
|
||||||
await assertHealthy(page, "openSettings")
|
|
||||||
await defocus(page)
|
await defocus(page)
|
||||||
|
|
||||||
const dialog = page.getByRole("dialog")
|
const dialog = page.getByRole("dialog")
|
||||||
@@ -305,18 +253,15 @@ export async function openSettings(page: Page) {
|
|||||||
|
|
||||||
if (opened) return dialog
|
if (opened) return dialog
|
||||||
|
|
||||||
await assertHealthy(page, "openSettings")
|
|
||||||
|
|
||||||
await page.getByRole("button", { name: "Settings" }).first().click()
|
await page.getByRole("button", { name: "Settings" }).first().click()
|
||||||
await expect(dialog).toBeVisible()
|
await expect(dialog).toBeVisible()
|
||||||
return dialog
|
return dialog
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function seedProjects(page: Page, input: { directory: string; extra?: string[]; serverUrl?: string }) {
|
export async function seedProjects(page: Page, input: { directory: string; extra?: string[] }) {
|
||||||
await page.addInitScript(
|
await page.addInitScript(
|
||||||
(args: { directory: string; serverUrl: string; extra: string[] }) => {
|
(args: { directory: string; serverUrl: string; extra: string[] }) => {
|
||||||
const key = "opencode.global.dat:server"
|
const key = "opencode.global.dat:server"
|
||||||
const defaultKey = "opencode.settings.dat:defaultServerUrl"
|
|
||||||
const raw = localStorage.getItem(key)
|
const raw = localStorage.getItem(key)
|
||||||
const parsed = (() => {
|
const parsed = (() => {
|
||||||
if (!raw) return undefined
|
if (!raw) return undefined
|
||||||
@@ -332,7 +277,6 @@ export async function seedProjects(page: Page, input: { directory: string; extra
|
|||||||
const lastProject = store.lastProject && typeof store.lastProject === "object" ? store.lastProject : {}
|
const lastProject = store.lastProject && typeof store.lastProject === "object" ? store.lastProject : {}
|
||||||
const projects = store.projects && typeof store.projects === "object" ? store.projects : {}
|
const projects = store.projects && typeof store.projects === "object" ? store.projects : {}
|
||||||
const nextProjects = { ...(projects as Record<string, unknown>) }
|
const nextProjects = { ...(projects as Record<string, unknown>) }
|
||||||
const nextList = list.includes(args.serverUrl) ? list : [args.serverUrl, ...list]
|
|
||||||
|
|
||||||
const add = (origin: string, directory: string) => {
|
const add = (origin: string, directory: string) => {
|
||||||
const current = nextProjects[origin]
|
const current = nextProjects[origin]
|
||||||
@@ -358,25 +302,22 @@ export async function seedProjects(page: Page, input: { directory: string; extra
|
|||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
key,
|
key,
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
list: nextList,
|
list,
|
||||||
projects: nextProjects,
|
projects: nextProjects,
|
||||||
lastProject,
|
lastProject,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
localStorage.setItem(defaultKey, args.serverUrl)
|
|
||||||
},
|
},
|
||||||
{ directory: input.directory, serverUrl: input.serverUrl ?? serverUrl, extra: input.extra ?? [] },
|
{ directory: input.directory, serverUrl, extra: input.extra ?? [] },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createTestProject(input?: { serverUrl?: string }) {
|
export async function createTestProject() {
|
||||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-e2e-project-"))
|
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-e2e-project-"))
|
||||||
const id = `e2e-${path.basename(root)}`
|
|
||||||
|
|
||||||
await fs.writeFile(path.join(root, "README.md"), `# e2e\n\n${id}\n`)
|
await fs.writeFile(path.join(root, "README.md"), "# e2e\n")
|
||||||
|
|
||||||
execSync("git init", { cwd: root, stdio: "ignore" })
|
execSync("git init", { cwd: root, stdio: "ignore" })
|
||||||
await fs.writeFile(path.join(root, ".git", "opencode"), id)
|
|
||||||
execSync("git config core.fsmonitor false", { cwd: root, stdio: "ignore" })
|
execSync("git config core.fsmonitor false", { cwd: root, stdio: "ignore" })
|
||||||
execSync("git add -A", { cwd: root, stdio: "ignore" })
|
execSync("git add -A", { cwd: root, stdio: "ignore" })
|
||||||
execSync('git -c user.name="e2e" -c user.email="e2e@example.com" commit -m "init" --allow-empty', {
|
execSync('git -c user.name="e2e" -c user.email="e2e@example.com" commit -m "init" --allow-empty', {
|
||||||
@@ -384,7 +325,7 @@ export async function createTestProject(input?: { serverUrl?: string }) {
|
|||||||
stdio: "ignore",
|
stdio: "ignore",
|
||||||
})
|
})
|
||||||
|
|
||||||
return resolveDirectory(root, input?.serverUrl)
|
return resolveDirectory(root)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function cleanupTestProject(directory: string) {
|
export async function cleanupTestProject(directory: string) {
|
||||||
@@ -398,24 +339,12 @@ export function slugFromUrl(url: string) {
|
|||||||
return /\/([^/]+)\/session(?:[/?#]|$)/.exec(url)?.[1] ?? ""
|
return /\/([^/]+)\/session(?:[/?#]|$)/.exec(url)?.[1] ?? ""
|
||||||
}
|
}
|
||||||
|
|
||||||
async function probeSession(page: Page) {
|
|
||||||
return page
|
|
||||||
.evaluate(() => {
|
|
||||||
const win = window as E2EWindow
|
|
||||||
const current = win.__opencode_e2e?.model?.current
|
|
||||||
if (!current) return null
|
|
||||||
return { dir: current.dir, sessionID: current.sessionID }
|
|
||||||
})
|
|
||||||
.catch(() => null as { dir?: string; sessionID?: string } | null)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function waitSlug(page: Page, skip: string[] = []) {
|
export async function waitSlug(page: Page, skip: string[] = []) {
|
||||||
let prev = ""
|
let prev = ""
|
||||||
let next = ""
|
let next = ""
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
() => {
|
||||||
await assertHealthy(page, "waitSlug")
|
|
||||||
const slug = slugFromUrl(page.url())
|
const slug = slugFromUrl(page.url())
|
||||||
if (!slug) return ""
|
if (!slug) return ""
|
||||||
if (skip.includes(slug)) return ""
|
if (skip.includes(slug)) return ""
|
||||||
@@ -433,22 +362,21 @@ export async function waitSlug(page: Page, skip: string[] = []) {
|
|||||||
return next
|
return next
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveSlug(slug: string, input?: { serverUrl?: string }) {
|
export async function resolveSlug(slug: string) {
|
||||||
const directory = base64Decode(slug)
|
const directory = base64Decode(slug)
|
||||||
if (!directory) throw new Error(`Failed to decode workspace slug: ${slug}`)
|
if (!directory) throw new Error(`Failed to decode workspace slug: ${slug}`)
|
||||||
const resolved = await resolveDirectory(directory, input?.serverUrl)
|
const resolved = await resolveDirectory(directory)
|
||||||
return { directory: resolved, slug: base64Encode(resolved), raw: slug }
|
return { directory: resolved, slug: base64Encode(resolved), raw: slug }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function waitDir(page: Page, directory: string, input?: { serverUrl?: string }) {
|
export async function waitDir(page: Page, directory: string) {
|
||||||
const target = await resolveDirectory(directory, input?.serverUrl)
|
const target = await resolveDirectory(directory)
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
await assertHealthy(page, "waitDir")
|
|
||||||
const slug = slugFromUrl(page.url())
|
const slug = slugFromUrl(page.url())
|
||||||
if (!slug) return ""
|
if (!slug) return ""
|
||||||
return resolveSlug(slug, input)
|
return resolveSlug(slug)
|
||||||
.then((item) => item.directory)
|
.then((item) => item.directory)
|
||||||
.catch(() => "")
|
.catch(() => "")
|
||||||
},
|
},
|
||||||
@@ -458,72 +386,6 @@ export async function waitDir(page: Page, directory: string, input?: { serverUrl
|
|||||||
return { directory: target, slug: base64Encode(target) }
|
return { directory: target, slug: base64Encode(target) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function waitSession(page: Page, input: { directory: string; sessionID?: string; serverUrl?: string }) {
|
|
||||||
const target = await resolveDirectory(input.directory, input.serverUrl)
|
|
||||||
await expect
|
|
||||||
.poll(
|
|
||||||
async () => {
|
|
||||||
await assertHealthy(page, "waitSession")
|
|
||||||
const slug = slugFromUrl(page.url())
|
|
||||||
if (!slug) return false
|
|
||||||
const resolved = await resolveSlug(slug, { serverUrl: input.serverUrl }).catch(() => undefined)
|
|
||||||
if (!resolved || resolved.directory !== target) return false
|
|
||||||
const current = sessionIDFromUrl(page.url())
|
|
||||||
if (input.sessionID && current !== input.sessionID) return false
|
|
||||||
if (!input.sessionID && current) return false
|
|
||||||
|
|
||||||
const state = await probeSession(page)
|
|
||||||
if (input.sessionID && (!state || state.sessionID !== input.sessionID)) return false
|
|
||||||
if (!input.sessionID && state?.sessionID) return false
|
|
||||||
if (state?.dir) {
|
|
||||||
const dir = await resolveDirectory(state.dir, input.serverUrl).catch(() => state.dir ?? "")
|
|
||||||
if (dir !== target) return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return page
|
|
||||||
.locator(promptSelector)
|
|
||||||
.first()
|
|
||||||
.isVisible()
|
|
||||||
.catch(() => false)
|
|
||||||
},
|
|
||||||
{ timeout: 45_000 },
|
|
||||||
)
|
|
||||||
.toBe(true)
|
|
||||||
return { directory: target, slug: base64Encode(target) }
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function waitSessionSaved(directory: string, sessionID: string, timeout = 30_000, serverUrl?: string) {
|
|
||||||
const sdk = createSdk(directory, serverUrl)
|
|
||||||
const target = await resolveDirectory(directory, serverUrl)
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(
|
|
||||||
async () => {
|
|
||||||
const data = await sdk.session
|
|
||||||
.get({ sessionID })
|
|
||||||
.then((x) => x.data)
|
|
||||||
.catch(() => undefined)
|
|
||||||
if (!data?.directory) return ""
|
|
||||||
return resolveDirectory(data.directory, serverUrl).catch(() => data.directory)
|
|
||||||
},
|
|
||||||
{ timeout },
|
|
||||||
)
|
|
||||||
.toBe(target)
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(
|
|
||||||
async () => {
|
|
||||||
const items = await sdk.session
|
|
||||||
.messages({ sessionID, limit: 20 })
|
|
||||||
.then((x) => x.data ?? [])
|
|
||||||
.catch(() => [])
|
|
||||||
return items.some((item) => item.info.role === "user")
|
|
||||||
},
|
|
||||||
{ timeout },
|
|
||||||
)
|
|
||||||
.toBe(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function sessionIDFromUrl(url: string) {
|
export function sessionIDFromUrl(url: string) {
|
||||||
const match = /\/session\/([^/?#]+)/.exec(url)
|
const match = /\/session\/([^/?#]+)/.exec(url)
|
||||||
return match?.[1]
|
return match?.[1]
|
||||||
@@ -669,9 +531,8 @@ export async function cleanupSession(input: {
|
|||||||
sessionID: string
|
sessionID: string
|
||||||
directory?: string
|
directory?: string
|
||||||
sdk?: ReturnType<typeof createSdk>
|
sdk?: ReturnType<typeof createSdk>
|
||||||
serverUrl?: string
|
|
||||||
}) {
|
}) {
|
||||||
const sdk = input.sdk ?? (input.directory ? createSdk(input.directory, input.serverUrl) : undefined)
|
const sdk = input.sdk ?? (input.directory ? createSdk(input.directory) : undefined)
|
||||||
if (!sdk) throw new Error("cleanupSession requires sdk or directory")
|
if (!sdk) throw new Error("cleanupSession requires sdk or directory")
|
||||||
await waitSessionIdle(sdk, input.sessionID, 5_000).catch(() => undefined)
|
await waitSessionIdle(sdk, input.sessionID, 5_000).catch(() => undefined)
|
||||||
const current = await status(sdk, input.sessionID).catch(() => undefined)
|
const current = await status(sdk, input.sessionID).catch(() => undefined)
|
||||||
@@ -936,14 +797,8 @@ export async function openStatusPopover(page: Page) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function openProjectMenu(page: Page, projectSlug: string) {
|
export async function openProjectMenu(page: Page, projectSlug: string) {
|
||||||
await openSidebar(page)
|
|
||||||
const item = page.locator(projectSwitchSelector(projectSlug)).first()
|
|
||||||
await expect(item).toBeVisible()
|
|
||||||
await item.hover()
|
|
||||||
|
|
||||||
const trigger = page.locator(projectMenuTriggerSelector(projectSlug)).first()
|
const trigger = page.locator(projectMenuTriggerSelector(projectSlug)).first()
|
||||||
await expect(trigger).toHaveCount(1)
|
await expect(trigger).toHaveCount(1)
|
||||||
await expect(trigger).toBeVisible()
|
|
||||||
|
|
||||||
const menu = page
|
const menu = page
|
||||||
.locator(dropdownMenuContentSelector)
|
.locator(dropdownMenuContentSelector)
|
||||||
@@ -952,7 +807,7 @@ export async function openProjectMenu(page: Page, projectSlug: string) {
|
|||||||
const close = menu.locator(projectCloseMenuSelector(projectSlug)).first()
|
const close = menu.locator(projectCloseMenuSelector(projectSlug)).first()
|
||||||
|
|
||||||
const clicked = await trigger
|
const clicked = await trigger
|
||||||
.click({ force: true, timeout: 1500 })
|
.click({ timeout: 1500 })
|
||||||
.then(() => true)
|
.then(() => true)
|
||||||
.catch(() => false)
|
.catch(() => false)
|
||||||
|
|
||||||
@@ -1023,13 +878,3 @@ export async function openWorkspaceMenu(page: Page, workspaceSlug: string) {
|
|||||||
await expect(menu).toBeVisible()
|
await expect(menu).toBeVisible()
|
||||||
return menu
|
return menu
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function assistantText(sdk: ReturnType<typeof createSdk>, sessionID: string) {
|
|
||||||
const messages = await sdk.session.messages({ sessionID, limit: 50 }).then((r) => r.data ?? [])
|
|
||||||
return messages
|
|
||||||
.filter((m) => m.info.role === "assistant")
|
|
||||||
.flatMap((m) => m.parts)
|
|
||||||
.filter((p) => p.type === "text")
|
|
||||||
.map((p) => p.text)
|
|
||||||
.join("\n")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import { closeDialog, openPalette } from "../actions"
|
import { openPalette } from "../actions"
|
||||||
|
|
||||||
test("search palette opens and closes", async ({ page, gotoSession }) => {
|
test("search palette opens and closes", async ({ page, gotoSession }) => {
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
@@ -9,12 +9,3 @@ test("search palette opens and closes", async ({ page, gotoSession }) => {
|
|||||||
await page.keyboard.press("Escape")
|
await page.keyboard.press("Escape")
|
||||||
await expect(dialog).toHaveCount(0)
|
await expect(dialog).toHaveCount(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("search palette also opens with cmd+p", async ({ page, gotoSession }) => {
|
|
||||||
await gotoSession()
|
|
||||||
|
|
||||||
const dialog = await openPalette(page, "P")
|
|
||||||
|
|
||||||
await closeDialog(page, dialog)
|
|
||||||
await expect(dialog).toHaveCount(0)
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
import { spawn } from "node:child_process"
|
|
||||||
import fs from "node:fs/promises"
|
|
||||||
import net from "node:net"
|
|
||||||
import os from "node:os"
|
|
||||||
import path from "node:path"
|
|
||||||
import { fileURLToPath } from "node:url"
|
|
||||||
|
|
||||||
type Handle = {
|
|
||||||
url: string
|
|
||||||
stop: () => Promise<void>
|
|
||||||
}
|
|
||||||
|
|
||||||
function freePort() {
|
|
||||||
return new Promise<number>((resolve, reject) => {
|
|
||||||
const server = net.createServer()
|
|
||||||
server.once("error", reject)
|
|
||||||
server.listen(0, () => {
|
|
||||||
const address = server.address()
|
|
||||||
if (!address || typeof address === "string") {
|
|
||||||
server.close(() => reject(new Error("Failed to acquire a free port")))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
server.close((err) => {
|
|
||||||
if (err) reject(err)
|
|
||||||
else resolve(address.port)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async function waitForHealth(url: string, probe = "/global/health") {
|
|
||||||
const end = Date.now() + 120_000
|
|
||||||
let last = ""
|
|
||||||
while (Date.now() < end) {
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${url}${probe}`)
|
|
||||||
if (res.ok) return
|
|
||||||
last = `status ${res.status}`
|
|
||||||
} catch (err) {
|
|
||||||
last = err instanceof Error ? err.message : String(err)
|
|
||||||
}
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 250))
|
|
||||||
}
|
|
||||||
throw new Error(`Timed out waiting for backend health at ${url}${probe}${last ? ` (${last})` : ""}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
const LOG_CAP = 100
|
|
||||||
|
|
||||||
function cap(input: string[]) {
|
|
||||||
if (input.length > LOG_CAP) input.splice(0, input.length - LOG_CAP)
|
|
||||||
}
|
|
||||||
|
|
||||||
function tail(input: string[]) {
|
|
||||||
return input.slice(-40).join("")
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function startBackend(label: string): Promise<Handle> {
|
|
||||||
const port = await freePort()
|
|
||||||
const sandbox = await fs.mkdtemp(path.join(os.tmpdir(), `opencode-e2e-${label}-`))
|
|
||||||
const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
|
|
||||||
const repoDir = path.resolve(appDir, "../..")
|
|
||||||
const opencodeDir = path.join(repoDir, "packages", "opencode")
|
|
||||||
const env = {
|
|
||||||
...process.env,
|
|
||||||
OPENCODE_DISABLE_SHARE: process.env.OPENCODE_DISABLE_SHARE ?? "true",
|
|
||||||
OPENCODE_DISABLE_LSP_DOWNLOAD: "true",
|
|
||||||
OPENCODE_DISABLE_DEFAULT_PLUGINS: "true",
|
|
||||||
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: "true",
|
|
||||||
OPENCODE_TEST_HOME: path.join(sandbox, "home"),
|
|
||||||
XDG_DATA_HOME: path.join(sandbox, "share"),
|
|
||||||
XDG_CACHE_HOME: path.join(sandbox, "cache"),
|
|
||||||
XDG_CONFIG_HOME: path.join(sandbox, "config"),
|
|
||||||
XDG_STATE_HOME: path.join(sandbox, "state"),
|
|
||||||
OPENCODE_CLIENT: "app",
|
|
||||||
OPENCODE_STRICT_CONFIG_DEPS: "true",
|
|
||||||
} satisfies Record<string, string | undefined>
|
|
||||||
const out: string[] = []
|
|
||||||
const err: string[] = []
|
|
||||||
const proc = spawn(
|
|
||||||
"bun",
|
|
||||||
["run", "--conditions=browser", "./src/index.ts", "serve", "--port", String(port), "--hostname", "127.0.0.1"],
|
|
||||||
{
|
|
||||||
cwd: opencodeDir,
|
|
||||||
env,
|
|
||||||
stdio: ["ignore", "pipe", "pipe"],
|
|
||||||
},
|
|
||||||
)
|
|
||||||
proc.stdout?.on("data", (chunk) => {
|
|
||||||
out.push(String(chunk))
|
|
||||||
cap(out)
|
|
||||||
})
|
|
||||||
proc.stderr?.on("data", (chunk) => {
|
|
||||||
err.push(String(chunk))
|
|
||||||
cap(err)
|
|
||||||
})
|
|
||||||
|
|
||||||
const url = `http://127.0.0.1:${port}`
|
|
||||||
try {
|
|
||||||
await waitForHealth(url)
|
|
||||||
} catch (error) {
|
|
||||||
proc.kill("SIGTERM")
|
|
||||||
await fs.rm(sandbox, { recursive: true, force: true }).catch(() => undefined)
|
|
||||||
throw new Error(
|
|
||||||
[
|
|
||||||
`Failed to start isolated e2e backend for ${label}`,
|
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
tail(out),
|
|
||||||
tail(err),
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join("\n"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
url,
|
|
||||||
async stop() {
|
|
||||||
if (proc.exitCode === null) {
|
|
||||||
proc.kill("SIGTERM")
|
|
||||||
await new Promise((resolve) => proc.once("exit", () => resolve(undefined))).catch(() => undefined)
|
|
||||||
}
|
|
||||||
await fs.rm(sandbox, { recursive: true, force: true }).catch(() => undefined)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+50
-216
@@ -1,165 +1,32 @@
|
|||||||
import { test as base, expect, type Page } from "@playwright/test"
|
import { test as base, expect, type Page } from "@playwright/test"
|
||||||
import { ManagedRuntime } from "effect"
|
|
||||||
import type { E2EWindow } from "../src/testing/terminal"
|
import type { E2EWindow } from "../src/testing/terminal"
|
||||||
import type { Item, Reply, Usage } from "../../opencode/test/lib/llm-server"
|
import { cleanupSession, cleanupTestProject, createTestProject, seedProjects, sessionIDFromUrl } from "./actions"
|
||||||
import { TestLLMServer } from "../../opencode/test/lib/llm-server"
|
import { promptSelector } from "./selectors"
|
||||||
import { startBackend } from "./backend"
|
|
||||||
import {
|
|
||||||
healthPhase,
|
|
||||||
cleanupSession,
|
|
||||||
cleanupTestProject,
|
|
||||||
createTestProject,
|
|
||||||
setHealthPhase,
|
|
||||||
seedProjects,
|
|
||||||
sessionIDFromUrl,
|
|
||||||
waitSlug,
|
|
||||||
waitSession,
|
|
||||||
} from "./actions"
|
|
||||||
import { createSdk, dirSlug, getWorktree, sessionPath } from "./utils"
|
import { createSdk, dirSlug, getWorktree, sessionPath } from "./utils"
|
||||||
|
|
||||||
type LLMFixture = {
|
|
||||||
url: string
|
|
||||||
push: (...input: (Item | Reply)[]) => Promise<void>
|
|
||||||
pushMatch: (
|
|
||||||
match: (hit: { url: URL; body: Record<string, unknown> }) => boolean,
|
|
||||||
...input: (Item | Reply)[]
|
|
||||||
) => Promise<void>
|
|
||||||
textMatch: (
|
|
||||||
match: (hit: { url: URL; body: Record<string, unknown> }) => boolean,
|
|
||||||
value: string,
|
|
||||||
opts?: { usage?: Usage },
|
|
||||||
) => Promise<void>
|
|
||||||
toolMatch: (
|
|
||||||
match: (hit: { url: URL; body: Record<string, unknown> }) => boolean,
|
|
||||||
name: string,
|
|
||||||
input: unknown,
|
|
||||||
) => Promise<void>
|
|
||||||
text: (value: string, opts?: { usage?: Usage }) => Promise<void>
|
|
||||||
tool: (name: string, input: unknown) => Promise<void>
|
|
||||||
toolHang: (name: string, input: unknown) => Promise<void>
|
|
||||||
reason: (value: string, opts?: { text?: string; usage?: Usage }) => Promise<void>
|
|
||||||
fail: (message?: unknown) => Promise<void>
|
|
||||||
error: (status: number, body: unknown) => Promise<void>
|
|
||||||
hang: () => Promise<void>
|
|
||||||
hold: (value: string, wait: PromiseLike<unknown>) => Promise<void>
|
|
||||||
hits: () => Promise<Array<{ url: URL; body: Record<string, unknown> }>>
|
|
||||||
calls: () => Promise<number>
|
|
||||||
wait: (count: number) => Promise<void>
|
|
||||||
inputs: () => Promise<Record<string, unknown>[]>
|
|
||||||
pending: () => Promise<number>
|
|
||||||
}
|
|
||||||
|
|
||||||
export const settingsKey = "settings.v3"
|
export const settingsKey = "settings.v3"
|
||||||
|
|
||||||
const seedModel = (() => {
|
|
||||||
const [providerID = "opencode", modelID = "big-pickle"] = (
|
|
||||||
process.env.OPENCODE_E2E_MODEL ?? "opencode/big-pickle"
|
|
||||||
).split("/")
|
|
||||||
return {
|
|
||||||
providerID: providerID || "opencode",
|
|
||||||
modelID: modelID || "big-pickle",
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
|
|
||||||
type ProjectHandle = {
|
|
||||||
directory: string
|
|
||||||
slug: string
|
|
||||||
gotoSession: (sessionID?: string) => Promise<void>
|
|
||||||
trackSession: (sessionID: string, directory?: string) => void
|
|
||||||
trackDirectory: (directory: string) => void
|
|
||||||
sdk: ReturnType<typeof createSdk>
|
|
||||||
}
|
|
||||||
|
|
||||||
type ProjectOptions = {
|
|
||||||
extra?: string[]
|
|
||||||
model?: { providerID: string; modelID: string }
|
|
||||||
setup?: (directory: string) => Promise<void>
|
|
||||||
beforeGoto?: (project: { directory: string; sdk: ReturnType<typeof createSdk> }) => Promise<void>
|
|
||||||
}
|
|
||||||
|
|
||||||
type TestFixtures = {
|
type TestFixtures = {
|
||||||
llm: LLMFixture
|
|
||||||
sdk: ReturnType<typeof createSdk>
|
sdk: ReturnType<typeof createSdk>
|
||||||
gotoSession: (sessionID?: string) => Promise<void>
|
gotoSession: (sessionID?: string) => Promise<void>
|
||||||
withProject: <T>(callback: (project: ProjectHandle) => Promise<T>, options?: ProjectOptions) => Promise<T>
|
withProject: <T>(
|
||||||
withBackendProject: <T>(callback: (project: ProjectHandle) => Promise<T>, options?: ProjectOptions) => Promise<T>
|
callback: (project: {
|
||||||
|
directory: string
|
||||||
|
slug: string
|
||||||
|
gotoSession: (sessionID?: string) => Promise<void>
|
||||||
|
trackSession: (sessionID: string, directory?: string) => void
|
||||||
|
trackDirectory: (directory: string) => void
|
||||||
|
}) => Promise<T>,
|
||||||
|
options?: { extra?: string[] },
|
||||||
|
) => Promise<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
type WorkerFixtures = {
|
type WorkerFixtures = {
|
||||||
backend: {
|
|
||||||
url: string
|
|
||||||
sdk: (directory?: string) => ReturnType<typeof createSdk>
|
|
||||||
}
|
|
||||||
directory: string
|
directory: string
|
||||||
slug: string
|
slug: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const test = base.extend<TestFixtures, WorkerFixtures>({
|
export const test = base.extend<TestFixtures, WorkerFixtures>({
|
||||||
backend: [
|
|
||||||
async ({}, use, workerInfo) => {
|
|
||||||
const handle = await startBackend(`w${workerInfo.workerIndex}`)
|
|
||||||
try {
|
|
||||||
await use({
|
|
||||||
url: handle.url,
|
|
||||||
sdk: (directory?: string) => createSdk(directory, handle.url),
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
await handle.stop()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ scope: "worker" },
|
|
||||||
],
|
|
||||||
llm: async ({}, use) => {
|
|
||||||
const rt = ManagedRuntime.make(TestLLMServer.layer)
|
|
||||||
try {
|
|
||||||
const svc = await rt.runPromise(TestLLMServer.asEffect())
|
|
||||||
await use({
|
|
||||||
url: svc.url,
|
|
||||||
push: (...input) => rt.runPromise(svc.push(...input)),
|
|
||||||
pushMatch: (match, ...input) => rt.runPromise(svc.pushMatch(match, ...input)),
|
|
||||||
textMatch: (match, value, opts) => rt.runPromise(svc.textMatch(match, value, opts)),
|
|
||||||
toolMatch: (match, name, input) => rt.runPromise(svc.toolMatch(match, name, input)),
|
|
||||||
text: (value, opts) => rt.runPromise(svc.text(value, opts)),
|
|
||||||
tool: (name, input) => rt.runPromise(svc.tool(name, input)),
|
|
||||||
toolHang: (name, input) => rt.runPromise(svc.toolHang(name, input)),
|
|
||||||
reason: (value, opts) => rt.runPromise(svc.reason(value, opts)),
|
|
||||||
fail: (message) => rt.runPromise(svc.fail(message)),
|
|
||||||
error: (status, body) => rt.runPromise(svc.error(status, body)),
|
|
||||||
hang: () => rt.runPromise(svc.hang),
|
|
||||||
hold: (value, wait) => rt.runPromise(svc.hold(value, wait)),
|
|
||||||
hits: () => rt.runPromise(svc.hits),
|
|
||||||
calls: () => rt.runPromise(svc.calls),
|
|
||||||
wait: (count) => rt.runPromise(svc.wait(count)),
|
|
||||||
inputs: () => rt.runPromise(svc.inputs),
|
|
||||||
pending: () => rt.runPromise(svc.pending),
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
await rt.dispose()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
page: async ({ page }, use) => {
|
|
||||||
let boundary: string | undefined
|
|
||||||
setHealthPhase(page, "test")
|
|
||||||
const consoleHandler = (msg: { text(): string }) => {
|
|
||||||
const text = msg.text()
|
|
||||||
if (!text.includes("[e2e:error-boundary]")) return
|
|
||||||
if (healthPhase(page) === "cleanup") {
|
|
||||||
console.warn(`[e2e:error-boundary][cleanup-warning]\n${text}`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
boundary ||= text
|
|
||||||
console.log(text)
|
|
||||||
}
|
|
||||||
const pageErrorHandler = (err: Error) => {
|
|
||||||
console.log(`[e2e:pageerror] ${err.stack || err.message}`)
|
|
||||||
}
|
|
||||||
page.on("console", consoleHandler)
|
|
||||||
page.on("pageerror", pageErrorHandler)
|
|
||||||
await use(page)
|
|
||||||
page.off("console", consoleHandler)
|
|
||||||
page.off("pageerror", pageErrorHandler)
|
|
||||||
if (boundary) throw new Error(boundary)
|
|
||||||
},
|
|
||||||
directory: [
|
directory: [
|
||||||
async ({}, use) => {
|
async ({}, use) => {
|
||||||
const directory = await getWorktree()
|
const directory = await getWorktree()
|
||||||
@@ -181,83 +48,50 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
|
|||||||
|
|
||||||
const gotoSession = async (sessionID?: string) => {
|
const gotoSession = async (sessionID?: string) => {
|
||||||
await page.goto(sessionPath(directory, sessionID))
|
await page.goto(sessionPath(directory, sessionID))
|
||||||
await waitSession(page, { directory, sessionID })
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
}
|
}
|
||||||
await use(gotoSession)
|
await use(gotoSession)
|
||||||
},
|
},
|
||||||
withProject: async ({ page }, use) => {
|
withProject: async ({ page }, use) => {
|
||||||
await use((callback, options) => runProject(page, callback, options))
|
await use(async (callback, options) => {
|
||||||
},
|
const root = await createTestProject()
|
||||||
withBackendProject: async ({ page, backend }, use) => {
|
const slug = dirSlug(root)
|
||||||
await use((callback, options) =>
|
const sessions = new Map<string, string>()
|
||||||
runProject(page, callback, { ...options, serverUrl: backend.url, sdk: backend.sdk }),
|
const dirs = new Set<string>()
|
||||||
)
|
await seedStorage(page, { directory: root, extra: options?.extra })
|
||||||
|
|
||||||
|
const gotoSession = async (sessionID?: string) => {
|
||||||
|
await page.goto(sessionPath(root, sessionID))
|
||||||
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
|
const current = sessionIDFromUrl(page.url())
|
||||||
|
if (current) trackSession(current)
|
||||||
|
}
|
||||||
|
|
||||||
|
const trackSession = (sessionID: string, directory?: string) => {
|
||||||
|
sessions.set(sessionID, directory ?? root)
|
||||||
|
}
|
||||||
|
|
||||||
|
const trackDirectory = (directory: string) => {
|
||||||
|
if (directory !== root) dirs.add(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await gotoSession()
|
||||||
|
return await callback({ directory: root, slug, gotoSession, trackSession, trackDirectory })
|
||||||
|
} finally {
|
||||||
|
await Promise.allSettled(
|
||||||
|
Array.from(sessions, ([sessionID, directory]) => cleanupSession({ sessionID, directory })),
|
||||||
|
)
|
||||||
|
await Promise.allSettled(Array.from(dirs, (directory) => cleanupTestProject(directory)))
|
||||||
|
await cleanupTestProject(root)
|
||||||
|
}
|
||||||
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
async function runProject<T>(
|
async function seedStorage(page: Page, input: { directory: string; extra?: string[] }) {
|
||||||
page: Page,
|
|
||||||
callback: (project: ProjectHandle) => Promise<T>,
|
|
||||||
options?: ProjectOptions & {
|
|
||||||
serverUrl?: string
|
|
||||||
sdk?: (directory?: string) => ReturnType<typeof createSdk>
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
const url = options?.serverUrl
|
|
||||||
const root = await createTestProject(url ? { serverUrl: url } : undefined)
|
|
||||||
const sdk = options?.sdk?.(root) ?? createSdk(root, url)
|
|
||||||
const sessions = new Map<string, string>()
|
|
||||||
const dirs = new Set<string>()
|
|
||||||
await options?.setup?.(root)
|
|
||||||
await seedStorage(page, {
|
|
||||||
directory: root,
|
|
||||||
extra: options?.extra,
|
|
||||||
model: options?.model,
|
|
||||||
serverUrl: url,
|
|
||||||
})
|
|
||||||
|
|
||||||
const gotoSession = async (sessionID?: string) => {
|
|
||||||
await page.goto(sessionPath(root, sessionID))
|
|
||||||
await waitSession(page, { directory: root, sessionID, serverUrl: url })
|
|
||||||
const current = sessionIDFromUrl(page.url())
|
|
||||||
if (current) trackSession(current)
|
|
||||||
}
|
|
||||||
|
|
||||||
const trackSession = (sessionID: string, directory?: string) => {
|
|
||||||
sessions.set(sessionID, directory ?? root)
|
|
||||||
}
|
|
||||||
|
|
||||||
const trackDirectory = (directory: string) => {
|
|
||||||
if (directory !== root) dirs.add(directory)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await options?.beforeGoto?.({ directory: root, sdk })
|
|
||||||
await gotoSession()
|
|
||||||
const slug = await waitSlug(page)
|
|
||||||
return await callback({ directory: root, slug, gotoSession, trackSession, trackDirectory, sdk })
|
|
||||||
} finally {
|
|
||||||
setHealthPhase(page, "cleanup")
|
|
||||||
await Promise.allSettled(
|
|
||||||
Array.from(sessions, ([sessionID, directory]) => cleanupSession({ sessionID, directory, serverUrl: url })),
|
|
||||||
)
|
|
||||||
await Promise.allSettled(Array.from(dirs, (directory) => cleanupTestProject(directory)))
|
|
||||||
await cleanupTestProject(root)
|
|
||||||
setHealthPhase(page, "test")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function seedStorage(
|
|
||||||
page: Page,
|
|
||||||
input: {
|
|
||||||
directory: string
|
|
||||||
extra?: string[]
|
|
||||||
model?: { providerID: string; modelID: string }
|
|
||||||
serverUrl?: string
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
await seedProjects(page, input)
|
await seedProjects(page, input)
|
||||||
await page.addInitScript((model: { providerID: string; modelID: string }) => {
|
await page.addInitScript(() => {
|
||||||
const win = window as E2EWindow
|
const win = window as E2EWindow
|
||||||
win.__opencode_e2e = {
|
win.__opencode_e2e = {
|
||||||
...win.__opencode_e2e,
|
...win.__opencode_e2e,
|
||||||
@@ -275,12 +109,12 @@ async function seedStorage(
|
|||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
"opencode.global.dat:model",
|
"opencode.global.dat:model",
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
recent: [model],
|
recent: [{ providerID: "opencode", modelID: "big-pickle" }],
|
||||||
user: [],
|
user: [],
|
||||||
variant: {},
|
variant: {},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}, input.model ?? seedModel)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export { expect }
|
export { expect }
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { base64Decode } from "@opencode-ai/util/encode"
|
import { base64Decode } from "@opencode-ai/util/encode"
|
||||||
|
import type { Page } from "@playwright/test"
|
||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import {
|
import {
|
||||||
defocus,
|
defocus,
|
||||||
@@ -6,14 +7,43 @@ import {
|
|||||||
cleanupTestProject,
|
cleanupTestProject,
|
||||||
openSidebar,
|
openSidebar,
|
||||||
sessionIDFromUrl,
|
sessionIDFromUrl,
|
||||||
setWorkspacesEnabled,
|
waitDir,
|
||||||
waitSession,
|
|
||||||
waitSessionSaved,
|
|
||||||
waitSlug,
|
waitSlug,
|
||||||
} from "../actions"
|
} from "../actions"
|
||||||
import { projectSwitchSelector, promptSelector, workspaceItemSelector, workspaceNewSessionSelector } from "../selectors"
|
import { projectSwitchSelector, promptSelector, workspaceItemSelector, workspaceNewSessionSelector } from "../selectors"
|
||||||
import { dirSlug, resolveDirectory } from "../utils"
|
import { dirSlug, resolveDirectory } from "../utils"
|
||||||
|
|
||||||
|
async function workspaces(page: Page, directory: string, enabled: boolean) {
|
||||||
|
await page.evaluate(
|
||||||
|
({ directory, enabled }: { directory: string; enabled: boolean }) => {
|
||||||
|
const key = "opencode.global.dat:layout"
|
||||||
|
const raw = localStorage.getItem(key)
|
||||||
|
const data = raw ? JSON.parse(raw) : {}
|
||||||
|
const sidebar = data.sidebar && typeof data.sidebar === "object" ? data.sidebar : {}
|
||||||
|
const current =
|
||||||
|
sidebar.workspaces && typeof sidebar.workspaces === "object" && !Array.isArray(sidebar.workspaces)
|
||||||
|
? sidebar.workspaces
|
||||||
|
: {}
|
||||||
|
const next = { ...current }
|
||||||
|
|
||||||
|
if (enabled) next[directory] = true
|
||||||
|
if (!enabled) delete next[directory]
|
||||||
|
|
||||||
|
localStorage.setItem(
|
||||||
|
key,
|
||||||
|
JSON.stringify({
|
||||||
|
...data,
|
||||||
|
sidebar: {
|
||||||
|
...sidebar,
|
||||||
|
workspaces: next,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{ directory, enabled },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
test("can switch between projects from sidebar", async ({ page, withProject }) => {
|
test("can switch between projects from sidebar", async ({ page, withProject }) => {
|
||||||
await page.setViewportSize({ width: 1400, height: 800 })
|
await page.setViewportSize({ width: 1400, height: 800 })
|
||||||
|
|
||||||
@@ -54,7 +84,9 @@ test("switching back to a project opens the latest workspace session", async ({
|
|||||||
await withProject(
|
await withProject(
|
||||||
async ({ directory, slug, trackSession, trackDirectory }) => {
|
async ({ directory, slug, trackSession, trackDirectory }) => {
|
||||||
await defocus(page)
|
await defocus(page)
|
||||||
await setWorkspacesEnabled(page, slug, true)
|
await workspaces(page, directory, true)
|
||||||
|
await page.reload()
|
||||||
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
await openSidebar(page)
|
await openSidebar(page)
|
||||||
await expect(page.getByRole("button", { name: "New workspace" }).first()).toBeVisible()
|
await expect(page.getByRole("button", { name: "New workspace" }).first()).toBeVisible()
|
||||||
|
|
||||||
@@ -76,7 +108,8 @@ test("switching back to a project opens the latest workspace session", async ({
|
|||||||
await expect(btn).toBeVisible()
|
await expect(btn).toBeVisible()
|
||||||
await btn.click({ force: true })
|
await btn.click({ force: true })
|
||||||
|
|
||||||
await waitSession(page, { directory: space })
|
await waitSlug(page)
|
||||||
|
await waitDir(page, space)
|
||||||
|
|
||||||
// Create a session by sending a prompt
|
// Create a session by sending a prompt
|
||||||
const prompt = page.locator(promptSelector)
|
const prompt = page.locator(promptSelector)
|
||||||
@@ -90,7 +123,6 @@ test("switching back to a project opens the latest workspace session", async ({
|
|||||||
const created = sessionIDFromUrl(page.url())
|
const created = sessionIDFromUrl(page.url())
|
||||||
if (!created) throw new Error(`Failed to get session ID from url: ${page.url()}`)
|
if (!created) throw new Error(`Failed to get session ID from url: ${page.url()}`)
|
||||||
trackSession(created, space)
|
trackSession(created, space)
|
||||||
await waitSessionSaved(space, created)
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(new RegExp(`/${next}/session/${created}(?:[/?#]|$)`))
|
await expect(page).toHaveURL(new RegExp(`/${next}/session/${created}(?:[/?#]|$)`))
|
||||||
|
|
||||||
@@ -98,14 +130,15 @@ test("switching back to a project opens the latest workspace session", async ({
|
|||||||
|
|
||||||
const otherButton = page.locator(projectSwitchSelector(otherSlug)).first()
|
const otherButton = page.locator(projectSwitchSelector(otherSlug)).first()
|
||||||
await expect(otherButton).toBeVisible()
|
await expect(otherButton).toBeVisible()
|
||||||
await otherButton.click({ force: true })
|
await otherButton.click()
|
||||||
await waitSession(page, { directory: other })
|
await expect(page).toHaveURL(new RegExp(`/${otherSlug}/session`))
|
||||||
|
|
||||||
const rootButton = page.locator(projectSwitchSelector(slug)).first()
|
const rootButton = page.locator(projectSwitchSelector(slug)).first()
|
||||||
await expect(rootButton).toBeVisible()
|
await expect(rootButton).toBeVisible()
|
||||||
await rootButton.click({ force: true })
|
await rootButton.click()
|
||||||
|
|
||||||
await waitSession(page, { directory: space, sessionID: created })
|
await waitDir(page, space)
|
||||||
|
await expect.poll(() => sessionIDFromUrl(page.url()) ?? "").toBe(created)
|
||||||
await expect(page).toHaveURL(new RegExp(`/session/${created}(?:[/?#]|$)`))
|
await expect(page).toHaveURL(new RegExp(`/session/${created}(?:[/?#]|$)`))
|
||||||
},
|
},
|
||||||
{ extra: [other] },
|
{ extra: [other] },
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
import type { Page } from "@playwright/test"
|
import type { Page } from "@playwright/test"
|
||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import {
|
import { openSidebar, resolveSlug, sessionIDFromUrl, setWorkspacesEnabled, waitDir, waitSlug } from "../actions"
|
||||||
openSidebar,
|
|
||||||
resolveSlug,
|
|
||||||
sessionIDFromUrl,
|
|
||||||
setWorkspacesEnabled,
|
|
||||||
waitDir,
|
|
||||||
waitSession,
|
|
||||||
waitSessionSaved,
|
|
||||||
waitSlug,
|
|
||||||
} from "../actions"
|
|
||||||
import { promptSelector, workspaceItemSelector, workspaceNewSessionSelector } from "../selectors"
|
import { promptSelector, workspaceItemSelector, workspaceNewSessionSelector } from "../selectors"
|
||||||
import { createSdk } from "../utils"
|
import { createSdk } from "../utils"
|
||||||
|
|
||||||
@@ -23,7 +14,20 @@ function button(space: { slug: string; raw: string }) {
|
|||||||
|
|
||||||
async function waitWorkspaceReady(page: Page, space: { slug: string; raw: string }) {
|
async function waitWorkspaceReady(page: Page, space: { slug: string; raw: string }) {
|
||||||
await openSidebar(page)
|
await openSidebar(page)
|
||||||
await expect(page.locator(item(space)).first()).toBeVisible({ timeout: 60_000 })
|
await expect
|
||||||
|
.poll(
|
||||||
|
async () => {
|
||||||
|
const row = page.locator(item(space)).first()
|
||||||
|
try {
|
||||||
|
await row.hover({ timeout: 500 })
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ timeout: 60_000 },
|
||||||
|
)
|
||||||
|
.toBe(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createWorkspace(page: Page, root: string, seen: string[]) {
|
async function createWorkspace(page: Page, root: string, seen: string[]) {
|
||||||
@@ -45,8 +49,7 @@ async function openWorkspaceNewSession(page: Page, space: { slug: string; raw: s
|
|||||||
await expect(next).toBeVisible()
|
await expect(next).toBeVisible()
|
||||||
await next.click({ force: true })
|
await next.click({ force: true })
|
||||||
|
|
||||||
await waitSession(page, { directory: space.directory })
|
return waitDir(page, space.directory)
|
||||||
await expect.poll(() => sessionIDFromUrl(page.url()) ?? "").toBe("")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createSessionFromWorkspace(
|
async function createSessionFromWorkspace(
|
||||||
@@ -54,28 +57,39 @@ async function createSessionFromWorkspace(
|
|||||||
space: { slug: string; raw: string; directory: string },
|
space: { slug: string; raw: string; directory: string },
|
||||||
text: string,
|
text: string,
|
||||||
) {
|
) {
|
||||||
await openWorkspaceNewSession(page, space)
|
const next = await openWorkspaceNewSession(page, space)
|
||||||
|
|
||||||
const prompt = page.locator(promptSelector)
|
const prompt = page.locator(promptSelector)
|
||||||
await expect(prompt).toBeVisible()
|
await expect(prompt).toBeVisible()
|
||||||
|
await expect(prompt).toBeEditable()
|
||||||
|
await prompt.click()
|
||||||
|
await expect(prompt).toBeFocused()
|
||||||
await prompt.fill(text)
|
await prompt.fill(text)
|
||||||
await page.keyboard.press("Enter")
|
await expect.poll(async () => ((await prompt.textContent()) ?? "").trim()).toContain(text)
|
||||||
|
await prompt.press("Enter")
|
||||||
|
|
||||||
|
await waitDir(page, next.directory)
|
||||||
|
await expect.poll(() => sessionIDFromUrl(page.url()) ?? "", { timeout: 30_000 }).not.toBe("")
|
||||||
|
|
||||||
await expect.poll(() => sessionIDFromUrl(page.url()) ?? "", { timeout: 15_000 }).not.toBe("")
|
|
||||||
const sessionID = sessionIDFromUrl(page.url())
|
const sessionID = sessionIDFromUrl(page.url())
|
||||||
if (!sessionID) throw new Error(`Failed to parse session id from url: ${page.url()}`)
|
if (!sessionID) throw new Error(`Failed to parse session id from url: ${page.url()}`)
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/session/${sessionID}(?:[/?#]|$)`))
|
||||||
|
return { sessionID, slug: next.slug }
|
||||||
|
}
|
||||||
|
|
||||||
await waitSessionSaved(space.directory, sessionID)
|
async function sessionDirectory(directory: string, sessionID: string) {
|
||||||
await createSdk(space.directory)
|
const info = await createSdk(directory)
|
||||||
.session.abort({ sessionID })
|
.session.get({ sessionID })
|
||||||
|
.then((x) => x.data)
|
||||||
.catch(() => undefined)
|
.catch(() => undefined)
|
||||||
return sessionID
|
if (!info) return ""
|
||||||
|
return info.directory
|
||||||
}
|
}
|
||||||
|
|
||||||
test("new sessions from sidebar workspace actions stay in selected workspace", async ({ page, withProject }) => {
|
test("new sessions from sidebar workspace actions stay in selected workspace", async ({ page, withProject }) => {
|
||||||
await page.setViewportSize({ width: 1400, height: 800 })
|
await page.setViewportSize({ width: 1400, height: 800 })
|
||||||
|
|
||||||
await withProject(async ({ slug: root, trackDirectory, trackSession }) => {
|
await withProject(async ({ directory, slug: root, trackSession, trackDirectory }) => {
|
||||||
await openSidebar(page)
|
await openSidebar(page)
|
||||||
await setWorkspacesEnabled(page, root, true)
|
await setWorkspacesEnabled(page, root, true)
|
||||||
|
|
||||||
@@ -87,8 +101,17 @@ test("new sessions from sidebar workspace actions stay in selected workspace", a
|
|||||||
trackDirectory(second.directory)
|
trackDirectory(second.directory)
|
||||||
await waitWorkspaceReady(page, second)
|
await waitWorkspaceReady(page, second)
|
||||||
|
|
||||||
trackSession(await createSessionFromWorkspace(page, first, `workspace one ${Date.now()}`), first.directory)
|
const firstSession = await createSessionFromWorkspace(page, first.slug, `workspace one ${Date.now()}`)
|
||||||
trackSession(await createSessionFromWorkspace(page, second, `workspace two ${Date.now()}`), second.directory)
|
trackSession(firstSession.sessionID, first.directory)
|
||||||
trackSession(await createSessionFromWorkspace(page, first, `workspace one again ${Date.now()}`), first.directory)
|
|
||||||
|
const secondSession = await createSessionFromWorkspace(page, second.slug, `workspace two ${Date.now()}`)
|
||||||
|
trackSession(secondSession.sessionID, second.directory)
|
||||||
|
|
||||||
|
const thirdSession = await createSessionFromWorkspace(page, first.slug, `workspace one again ${Date.now()}`)
|
||||||
|
trackSession(thirdSession.sessionID, first.directory)
|
||||||
|
|
||||||
|
await expect.poll(() => sessionDirectory(first.directory, firstSession.sessionID)).toBe(first.directory)
|
||||||
|
await expect.poll(() => sessionDirectory(second.directory, secondSession.sessionID)).toBe(second.directory)
|
||||||
|
await expect.poll(() => sessionDirectory(first.directory, thirdSession.sessionID)).toBe(first.directory)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import { createSdk } from "../utils"
|
|
||||||
|
|
||||||
export const openaiModel = { providerID: "openai", modelID: "gpt-5.3-chat-latest" }
|
|
||||||
|
|
||||||
type Hit = { body: Record<string, unknown> }
|
|
||||||
|
|
||||||
export function bodyText(hit: Hit) {
|
|
||||||
return JSON.stringify(hit.body)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function titleMatch(hit: Hit) {
|
|
||||||
return bodyText(hit).includes("Generate a title for this conversation")
|
|
||||||
}
|
|
||||||
|
|
||||||
export function promptMatch(token: string) {
|
|
||||||
return (hit: Hit) => bodyText(hit).includes(token)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function withMockOpenAI<T>(input: { serverUrl: string; llmUrl: string; fn: () => Promise<T> }) {
|
|
||||||
const sdk = createSdk(undefined, input.serverUrl)
|
|
||||||
const prev = await sdk.global.config.get().then((res) => res.data ?? {})
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sdk.global.config.update({
|
|
||||||
config: {
|
|
||||||
...prev,
|
|
||||||
model: `${openaiModel.providerID}/${openaiModel.modelID}`,
|
|
||||||
enabled_providers: ["openai"],
|
|
||||||
provider: {
|
|
||||||
...prev.provider,
|
|
||||||
openai: {
|
|
||||||
...prev.provider?.openai,
|
|
||||||
options: {
|
|
||||||
...prev.provider?.openai?.options,
|
|
||||||
apiKey: "test-key",
|
|
||||||
baseURL: input.llmUrl,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
return await input.fn()
|
|
||||||
} finally {
|
|
||||||
await sdk.global.config.update({ config: prev })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,52 +1,47 @@
|
|||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import { promptSelector } from "../selectors"
|
import { promptSelector } from "../selectors"
|
||||||
import { assistantText, sessionIDFromUrl, withSession } from "../actions"
|
import { cleanupSession, sessionIDFromUrl, withSession } from "../actions"
|
||||||
import { openaiModel, promptMatch, titleMatch, withMockOpenAI } from "./mock"
|
|
||||||
|
|
||||||
const text = (value: string | null) => (value ?? "").replace(/\u200B/g, "").trim()
|
const text = (value: string | null) => (value ?? "").replace(/\u200B/g, "").trim()
|
||||||
|
|
||||||
// Regression test for Issue #12453: the synchronous POST /message endpoint holds
|
// Regression test for Issue #12453: the synchronous POST /message endpoint holds
|
||||||
// the connection open while the agent works, causing "Failed to fetch" over
|
// the connection open while the agent works, causing "Failed to fetch" over
|
||||||
// VPN/Tailscale. The fix switches to POST /prompt_async which returns immediately.
|
// VPN/Tailscale. The fix switches to POST /prompt_async which returns immediately.
|
||||||
test("prompt succeeds when sync message endpoint is unreachable", async ({
|
test("prompt succeeds when sync message endpoint is unreachable", async ({ page, sdk, gotoSession }) => {
|
||||||
page,
|
|
||||||
llm,
|
|
||||||
backend,
|
|
||||||
withBackendProject,
|
|
||||||
}) => {
|
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
// Simulate Tailscale/VPN killing the long-lived sync connection
|
// Simulate Tailscale/VPN killing the long-lived sync connection
|
||||||
await page.route("**/session/*/message", (route) => route.abort("connectionfailed"))
|
await page.route("**/session/*/message", (route) => route.abort("connectionfailed"))
|
||||||
|
|
||||||
await withMockOpenAI({
|
await gotoSession()
|
||||||
serverUrl: backend.url,
|
|
||||||
llmUrl: llm.url,
|
|
||||||
fn: async () => {
|
|
||||||
const token = `E2E_ASYNC_${Date.now()}`
|
|
||||||
await llm.textMatch(titleMatch, "E2E Title")
|
|
||||||
await llm.textMatch(promptMatch(token), token)
|
|
||||||
|
|
||||||
await withBackendProject(
|
const token = `E2E_ASYNC_${Date.now()}`
|
||||||
async (project) => {
|
await page.locator(promptSelector).click()
|
||||||
await page.locator(promptSelector).click()
|
await page.keyboard.type(`Reply with exactly: ${token}`)
|
||||||
await page.keyboard.type(`Reply with exactly: ${token}`)
|
await page.keyboard.press("Enter")
|
||||||
await page.keyboard.press("Enter")
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/session\/[^/?#]+/, { timeout: 30_000 })
|
await expect(page).toHaveURL(/\/session\/[^/?#]+/, { timeout: 30_000 })
|
||||||
const sessionID = sessionIDFromUrl(page.url())!
|
const sessionID = sessionIDFromUrl(page.url())!
|
||||||
project.trackSession(sessionID)
|
|
||||||
|
|
||||||
await expect.poll(() => llm.calls()).toBeGreaterThanOrEqual(1)
|
try {
|
||||||
|
// Agent response arrives via SSE despite sync endpoint being dead
|
||||||
await expect.poll(() => assistantText(project.sdk, sessionID), { timeout: 90_000 }).toContain(token)
|
await expect
|
||||||
},
|
.poll(
|
||||||
{
|
async () => {
|
||||||
model: openaiModel,
|
const messages = await sdk.session.messages({ sessionID, limit: 50 }).then((r) => r.data ?? [])
|
||||||
|
return messages
|
||||||
|
.filter((m) => m.info.role === "assistant")
|
||||||
|
.flatMap((m) => m.parts)
|
||||||
|
.filter((p) => p.type === "text")
|
||||||
|
.map((p) => p.text)
|
||||||
|
.join("\n")
|
||||||
},
|
},
|
||||||
|
{ timeout: 90_000 },
|
||||||
)
|
)
|
||||||
},
|
.toContain(token)
|
||||||
})
|
} finally {
|
||||||
|
await cleanupSession({ sdk, sessionID })
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
test("failed prompt send restores the composer input", async ({ page, sdk, gotoSession }) => {
|
test("failed prompt send restores the composer input", async ({ page, sdk, gotoSession }) => {
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import type { ToolPart } from "@opencode-ai/sdk/v2/client"
|
import type { ToolPart } from "@opencode-ai/sdk/v2/client"
|
||||||
import type { Page } from "@playwright/test"
|
import type { Page } from "@playwright/test"
|
||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import { assistantText, sessionIDFromUrl } from "../actions"
|
import { withSession } from "../actions"
|
||||||
import { promptSelector } from "../selectors"
|
import { promptSelector } from "../selectors"
|
||||||
import { openaiModel, promptMatch, titleMatch, withMockOpenAI } from "./mock"
|
|
||||||
|
|
||||||
const text = (value: string | null) => (value ?? "").replace(/\u200B/g, "").trim()
|
const text = (value: string | null) => (value ?? "").replace(/\u200B/g, "").trim()
|
||||||
|
|
||||||
@@ -44,13 +43,20 @@ async function wait(page: Page, value: string) {
|
|||||||
await expect.poll(async () => text(await page.locator(promptSelector).textContent())).toBe(value)
|
await expect.poll(async () => text(await page.locator(promptSelector).textContent())).toBe(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function reply(
|
async function reply(sdk: Parameters<typeof withSession>[0], sessionID: string, token: string) {
|
||||||
sdk: { session: { messages: Parameters<typeof assistantText>[0]["session"] } },
|
|
||||||
sessionID: string,
|
|
||||||
token: string,
|
|
||||||
) {
|
|
||||||
await expect
|
await expect
|
||||||
.poll(() => assistantText(sdk as Parameters<typeof assistantText>[0], sessionID), { timeout: 90_000 })
|
.poll(
|
||||||
|
async () => {
|
||||||
|
const messages = await sdk.session.messages({ sessionID, limit: 50 }).then((r) => r.data ?? [])
|
||||||
|
return messages
|
||||||
|
.filter((item) => item.info.role === "assistant")
|
||||||
|
.flatMap((item) => item.parts)
|
||||||
|
.filter((item) => item.type === "text")
|
||||||
|
.map((item) => item.text)
|
||||||
|
.join("\n")
|
||||||
|
},
|
||||||
|
{ timeout: 90_000 },
|
||||||
|
)
|
||||||
.toContain(token)
|
.toContain(token)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,145 +79,103 @@ async function shell(sdk: Parameters<typeof withSession>[0], sessionID: string,
|
|||||||
.toContain(token)
|
.toContain(token)
|
||||||
}
|
}
|
||||||
|
|
||||||
test("prompt history restores unsent draft with arrow navigation", async ({
|
test("prompt history restores unsent draft with arrow navigation", async ({ page, sdk, gotoSession }) => {
|
||||||
page,
|
|
||||||
llm,
|
|
||||||
backend,
|
|
||||||
withBackendProject,
|
|
||||||
}) => {
|
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
await withMockOpenAI({
|
await withSession(sdk, `e2e prompt history ${Date.now()}`, async (session) => {
|
||||||
serverUrl: backend.url,
|
await gotoSession(session.id)
|
||||||
llmUrl: llm.url,
|
|
||||||
fn: async () => {
|
|
||||||
const firstToken = `E2E_HISTORY_ONE_${Date.now()}`
|
|
||||||
const secondToken = `E2E_HISTORY_TWO_${Date.now()}`
|
|
||||||
const first = `Reply with exactly: ${firstToken}`
|
|
||||||
const second = `Reply with exactly: ${secondToken}`
|
|
||||||
const draft = `draft ${Date.now()}`
|
|
||||||
|
|
||||||
await llm.textMatch(titleMatch, "E2E Title")
|
const prompt = page.locator(promptSelector)
|
||||||
await llm.textMatch(promptMatch(firstToken), firstToken)
|
const firstToken = `E2E_HISTORY_ONE_${Date.now()}`
|
||||||
await llm.textMatch(promptMatch(secondToken), secondToken)
|
const secondToken = `E2E_HISTORY_TWO_${Date.now()}`
|
||||||
|
const first = `Reply with exactly: ${firstToken}`
|
||||||
|
const second = `Reply with exactly: ${secondToken}`
|
||||||
|
const draft = `draft ${Date.now()}`
|
||||||
|
|
||||||
await withBackendProject(
|
await prompt.click()
|
||||||
async (project) => {
|
await page.keyboard.type(first)
|
||||||
const prompt = page.locator(promptSelector)
|
await page.keyboard.press("Enter")
|
||||||
|
await wait(page, "")
|
||||||
|
await reply(sdk, session.id, firstToken)
|
||||||
|
|
||||||
await prompt.click()
|
await prompt.click()
|
||||||
await page.keyboard.type(first)
|
await page.keyboard.type(second)
|
||||||
await page.keyboard.press("Enter")
|
await page.keyboard.press("Enter")
|
||||||
await wait(page, "")
|
await wait(page, "")
|
||||||
|
await reply(sdk, session.id, secondToken)
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/session\/[^/?#]+/, { timeout: 30_000 })
|
await prompt.click()
|
||||||
const sessionID = sessionIDFromUrl(page.url())!
|
await page.keyboard.type(draft)
|
||||||
project.trackSession(sessionID)
|
await wait(page, draft)
|
||||||
await reply(project.sdk, sessionID, firstToken)
|
|
||||||
|
|
||||||
await prompt.click()
|
await edge(page, "start")
|
||||||
await page.keyboard.type(second)
|
await page.keyboard.press("ArrowUp")
|
||||||
await page.keyboard.press("Enter")
|
await wait(page, second)
|
||||||
await wait(page, "")
|
|
||||||
await reply(project.sdk, sessionID, secondToken)
|
|
||||||
|
|
||||||
await prompt.click()
|
await page.keyboard.press("ArrowUp")
|
||||||
await page.keyboard.type(draft)
|
await wait(page, first)
|
||||||
await wait(page, draft)
|
|
||||||
|
|
||||||
await prompt.fill("")
|
await page.keyboard.press("ArrowDown")
|
||||||
await wait(page, "")
|
await wait(page, second)
|
||||||
|
|
||||||
await page.keyboard.press("ArrowUp")
|
await page.keyboard.press("ArrowDown")
|
||||||
await wait(page, second)
|
await wait(page, draft)
|
||||||
|
|
||||||
await page.keyboard.press("ArrowUp")
|
|
||||||
await wait(page, first)
|
|
||||||
|
|
||||||
await page.keyboard.press("ArrowDown")
|
|
||||||
await wait(page, second)
|
|
||||||
|
|
||||||
await page.keyboard.press("ArrowDown")
|
|
||||||
await wait(page, "")
|
|
||||||
},
|
|
||||||
{
|
|
||||||
model: openaiModel,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("shell history stays separate from normal prompt history", async ({ page, llm, backend, withBackendProject }) => {
|
test("shell history stays separate from normal prompt history", async ({ page, sdk, gotoSession }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
await withMockOpenAI({
|
await withSession(sdk, `e2e shell history ${Date.now()}`, async (session) => {
|
||||||
serverUrl: backend.url,
|
await gotoSession(session.id)
|
||||||
llmUrl: llm.url,
|
|
||||||
fn: async () => {
|
|
||||||
const firstToken = `E2E_SHELL_ONE_${Date.now()}`
|
|
||||||
const secondToken = `E2E_SHELL_TWO_${Date.now()}`
|
|
||||||
const normalToken = `E2E_NORMAL_${Date.now()}`
|
|
||||||
const first = `echo ${firstToken}`
|
|
||||||
const second = `echo ${secondToken}`
|
|
||||||
const normal = `Reply with exactly: ${normalToken}`
|
|
||||||
|
|
||||||
await llm.textMatch(titleMatch, "E2E Title")
|
const prompt = page.locator(promptSelector)
|
||||||
await llm.textMatch(promptMatch(normalToken), normalToken)
|
const firstToken = `E2E_SHELL_ONE_${Date.now()}`
|
||||||
|
const secondToken = `E2E_SHELL_TWO_${Date.now()}`
|
||||||
|
const normalToken = `E2E_NORMAL_${Date.now()}`
|
||||||
|
const first = `echo ${firstToken}`
|
||||||
|
const second = `echo ${secondToken}`
|
||||||
|
const normal = `Reply with exactly: ${normalToken}`
|
||||||
|
|
||||||
await withBackendProject(
|
await prompt.click()
|
||||||
async (project) => {
|
await page.keyboard.type("!")
|
||||||
const prompt = page.locator(promptSelector)
|
await page.keyboard.type(first)
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
await wait(page, "")
|
||||||
|
await shell(sdk, session.id, first, firstToken)
|
||||||
|
|
||||||
await prompt.click()
|
await prompt.click()
|
||||||
await page.keyboard.type("!")
|
await page.keyboard.type("!")
|
||||||
await page.keyboard.type(first)
|
await page.keyboard.type(second)
|
||||||
await page.keyboard.press("Enter")
|
await page.keyboard.press("Enter")
|
||||||
await wait(page, "")
|
await wait(page, "")
|
||||||
|
await shell(sdk, session.id, second, secondToken)
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/session\/[^/?#]+/, { timeout: 30_000 })
|
await prompt.click()
|
||||||
const sessionID = sessionIDFromUrl(page.url())!
|
await page.keyboard.type("!")
|
||||||
project.trackSession(sessionID)
|
await page.keyboard.press("ArrowUp")
|
||||||
await shell(project.sdk, sessionID, first, firstToken)
|
await wait(page, second)
|
||||||
|
|
||||||
await prompt.click()
|
await page.keyboard.press("ArrowUp")
|
||||||
await page.keyboard.type("!")
|
await wait(page, first)
|
||||||
await page.keyboard.type(second)
|
|
||||||
await page.keyboard.press("Enter")
|
|
||||||
await wait(page, "")
|
|
||||||
await shell(project.sdk, sessionID, second, secondToken)
|
|
||||||
|
|
||||||
await prompt.click()
|
await page.keyboard.press("ArrowDown")
|
||||||
await page.keyboard.type("!")
|
await wait(page, second)
|
||||||
await page.keyboard.press("ArrowUp")
|
|
||||||
await wait(page, second)
|
|
||||||
|
|
||||||
await page.keyboard.press("ArrowUp")
|
await page.keyboard.press("ArrowDown")
|
||||||
await wait(page, first)
|
await wait(page, "")
|
||||||
|
|
||||||
await page.keyboard.press("ArrowDown")
|
await page.keyboard.press("Escape")
|
||||||
await wait(page, second)
|
await wait(page, "")
|
||||||
|
|
||||||
await page.keyboard.press("ArrowDown")
|
await prompt.click()
|
||||||
await wait(page, "")
|
await page.keyboard.type(normal)
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
await wait(page, "")
|
||||||
|
await reply(sdk, session.id, normalToken)
|
||||||
|
|
||||||
await page.keyboard.press("Escape")
|
await prompt.click()
|
||||||
await wait(page, "")
|
await page.keyboard.press("ArrowUp")
|
||||||
|
await wait(page, normal)
|
||||||
await prompt.click()
|
|
||||||
await page.keyboard.type(normal)
|
|
||||||
await page.keyboard.press("Enter")
|
|
||||||
await wait(page, "")
|
|
||||||
await reply(project.sdk, sessionID, normalToken)
|
|
||||||
|
|
||||||
await prompt.click()
|
|
||||||
await page.keyboard.press("ArrowUp")
|
|
||||||
await wait(page, normal)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
model: openaiModel,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { ToolPart } from "@opencode-ai/sdk/v2/client"
|
|||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import { sessionIDFromUrl } from "../actions"
|
import { sessionIDFromUrl } from "../actions"
|
||||||
import { promptSelector } from "../selectors"
|
import { promptSelector } from "../selectors"
|
||||||
|
import { createSdk } from "../utils"
|
||||||
|
|
||||||
const isBash = (part: unknown): part is ToolPart => {
|
const isBash = (part: unknown): part is ToolPart => {
|
||||||
if (!part || typeof part !== "object") return false
|
if (!part || typeof part !== "object") return false
|
||||||
@@ -10,12 +11,13 @@ const isBash = (part: unknown): part is ToolPart => {
|
|||||||
return "state" in part
|
return "state" in part
|
||||||
}
|
}
|
||||||
|
|
||||||
test("shell mode runs a command in the project directory", async ({ page, withBackendProject }) => {
|
test("shell mode runs a command in the project directory", async ({ page, withProject }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
await withBackendProject(async ({ directory, gotoSession, trackSession, sdk }) => {
|
await withProject(async ({ directory, gotoSession, trackSession }) => {
|
||||||
|
const sdk = createSdk(directory)
|
||||||
const prompt = page.locator(promptSelector)
|
const prompt = page.locator(promptSelector)
|
||||||
const cmd = process.platform === "win32" ? "dir" : "command ls"
|
const cmd = process.platform === "win32" ? "dir" : "ls"
|
||||||
|
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
await prompt.click()
|
await prompt.click()
|
||||||
|
|||||||
@@ -22,45 +22,43 @@ async function seed(sdk: Parameters<typeof withSession>[0], sessionID: string) {
|
|||||||
.toBeGreaterThan(0)
|
.toBeGreaterThan(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
test("/share and /unshare update session share state", async ({ page, withBackendProject }) => {
|
test("/share and /unshare update session share state", async ({ page, sdk, gotoSession }) => {
|
||||||
test.skip(shareDisabled, "Share is disabled in this environment (OPENCODE_DISABLE_SHARE).")
|
test.skip(shareDisabled, "Share is disabled in this environment (OPENCODE_DISABLE_SHARE).")
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withSession(sdk, `e2e slash share ${Date.now()}`, async (session) => {
|
||||||
await withSession(project.sdk, `e2e slash share ${Date.now()}`, async (session) => {
|
const prompt = page.locator(promptSelector)
|
||||||
const prompt = page.locator(promptSelector)
|
|
||||||
|
|
||||||
await seed(project.sdk, session.id)
|
await seed(sdk, session.id)
|
||||||
await project.gotoSession(session.id)
|
await gotoSession(session.id)
|
||||||
|
|
||||||
await prompt.click()
|
await prompt.click()
|
||||||
await page.keyboard.type("/share")
|
await page.keyboard.type("/share")
|
||||||
await expect(page.locator('[data-slash-id="session.share"]').first()).toBeVisible()
|
await expect(page.locator('[data-slash-id="session.share"]').first()).toBeVisible()
|
||||||
await page.keyboard.press("Enter")
|
await page.keyboard.press("Enter")
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
const data = await sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
||||||
return data?.share?.url || undefined
|
return data?.share?.url || undefined
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.not.toBeUndefined()
|
.not.toBeUndefined()
|
||||||
|
|
||||||
await prompt.click()
|
await prompt.click()
|
||||||
await page.keyboard.type("/unshare")
|
await page.keyboard.type("/unshare")
|
||||||
await expect(page.locator('[data-slash-id="session.unshare"]').first()).toBeVisible()
|
await expect(page.locator('[data-slash-id="session.unshare"]').first()).toBeVisible()
|
||||||
await page.keyboard.press("Enter")
|
await page.keyboard.press("Enter")
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
const data = await sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
||||||
return data?.share?.url || undefined
|
return data?.share?.url || undefined
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.toBeUndefined()
|
.toBeUndefined()
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import { promptSelector } from "../selectors"
|
import { promptSelector } from "../selectors"
|
||||||
import { assistantText, sessionIDFromUrl } from "../actions"
|
import { cleanupSession, sessionIDFromUrl, withSession } from "../actions"
|
||||||
import { openaiModel, promptMatch, titleMatch, withMockOpenAI } from "./mock"
|
|
||||||
|
|
||||||
test("can send a prompt and receive a reply", async ({ page, llm, backend, withBackendProject }) => {
|
test("can send a prompt and receive a reply", async ({ page, sdk, gotoSession }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
const pageErrors: string[] = []
|
const pageErrors: string[] = []
|
||||||
@@ -12,44 +11,42 @@ test("can send a prompt and receive a reply", async ({ page, llm, backend, withB
|
|||||||
}
|
}
|
||||||
page.on("pageerror", onPageError)
|
page.on("pageerror", onPageError)
|
||||||
|
|
||||||
|
await gotoSession()
|
||||||
|
|
||||||
|
const token = `E2E_OK_${Date.now()}`
|
||||||
|
|
||||||
|
const prompt = page.locator(promptSelector)
|
||||||
|
await prompt.click()
|
||||||
|
await page.keyboard.type(`Reply with exactly: ${token}`)
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/session\/[^/?#]+/, { timeout: 30_000 })
|
||||||
|
|
||||||
|
const sessionID = (() => {
|
||||||
|
const id = sessionIDFromUrl(page.url())
|
||||||
|
if (!id) throw new Error(`Failed to parse session id from url: ${page.url()}`)
|
||||||
|
return id
|
||||||
|
})()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await withMockOpenAI({
|
await expect
|
||||||
serverUrl: backend.url,
|
.poll(
|
||||||
llmUrl: llm.url,
|
async () => {
|
||||||
fn: async () => {
|
const messages = await sdk.session.messages({ sessionID, limit: 50 }).then((r) => r.data ?? [])
|
||||||
const token = `E2E_OK_${Date.now()}`
|
return messages
|
||||||
|
.filter((m) => m.info.role === "assistant")
|
||||||
|
.flatMap((m) => m.parts)
|
||||||
|
.filter((p) => p.type === "text")
|
||||||
|
.map((p) => p.text)
|
||||||
|
.join("\n")
|
||||||
|
},
|
||||||
|
{ timeout: 90_000 },
|
||||||
|
)
|
||||||
|
|
||||||
await llm.textMatch(titleMatch, "E2E Title")
|
.toContain(token)
|
||||||
await llm.textMatch(promptMatch(token), token)
|
|
||||||
|
|
||||||
await withBackendProject(
|
|
||||||
async (project) => {
|
|
||||||
const prompt = page.locator(promptSelector)
|
|
||||||
await prompt.click()
|
|
||||||
await page.keyboard.type(`Reply with exactly: ${token}`)
|
|
||||||
await page.keyboard.press("Enter")
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/session\/[^/?#]+/, { timeout: 30_000 })
|
|
||||||
|
|
||||||
const sessionID = (() => {
|
|
||||||
const id = sessionIDFromUrl(page.url())
|
|
||||||
if (!id) throw new Error(`Failed to parse session id from url: ${page.url()}`)
|
|
||||||
return id
|
|
||||||
})()
|
|
||||||
project.trackSession(sessionID)
|
|
||||||
|
|
||||||
await expect.poll(() => llm.calls()).toBeGreaterThanOrEqual(1)
|
|
||||||
|
|
||||||
await expect.poll(() => assistantText(project.sdk, sessionID), { timeout: 30_000 }).toContain(token)
|
|
||||||
},
|
|
||||||
{
|
|
||||||
model: openaiModel,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} finally {
|
} finally {
|
||||||
page.off("pageerror", onPageError)
|
page.off("pageerror", onPageError)
|
||||||
|
await cleanupSession({ sdk, sessionID })
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pageErrors.length > 0) {
|
if (pageErrors.length > 0) {
|
||||||
|
|||||||
@@ -19,8 +19,7 @@ export const promptVariantSelector = '[data-component="prompt-variant-control"]'
|
|||||||
export const settingsLanguageSelectSelector = '[data-action="settings-language"]'
|
export const settingsLanguageSelectSelector = '[data-action="settings-language"]'
|
||||||
export const settingsColorSchemeSelector = '[data-action="settings-color-scheme"]'
|
export const settingsColorSchemeSelector = '[data-action="settings-color-scheme"]'
|
||||||
export const settingsThemeSelector = '[data-action="settings-theme"]'
|
export const settingsThemeSelector = '[data-action="settings-theme"]'
|
||||||
export const settingsCodeFontSelector = '[data-action="settings-code-font"]'
|
export const settingsFontSelector = '[data-action="settings-font"]'
|
||||||
export const settingsUIFontSelector = '[data-action="settings-ui-font"]'
|
|
||||||
export const settingsNotificationsAgentSelector = '[data-action="settings-notifications-agent"]'
|
export const settingsNotificationsAgentSelector = '[data-action="settings-notifications-agent"]'
|
||||||
export const settingsNotificationsPermissionsSelector = '[data-action="settings-notifications-permissions"]'
|
export const settingsNotificationsPermissionsSelector = '[data-action="settings-notifications-permissions"]'
|
||||||
export const settingsNotificationsErrorsSelector = '[data-action="settings-notifications-errors"]'
|
export const settingsNotificationsErrorsSelector = '[data-action="settings-notifications-errors"]'
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { seedSessionTask, withSession } from "../actions"
|
import { seedSessionTask, withSession } from "../actions"
|
||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
|
|
||||||
test("task tool child-session link does not trigger stale show errors", async ({ page, withBackendProject }) => {
|
test("task tool child-session link does not trigger stale show errors", async ({ page, sdk, gotoSession }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
const errs: string[] = []
|
const errs: string[] = []
|
||||||
@@ -10,32 +10,28 @@ test("task tool child-session link does not trigger stale show errors", async ({
|
|||||||
}
|
}
|
||||||
page.on("pageerror", onError)
|
page.on("pageerror", onError)
|
||||||
|
|
||||||
await withBackendProject(async ({ gotoSession, trackSession, sdk }) => {
|
await withSession(sdk, `e2e child nav ${Date.now()}`, async (session) => {
|
||||||
await withSession(sdk, `e2e child nav ${Date.now()}`, async (session) => {
|
const child = await seedSessionTask(sdk, {
|
||||||
trackSession(session.id)
|
sessionID: session.id,
|
||||||
const child = await seedSessionTask(sdk, {
|
description: "Open child session",
|
||||||
sessionID: session.id,
|
prompt: "Search the repository for AssistantParts and then reply with exactly CHILD_OK.",
|
||||||
description: "Open child session",
|
|
||||||
prompt: "Search the repository for AssistantParts and then reply with exactly CHILD_OK.",
|
|
||||||
})
|
|
||||||
trackSession(child.sessionID)
|
|
||||||
|
|
||||||
try {
|
|
||||||
await gotoSession(session.id)
|
|
||||||
|
|
||||||
const link = page
|
|
||||||
.locator("a.subagent-link")
|
|
||||||
.filter({ hasText: /open child session/i })
|
|
||||||
.first()
|
|
||||||
await expect(link).toBeVisible({ timeout: 30_000 })
|
|
||||||
await link.click()
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(new RegExp(`/session/${child.sessionID}(?:[/?#]|$)`), { timeout: 30_000 })
|
|
||||||
await page.waitForTimeout(1000)
|
|
||||||
expect(errs).toEqual([])
|
|
||||||
} finally {
|
|
||||||
page.off("pageerror", onError)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
await gotoSession(session.id)
|
||||||
|
|
||||||
|
const link = page
|
||||||
|
.locator("a.subagent-link")
|
||||||
|
.filter({ hasText: /open child session/i })
|
||||||
|
.first()
|
||||||
|
await expect(link).toBeVisible({ timeout: 30_000 })
|
||||||
|
await link.click()
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/session/${child.sessionID}(?:[/?#]|$)`), { timeout: 30_000 })
|
||||||
|
await page.waitForTimeout(1000)
|
||||||
|
expect(errs).toEqual([])
|
||||||
|
} finally {
|
||||||
|
page.off("pageerror", onError)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import {
|
|||||||
sessionComposerDockSelector,
|
sessionComposerDockSelector,
|
||||||
sessionTodoToggleButtonSelector,
|
sessionTodoToggleButtonSelector,
|
||||||
} from "../selectors"
|
} from "../selectors"
|
||||||
import { modKey } from "../utils"
|
|
||||||
|
|
||||||
type Sdk = Parameters<typeof clearSessionDockSeed>[0]
|
type Sdk = Parameters<typeof clearSessionDockSeed>[0]
|
||||||
type PermissionRule = { permission: string; pattern: string; action: "allow" | "deny" | "ask" }
|
type PermissionRule = { permission: string; pattern: string; action: "allow" | "deny" | "ask" }
|
||||||
@@ -94,7 +93,7 @@ async function todoDock(page: any, sessionID: string) {
|
|||||||
|
|
||||||
const write = async (driver: ComposerDriverState | undefined) => {
|
const write = async (driver: ComposerDriverState | undefined) => {
|
||||||
await page.evaluate(
|
await page.evaluate(
|
||||||
(input: { event: string; sessionID: string; driver: ComposerDriverState | undefined }) => {
|
(input) => {
|
||||||
const win = window as ComposerWindow
|
const win = window as ComposerWindow
|
||||||
const composer = win.__opencode_e2e?.composer
|
const composer = win.__opencode_e2e?.composer
|
||||||
if (!composer?.enabled) throw new Error("Composer e2e driver is not enabled")
|
if (!composer?.enabled) throw new Error("Composer e2e driver is not enabled")
|
||||||
@@ -119,7 +118,7 @@ async function todoDock(page: any, sessionID: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const read = () =>
|
const read = () =>
|
||||||
page.evaluate((sessionID: string) => {
|
page.evaluate((sessionID) => {
|
||||||
const win = window as ComposerWindow
|
const win = window as ComposerWindow
|
||||||
return win.__opencode_e2e?.composer?.sessions?.[sessionID]?.probe ?? null
|
return win.__opencode_e2e?.composer?.sessions?.[sessionID]?.probe ?? null
|
||||||
}, sessionID) as Promise<ComposerProbeState | null>
|
}, sessionID) as Promise<ComposerProbeState | null>
|
||||||
@@ -187,8 +186,6 @@ async function withMockPermission<T>(
|
|||||||
opts: { child?: any } | undefined,
|
opts: { child?: any } | undefined,
|
||||||
fn: (state: { resolved: () => Promise<void> }) => Promise<T>,
|
fn: (state: { resolved: () => Promise<void> }) => Promise<T>,
|
||||||
) {
|
) {
|
||||||
const listUrl = /\/permission(?:\?.*)?$/
|
|
||||||
const replyUrls = [/\/session\/[^/]+\/permissions\/[^/?]+(?:\?.*)?$/, /\/permission\/[^/]+\/reply(?:\?.*)?$/]
|
|
||||||
let pending = [
|
let pending = [
|
||||||
{
|
{
|
||||||
...request,
|
...request,
|
||||||
@@ -207,8 +204,7 @@ async function withMockPermission<T>(
|
|||||||
|
|
||||||
const reply = async (route: any) => {
|
const reply = async (route: any) => {
|
||||||
const url = new URL(route.request().url())
|
const url = new URL(route.request().url())
|
||||||
const parts = url.pathname.split("/").filter(Boolean)
|
const id = url.pathname.split("/").pop()
|
||||||
const id = parts.at(-1) === "reply" ? parts.at(-2) : parts.at(-1)
|
|
||||||
pending = pending.filter((item) => item.id !== id)
|
pending = pending.filter((item) => item.id !== id)
|
||||||
await route.fulfill({
|
await route.fulfill({
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -217,10 +213,8 @@ async function withMockPermission<T>(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
await page.route(listUrl, list)
|
await page.route("**/permission", list)
|
||||||
for (const item of replyUrls) {
|
await page.route("**/session/*/permissions/*", reply)
|
||||||
await page.route(item, reply)
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionList = opts?.child
|
const sessionList = opts?.child
|
||||||
? async (route: any) => {
|
? async (route: any) => {
|
||||||
@@ -248,58 +242,174 @@ async function withMockPermission<T>(
|
|||||||
try {
|
try {
|
||||||
return await fn(state)
|
return await fn(state)
|
||||||
} finally {
|
} finally {
|
||||||
await page.unroute(listUrl, list)
|
await page.unroute("**/permission", list)
|
||||||
for (const item of replyUrls) {
|
await page.unroute("**/session/*/permissions/*", reply)
|
||||||
await page.unroute(item, reply)
|
|
||||||
}
|
|
||||||
if (sessionList) await page.unroute("**/session?*", sessionList)
|
if (sessionList) await page.unroute("**/session?*", sessionList)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
test("default dock shows prompt input", async ({ page, withBackendProject }) => {
|
test("default dock shows prompt input", async ({ page, sdk, gotoSession }) => {
|
||||||
await withBackendProject(async (project) => {
|
await withDockSession(sdk, "e2e composer dock default", async (session) => {
|
||||||
await withDockSession(project.sdk, "e2e composer dock default", async (session) => {
|
await gotoSession(session.id)
|
||||||
await project.gotoSession(session.id)
|
|
||||||
|
|
||||||
await expect(page.locator(sessionComposerDockSelector)).toBeVisible()
|
await expect(page.locator(sessionComposerDockSelector)).toBeVisible()
|
||||||
await expect(page.locator(promptSelector)).toBeVisible()
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
await expect(page.locator(questionDockSelector)).toHaveCount(0)
|
await expect(page.locator(questionDockSelector)).toHaveCount(0)
|
||||||
await expect(page.locator(permissionDockSelector)).toHaveCount(0)
|
await expect(page.locator(permissionDockSelector)).toHaveCount(0)
|
||||||
|
|
||||||
await page.locator(promptSelector).click()
|
await page.locator(promptSelector).click()
|
||||||
await expect(page.locator(promptSelector)).toBeFocused()
|
await expect(page.locator(promptSelector)).toBeFocused()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test("auto-accept toggle works before first submit", async ({ page, gotoSession }) => {
|
||||||
|
await gotoSession()
|
||||||
|
|
||||||
|
const button = page.locator('[data-action="prompt-permissions"]').first()
|
||||||
|
await expect(button).toBeVisible()
|
||||||
|
await expect(button).toHaveAttribute("aria-pressed", "false")
|
||||||
|
|
||||||
|
await setAutoAccept(page, true)
|
||||||
|
await setAutoAccept(page, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("blocked question flow unblocks after submit", async ({ page, sdk, gotoSession }) => {
|
||||||
|
await withDockSession(sdk, "e2e composer dock question", async (session) => {
|
||||||
|
await withDockSeed(sdk, session.id, async () => {
|
||||||
|
await gotoSession(session.id)
|
||||||
|
|
||||||
|
await seedSessionQuestion(sdk, {
|
||||||
|
sessionID: session.id,
|
||||||
|
questions: [
|
||||||
|
{
|
||||||
|
header: "Need input",
|
||||||
|
question: "Pick one option",
|
||||||
|
options: [
|
||||||
|
{ label: "Continue", description: "Continue now" },
|
||||||
|
{ label: "Stop", description: "Stop here" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
const dock = page.locator(questionDockSelector)
|
||||||
|
await expectQuestionBlocked(page)
|
||||||
|
|
||||||
|
await dock.locator('[data-slot="question-option"]').first().click()
|
||||||
|
await dock.getByRole("button", { name: /submit/i }).click()
|
||||||
|
|
||||||
|
await expectQuestionOpen(page)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("auto-accept toggle works before first submit", async ({ page, withBackendProject }) => {
|
test("blocked permission flow supports allow once", async ({ page, sdk, gotoSession }) => {
|
||||||
await withBackendProject(async ({ gotoSession }) => {
|
await withDockSession(sdk, "e2e composer dock permission once", async (session) => {
|
||||||
await gotoSession()
|
await gotoSession(session.id)
|
||||||
|
|
||||||
const button = page.locator('[data-action="prompt-permissions"]').first()
|
|
||||||
await expect(button).toBeVisible()
|
|
||||||
await expect(button).toHaveAttribute("aria-pressed", "false")
|
|
||||||
|
|
||||||
await setAutoAccept(page, true)
|
|
||||||
await setAutoAccept(page, false)
|
await setAutoAccept(page, false)
|
||||||
|
await withMockPermission(
|
||||||
|
page,
|
||||||
|
{
|
||||||
|
id: "per_e2e_once",
|
||||||
|
sessionID: session.id,
|
||||||
|
permission: "bash",
|
||||||
|
patterns: ["/tmp/opencode-e2e-perm-once"],
|
||||||
|
metadata: { description: "Need permission for command" },
|
||||||
|
},
|
||||||
|
undefined,
|
||||||
|
async (state) => {
|
||||||
|
await page.goto(page.url())
|
||||||
|
await expectPermissionBlocked(page)
|
||||||
|
|
||||||
|
await clearPermissionDock(page, /allow once/i)
|
||||||
|
await state.resolved()
|
||||||
|
await page.goto(page.url())
|
||||||
|
await expectPermissionOpen(page)
|
||||||
|
},
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("blocked question flow unblocks after submit", async ({ page, withBackendProject }) => {
|
test("blocked permission flow supports reject", async ({ page, sdk, gotoSession }) => {
|
||||||
await withBackendProject(async (project) => {
|
await withDockSession(sdk, "e2e composer dock permission reject", async (session) => {
|
||||||
await withDockSession(project.sdk, "e2e composer dock question", async (session) => {
|
await gotoSession(session.id)
|
||||||
await withDockSeed(project.sdk, session.id, async () => {
|
await setAutoAccept(page, false)
|
||||||
await project.gotoSession(session.id)
|
await withMockPermission(
|
||||||
|
page,
|
||||||
|
{
|
||||||
|
id: "per_e2e_reject",
|
||||||
|
sessionID: session.id,
|
||||||
|
permission: "bash",
|
||||||
|
patterns: ["/tmp/opencode-e2e-perm-reject"],
|
||||||
|
},
|
||||||
|
undefined,
|
||||||
|
async (state) => {
|
||||||
|
await page.goto(page.url())
|
||||||
|
await expectPermissionBlocked(page)
|
||||||
|
|
||||||
await seedSessionQuestion(project.sdk, {
|
await clearPermissionDock(page, /deny/i)
|
||||||
sessionID: session.id,
|
await state.resolved()
|
||||||
|
await page.goto(page.url())
|
||||||
|
await expectPermissionOpen(page)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test("blocked permission flow supports allow always", async ({ page, sdk, gotoSession }) => {
|
||||||
|
await withDockSession(sdk, "e2e composer dock permission always", async (session) => {
|
||||||
|
await gotoSession(session.id)
|
||||||
|
await setAutoAccept(page, false)
|
||||||
|
await withMockPermission(
|
||||||
|
page,
|
||||||
|
{
|
||||||
|
id: "per_e2e_always",
|
||||||
|
sessionID: session.id,
|
||||||
|
permission: "bash",
|
||||||
|
patterns: ["/tmp/opencode-e2e-perm-always"],
|
||||||
|
metadata: { description: "Need permission for command" },
|
||||||
|
},
|
||||||
|
undefined,
|
||||||
|
async (state) => {
|
||||||
|
await page.goto(page.url())
|
||||||
|
await expectPermissionBlocked(page)
|
||||||
|
|
||||||
|
await clearPermissionDock(page, /allow always/i)
|
||||||
|
await state.resolved()
|
||||||
|
await page.goto(page.url())
|
||||||
|
await expectPermissionOpen(page)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test("child session question request blocks parent dock and unblocks after submit", async ({
|
||||||
|
page,
|
||||||
|
sdk,
|
||||||
|
gotoSession,
|
||||||
|
}) => {
|
||||||
|
await withDockSession(sdk, "e2e composer dock child question parent", async (session) => {
|
||||||
|
await gotoSession(session.id)
|
||||||
|
|
||||||
|
const child = await sdk.session
|
||||||
|
.create({
|
||||||
|
title: "e2e composer dock child question",
|
||||||
|
parentID: session.id,
|
||||||
|
})
|
||||||
|
.then((r) => r.data)
|
||||||
|
if (!child?.id) throw new Error("Child session create did not return an id")
|
||||||
|
|
||||||
|
try {
|
||||||
|
await withDockSeed(sdk, child.id, async () => {
|
||||||
|
await seedSessionQuestion(sdk, {
|
||||||
|
sessionID: child.id,
|
||||||
questions: [
|
questions: [
|
||||||
{
|
{
|
||||||
header: "Need input",
|
header: "Child input",
|
||||||
question: "Pick one option",
|
question: "Pick one child option",
|
||||||
options: [
|
options: [
|
||||||
{ label: "Continue", description: "Continue now" },
|
{ label: "Continue", description: "Continue child" },
|
||||||
{ label: "Stop", description: "Stop here" },
|
{ label: "Stop", description: "Stop child" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -313,96 +423,40 @@ test("blocked question flow unblocks after submit", async ({ page, withBackendPr
|
|||||||
|
|
||||||
await expectQuestionOpen(page)
|
await expectQuestionOpen(page)
|
||||||
})
|
})
|
||||||
})
|
} finally {
|
||||||
|
await cleanupSession({ sdk, sessionID: child.id })
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("blocked question flow supports keyboard shortcuts", async ({ page, withBackendProject }) => {
|
test("child session permission request blocks parent dock and supports allow once", async ({
|
||||||
await withBackendProject(async (project) => {
|
page,
|
||||||
await withDockSession(project.sdk, "e2e composer dock question keyboard", async (session) => {
|
sdk,
|
||||||
await withDockSeed(project.sdk, session.id, async () => {
|
gotoSession,
|
||||||
await project.gotoSession(session.id)
|
}) => {
|
||||||
|
await withDockSession(sdk, "e2e composer dock child permission parent", async (session) => {
|
||||||
|
await gotoSession(session.id)
|
||||||
|
await setAutoAccept(page, false)
|
||||||
|
|
||||||
await seedSessionQuestion(project.sdk, {
|
const child = await sdk.session
|
||||||
sessionID: session.id,
|
.create({
|
||||||
questions: [
|
title: "e2e composer dock child permission",
|
||||||
{
|
parentID: session.id,
|
||||||
header: "Need input",
|
|
||||||
question: "Pick one option",
|
|
||||||
options: [
|
|
||||||
{ label: "Continue", description: "Continue now" },
|
|
||||||
{ label: "Stop", description: "Stop here" },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
const dock = page.locator(questionDockSelector)
|
|
||||||
const first = dock.locator('[data-slot="question-option"]').first()
|
|
||||||
const second = dock.locator('[data-slot="question-option"]').nth(1)
|
|
||||||
|
|
||||||
await expectQuestionBlocked(page)
|
|
||||||
await expect(first).toBeFocused()
|
|
||||||
|
|
||||||
await page.keyboard.press("ArrowDown")
|
|
||||||
await expect(second).toBeFocused()
|
|
||||||
|
|
||||||
await page.keyboard.press("Space")
|
|
||||||
await page.keyboard.press(`${modKey}+Enter`)
|
|
||||||
await expectQuestionOpen(page)
|
|
||||||
})
|
})
|
||||||
})
|
.then((r) => r.data)
|
||||||
})
|
if (!child?.id) throw new Error("Child session create did not return an id")
|
||||||
})
|
|
||||||
|
|
||||||
test("blocked question flow supports escape dismiss", async ({ page, withBackendProject }) => {
|
try {
|
||||||
await withBackendProject(async (project) => {
|
|
||||||
await withDockSession(project.sdk, "e2e composer dock question escape", async (session) => {
|
|
||||||
await withDockSeed(project.sdk, session.id, async () => {
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
|
|
||||||
await seedSessionQuestion(project.sdk, {
|
|
||||||
sessionID: session.id,
|
|
||||||
questions: [
|
|
||||||
{
|
|
||||||
header: "Need input",
|
|
||||||
question: "Pick one option",
|
|
||||||
options: [
|
|
||||||
{ label: "Continue", description: "Continue now" },
|
|
||||||
{ label: "Stop", description: "Stop here" },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
const dock = page.locator(questionDockSelector)
|
|
||||||
const first = dock.locator('[data-slot="question-option"]').first()
|
|
||||||
|
|
||||||
await expectQuestionBlocked(page)
|
|
||||||
await expect(first).toBeFocused()
|
|
||||||
|
|
||||||
await page.keyboard.press("Escape")
|
|
||||||
await expectQuestionOpen(page)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test("blocked permission flow supports allow once", async ({ page, withBackendProject }) => {
|
|
||||||
await withBackendProject(async (project) => {
|
|
||||||
await withDockSession(project.sdk, "e2e composer dock permission once", async (session) => {
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
await setAutoAccept(page, false)
|
|
||||||
await withMockPermission(
|
await withMockPermission(
|
||||||
page,
|
page,
|
||||||
{
|
{
|
||||||
id: "per_e2e_once",
|
id: "per_e2e_child",
|
||||||
sessionID: session.id,
|
sessionID: child.id,
|
||||||
permission: "bash",
|
permission: "bash",
|
||||||
patterns: ["/tmp/opencode-e2e-perm-once"],
|
patterns: ["/tmp/opencode-e2e-perm-child"],
|
||||||
metadata: { description: "Need permission for command" },
|
metadata: { description: "Need child permission" },
|
||||||
},
|
},
|
||||||
undefined,
|
{ child },
|
||||||
async (state) => {
|
async (state) => {
|
||||||
await page.goto(page.url())
|
await page.goto(page.url())
|
||||||
await expectPermissionBlocked(page)
|
await expectPermissionBlocked(page)
|
||||||
@@ -410,218 +464,67 @@ test("blocked permission flow supports allow once", async ({ page, withBackendPr
|
|||||||
await clearPermissionDock(page, /allow once/i)
|
await clearPermissionDock(page, /allow once/i)
|
||||||
await state.resolved()
|
await state.resolved()
|
||||||
await page.goto(page.url())
|
await page.goto(page.url())
|
||||||
|
|
||||||
await expectPermissionOpen(page)
|
await expectPermissionOpen(page)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
})
|
} finally {
|
||||||
|
await cleanupSession({ sdk, sessionID: child.id })
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("blocked permission flow supports reject", async ({ page, withBackendProject }) => {
|
test("todo dock transitions and collapse behavior", async ({ page, sdk, gotoSession }) => {
|
||||||
await withBackendProject(async (project) => {
|
await withDockSession(sdk, "e2e composer dock todo", async (session) => {
|
||||||
await withDockSession(project.sdk, "e2e composer dock permission reject", async (session) => {
|
const dock = await todoDock(page, session.id)
|
||||||
await project.gotoSession(session.id)
|
await gotoSession(session.id)
|
||||||
await setAutoAccept(page, false)
|
await expect(page.locator(sessionComposerDockSelector)).toBeVisible()
|
||||||
await withMockPermission(
|
|
||||||
page,
|
|
||||||
{
|
|
||||||
id: "per_e2e_reject",
|
|
||||||
sessionID: session.id,
|
|
||||||
permission: "bash",
|
|
||||||
patterns: ["/tmp/opencode-e2e-perm-reject"],
|
|
||||||
},
|
|
||||||
undefined,
|
|
||||||
async (state) => {
|
|
||||||
await page.goto(page.url())
|
|
||||||
await expectPermissionBlocked(page)
|
|
||||||
|
|
||||||
await clearPermissionDock(page, /deny/i)
|
try {
|
||||||
await state.resolved()
|
await dock.open([
|
||||||
await page.goto(page.url())
|
{ content: "first task", status: "pending", priority: "high" },
|
||||||
await expectPermissionOpen(page)
|
{ content: "second task", status: "in_progress", priority: "medium" },
|
||||||
},
|
])
|
||||||
)
|
await dock.expectOpen(["pending", "in_progress"])
|
||||||
})
|
|
||||||
|
await dock.collapse()
|
||||||
|
await dock.expectCollapsed(["pending", "in_progress"])
|
||||||
|
|
||||||
|
await dock.expand()
|
||||||
|
await dock.expectOpen(["pending", "in_progress"])
|
||||||
|
|
||||||
|
await dock.finish([
|
||||||
|
{ content: "first task", status: "completed", priority: "high" },
|
||||||
|
{ content: "second task", status: "cancelled", priority: "medium" },
|
||||||
|
])
|
||||||
|
await dock.expectClosed()
|
||||||
|
} finally {
|
||||||
|
await dock.clear()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("blocked permission flow supports allow always", async ({ page, withBackendProject }) => {
|
test("keyboard focus stays off prompt while blocked", async ({ page, sdk, gotoSession }) => {
|
||||||
await withBackendProject(async (project) => {
|
await withDockSession(sdk, "e2e composer dock keyboard", async (session) => {
|
||||||
await withDockSession(project.sdk, "e2e composer dock permission always", async (session) => {
|
await withDockSeed(sdk, session.id, async () => {
|
||||||
await project.gotoSession(session.id)
|
await gotoSession(session.id)
|
||||||
await setAutoAccept(page, false)
|
|
||||||
await withMockPermission(
|
|
||||||
page,
|
|
||||||
{
|
|
||||||
id: "per_e2e_always",
|
|
||||||
sessionID: session.id,
|
|
||||||
permission: "bash",
|
|
||||||
patterns: ["/tmp/opencode-e2e-perm-always"],
|
|
||||||
metadata: { description: "Need permission for command" },
|
|
||||||
},
|
|
||||||
undefined,
|
|
||||||
async (state) => {
|
|
||||||
await page.goto(page.url())
|
|
||||||
await expectPermissionBlocked(page)
|
|
||||||
|
|
||||||
await clearPermissionDock(page, /allow always/i)
|
await seedSessionQuestion(sdk, {
|
||||||
await state.resolved()
|
sessionID: session.id,
|
||||||
await page.goto(page.url())
|
questions: [
|
||||||
await expectPermissionOpen(page)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test("child session question request blocks parent dock and unblocks after submit", async ({
|
|
||||||
page,
|
|
||||||
withBackendProject,
|
|
||||||
}) => {
|
|
||||||
await withBackendProject(async (project) => {
|
|
||||||
await withDockSession(project.sdk, "e2e composer dock child question parent", async (session) => {
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
|
|
||||||
const child = await project.sdk.session
|
|
||||||
.create({
|
|
||||||
title: "e2e composer dock child question",
|
|
||||||
parentID: session.id,
|
|
||||||
})
|
|
||||||
.then((r) => r.data)
|
|
||||||
if (!child?.id) throw new Error("Child session create did not return an id")
|
|
||||||
|
|
||||||
try {
|
|
||||||
await withDockSeed(project.sdk, child.id, async () => {
|
|
||||||
await seedSessionQuestion(project.sdk, {
|
|
||||||
sessionID: child.id,
|
|
||||||
questions: [
|
|
||||||
{
|
|
||||||
header: "Child input",
|
|
||||||
question: "Pick one child option",
|
|
||||||
options: [
|
|
||||||
{ label: "Continue", description: "Continue child" },
|
|
||||||
{ label: "Stop", description: "Stop child" },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
const dock = page.locator(questionDockSelector)
|
|
||||||
await expectQuestionBlocked(page)
|
|
||||||
|
|
||||||
await dock.locator('[data-slot="question-option"]').first().click()
|
|
||||||
await dock.getByRole("button", { name: /submit/i }).click()
|
|
||||||
|
|
||||||
await expectQuestionOpen(page)
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
await cleanupSession({ sdk: project.sdk, sessionID: child.id })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test("child session permission request blocks parent dock and supports allow once", async ({
|
|
||||||
page,
|
|
||||||
withBackendProject,
|
|
||||||
}) => {
|
|
||||||
await withBackendProject(async (project) => {
|
|
||||||
await withDockSession(project.sdk, "e2e composer dock child permission parent", async (session) => {
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
await setAutoAccept(page, false)
|
|
||||||
|
|
||||||
const child = await project.sdk.session
|
|
||||||
.create({
|
|
||||||
title: "e2e composer dock child permission",
|
|
||||||
parentID: session.id,
|
|
||||||
})
|
|
||||||
.then((r) => r.data)
|
|
||||||
if (!child?.id) throw new Error("Child session create did not return an id")
|
|
||||||
|
|
||||||
try {
|
|
||||||
await withMockPermission(
|
|
||||||
page,
|
|
||||||
{
|
{
|
||||||
id: "per_e2e_child",
|
header: "Need input",
|
||||||
sessionID: child.id,
|
question: "Pick one option",
|
||||||
permission: "bash",
|
options: [{ label: "Continue", description: "Continue now" }],
|
||||||
patterns: ["/tmp/opencode-e2e-perm-child"],
|
|
||||||
metadata: { description: "Need child permission" },
|
|
||||||
},
|
},
|
||||||
{ child },
|
],
|
||||||
async (state) => {
|
|
||||||
await page.goto(page.url())
|
|
||||||
await expectPermissionBlocked(page)
|
|
||||||
|
|
||||||
await clearPermissionDock(page, /allow once/i)
|
|
||||||
await state.resolved()
|
|
||||||
await page.goto(page.url())
|
|
||||||
|
|
||||||
await expectPermissionOpen(page)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
await cleanupSession({ sdk: project.sdk, sessionID: child.id })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test("todo dock transitions and collapse behavior", async ({ page, withBackendProject }) => {
|
|
||||||
await withBackendProject(async (project) => {
|
|
||||||
await withDockSession(project.sdk, "e2e composer dock todo", async (session) => {
|
|
||||||
const dock = await todoDock(page, session.id)
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
await expect(page.locator(sessionComposerDockSelector)).toBeVisible()
|
|
||||||
|
|
||||||
try {
|
|
||||||
await dock.open([
|
|
||||||
{ content: "first task", status: "pending", priority: "high" },
|
|
||||||
{ content: "second task", status: "in_progress", priority: "medium" },
|
|
||||||
])
|
|
||||||
await dock.expectOpen(["pending", "in_progress"])
|
|
||||||
|
|
||||||
await dock.collapse()
|
|
||||||
await dock.expectCollapsed(["pending", "in_progress"])
|
|
||||||
|
|
||||||
await dock.expand()
|
|
||||||
await dock.expectOpen(["pending", "in_progress"])
|
|
||||||
|
|
||||||
await dock.finish([
|
|
||||||
{ content: "first task", status: "completed", priority: "high" },
|
|
||||||
{ content: "second task", status: "cancelled", priority: "medium" },
|
|
||||||
])
|
|
||||||
await dock.expectClosed()
|
|
||||||
} finally {
|
|
||||||
await dock.clear()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test("keyboard focus stays off prompt while blocked", async ({ page, withBackendProject }) => {
|
|
||||||
await withBackendProject(async (project) => {
|
|
||||||
await withDockSession(project.sdk, "e2e composer dock keyboard", async (session) => {
|
|
||||||
await withDockSeed(project.sdk, session.id, async () => {
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
|
|
||||||
await seedSessionQuestion(project.sdk, {
|
|
||||||
sessionID: session.id,
|
|
||||||
questions: [
|
|
||||||
{
|
|
||||||
header: "Need input",
|
|
||||||
question: "Pick one option",
|
|
||||||
options: [{ label: "Continue", description: "Continue now" }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
await expectQuestionBlocked(page)
|
|
||||||
|
|
||||||
await page.locator("main").click({ position: { x: 5, y: 5 } })
|
|
||||||
await page.keyboard.type("abc")
|
|
||||||
await expect(page.locator(promptSelector)).toHaveCount(0)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await expectQuestionBlocked(page)
|
||||||
|
|
||||||
|
await page.locator("main").click({ position: { x: 5, y: 5 } })
|
||||||
|
await page.keyboard.type("abc")
|
||||||
|
await expect(page.locator(promptSelector)).toHaveCount(0)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,14 +1,6 @@
|
|||||||
import type { Locator, Page } from "@playwright/test"
|
import type { Locator, Page } from "@playwright/test"
|
||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import {
|
import { openSidebar, resolveSlug, sessionIDFromUrl, setWorkspacesEnabled, waitSessionIdle, waitSlug } from "../actions"
|
||||||
openSidebar,
|
|
||||||
resolveSlug,
|
|
||||||
sessionIDFromUrl,
|
|
||||||
setWorkspacesEnabled,
|
|
||||||
waitSession,
|
|
||||||
waitSessionIdle,
|
|
||||||
waitSlug,
|
|
||||||
} from "../actions"
|
|
||||||
import {
|
import {
|
||||||
promptAgentSelector,
|
promptAgentSelector,
|
||||||
promptModelSelector,
|
promptModelSelector,
|
||||||
@@ -28,17 +20,7 @@ type Footer = {
|
|||||||
type Probe = {
|
type Probe = {
|
||||||
dir?: string
|
dir?: string
|
||||||
sessionID?: string
|
sessionID?: string
|
||||||
agent?: string
|
model?: { providerID: string; modelID: string }
|
||||||
model?: { providerID: string; modelID: string; name?: string }
|
|
||||||
variant?: string | null
|
|
||||||
pick?: {
|
|
||||||
agent?: string
|
|
||||||
model?: { providerID: string; modelID: string }
|
|
||||||
variant?: string | null
|
|
||||||
}
|
|
||||||
variants?: string[]
|
|
||||||
models?: Array<{ providerID: string; modelID: string; name: string }>
|
|
||||||
agents?: Array<{ name: string }>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||||
@@ -47,6 +29,8 @@ const text = async (locator: Locator) => ((await locator.textContent()) ?? "").t
|
|||||||
|
|
||||||
const modelKey = (state: Probe | null) => (state?.model ? `${state.model.providerID}:${state.model.modelID}` : null)
|
const modelKey = (state: Probe | null) => (state?.model ? `${state.model.providerID}:${state.model.modelID}` : null)
|
||||||
|
|
||||||
|
const dirKey = (state: Probe | null) => state?.dir ?? ""
|
||||||
|
|
||||||
async function probe(page: Page): Promise<Probe | null> {
|
async function probe(page: Page): Promise<Probe | null> {
|
||||||
return page.evaluate(() => {
|
return page.evaluate(() => {
|
||||||
const win = window as Window & {
|
const win = window as Window & {
|
||||||
@@ -60,84 +44,19 @@ async function probe(page: Page): Promise<Probe | null> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async function currentModel(page: Page) {
|
async function currentDir(page: Page) {
|
||||||
await expect.poll(() => probe(page).then(modelKey), { timeout: 30_000 }).not.toBe(null)
|
let hit = ""
|
||||||
const value = await probe(page).then(modelKey)
|
|
||||||
if (!value) throw new Error("Failed to resolve current model key")
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
async function waitControl(page: Page, key: "setAgent" | "setModel" | "setVariant") {
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
() =>
|
async () => {
|
||||||
page.evaluate((key) => {
|
const next = dirKey(await probe(page))
|
||||||
const win = window as Window & {
|
if (next) hit = next
|
||||||
__opencode_e2e?: {
|
return next
|
||||||
model?: {
|
},
|
||||||
controls?: Record<string, unknown>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return !!win.__opencode_e2e?.model?.controls?.[key]
|
|
||||||
}, key),
|
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.toBe(true)
|
.not.toBe("")
|
||||||
}
|
return hit
|
||||||
|
|
||||||
async function pickAgent(page: Page, value: string) {
|
|
||||||
await waitControl(page, "setAgent")
|
|
||||||
await page.evaluate((value) => {
|
|
||||||
const win = window as Window & {
|
|
||||||
__opencode_e2e?: {
|
|
||||||
model?: {
|
|
||||||
controls?: {
|
|
||||||
setAgent?: (value: string | undefined) => void
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const fn = win.__opencode_e2e?.model?.controls?.setAgent
|
|
||||||
if (!fn) throw new Error("Model e2e agent control is not enabled")
|
|
||||||
fn(value)
|
|
||||||
}, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pickModel(page: Page, value: { providerID: string; modelID: string }) {
|
|
||||||
await waitControl(page, "setModel")
|
|
||||||
await page.evaluate((value) => {
|
|
||||||
const win = window as Window & {
|
|
||||||
__opencode_e2e?: {
|
|
||||||
model?: {
|
|
||||||
controls?: {
|
|
||||||
setModel?: (value: { providerID: string; modelID: string } | undefined) => void
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const fn = win.__opencode_e2e?.model?.controls?.setModel
|
|
||||||
if (!fn) throw new Error("Model e2e model control is not enabled")
|
|
||||||
fn(value)
|
|
||||||
}, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pickVariant(page: Page, value: string) {
|
|
||||||
await waitControl(page, "setVariant")
|
|
||||||
await page.evaluate((value) => {
|
|
||||||
const win = window as Window & {
|
|
||||||
__opencode_e2e?: {
|
|
||||||
model?: {
|
|
||||||
controls?: {
|
|
||||||
setVariant?: (value: string | undefined) => void
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const fn = win.__opencode_e2e?.model?.controls?.setVariant
|
|
||||||
if (!fn) throw new Error("Model e2e variant control is not enabled")
|
|
||||||
fn(value)
|
|
||||||
}, value)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function read(page: Page): Promise<Footer> {
|
async function read(page: Page): Promise<Footer> {
|
||||||
@@ -172,15 +91,31 @@ async function waitModel(page: Page, value: string) {
|
|||||||
async function choose(page: Page, root: string, value: string) {
|
async function choose(page: Page, root: string, value: string) {
|
||||||
const select = page.locator(root)
|
const select = page.locator(root)
|
||||||
await expect(select).toBeVisible()
|
await expect(select).toBeVisible()
|
||||||
await pickAgent(page, value)
|
await select.locator('[data-action], [data-slot="select-select-trigger"]').first().click()
|
||||||
|
const item = page
|
||||||
|
.locator('[data-slot="select-select-item"]')
|
||||||
|
.filter({ hasText: new RegExp(`^\\s*${escape(value)}\\s*$`) })
|
||||||
|
.first()
|
||||||
|
await expect(item).toBeVisible()
|
||||||
|
await item.click()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function variantCount(page: Page) {
|
async function variantCount(page: Page) {
|
||||||
return (await probe(page))?.variants?.length ?? 0
|
const select = page.locator(promptVariantSelector)
|
||||||
|
await expect(select).toBeVisible()
|
||||||
|
await select.locator('[data-slot="select-select-trigger"]').click()
|
||||||
|
const count = await page.locator('[data-slot="select-select-item"]').count()
|
||||||
|
await page.keyboard.press("Escape")
|
||||||
|
return count
|
||||||
}
|
}
|
||||||
|
|
||||||
async function agents(page: Page) {
|
async function agents(page: Page) {
|
||||||
return ((await probe(page))?.agents ?? []).map((item) => item.name).filter(Boolean)
|
const select = page.locator(promptAgentSelector)
|
||||||
|
await expect(select).toBeVisible()
|
||||||
|
await select.locator('[data-action], [data-slot="select-select-trigger"]').first().click()
|
||||||
|
const labels = await page.locator('[data-slot="select-select-item-label"]').allTextContents()
|
||||||
|
await page.keyboard.press("Escape")
|
||||||
|
return labels.map((item) => item.trim()).filter(Boolean)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ensureVariant(page: Page, directory: string): Promise<Footer> {
|
async function ensureVariant(page: Page, directory: string): Promise<Footer> {
|
||||||
@@ -206,28 +141,54 @@ async function ensureVariant(page: Page, directory: string): Promise<Footer> {
|
|||||||
|
|
||||||
async function chooseDifferentVariant(page: Page): Promise<Footer> {
|
async function chooseDifferentVariant(page: Page): Promise<Footer> {
|
||||||
const current = await read(page)
|
const current = await read(page)
|
||||||
const next = (await probe(page))?.variants?.find((item) => item !== current.variant)
|
const select = page.locator(promptVariantSelector)
|
||||||
if (!next) throw new Error("Current model has no alternate variant to select")
|
await expect(select).toBeVisible()
|
||||||
|
await select.locator('[data-slot="select-select-trigger"]').click()
|
||||||
|
|
||||||
await pickVariant(page, next)
|
const items = page.locator('[data-slot="select-select-item"]')
|
||||||
return waitFooter(page, { agent: current.agent, model: current.model, variant: next })
|
const count = await items.count()
|
||||||
|
if (count < 2) throw new Error("Current model has no alternate variant to select")
|
||||||
|
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const item = items.nth(i)
|
||||||
|
const next = await text(item.locator('[data-slot="select-select-item-label"]').first())
|
||||||
|
if (!next || next === current.variant) continue
|
||||||
|
await item.click()
|
||||||
|
return waitFooter(page, { agent: current.agent, model: current.model, variant: next })
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("Failed to choose a different variant")
|
||||||
}
|
}
|
||||||
|
|
||||||
async function chooseOtherModel(page: Page, skip: string[] = []): Promise<Footer> {
|
async function chooseOtherModel(page: Page): Promise<Footer> {
|
||||||
const current = await currentModel(page)
|
const current = await read(page)
|
||||||
const next = (await probe(page))?.models?.find((item) => {
|
const button = page.locator(`${promptModelSelector} [data-action="prompt-model"]`)
|
||||||
const key = `${item.providerID}:${item.modelID}`
|
await expect(button).toBeVisible()
|
||||||
return key !== current && !skip.includes(key)
|
await button.click()
|
||||||
})
|
|
||||||
if (!next) throw new Error("Failed to choose a different model")
|
const dialog = page.getByRole("dialog")
|
||||||
await pickModel(page, { providerID: next.providerID, modelID: next.modelID })
|
await expect(dialog).toBeVisible()
|
||||||
await expect.poll(async () => (await read(page)).model, { timeout: 30_000 }).toBe(next.name)
|
const items = dialog.locator('[data-slot="list-item"]')
|
||||||
return read(page)
|
const count = await items.count()
|
||||||
|
expect(count).toBeGreaterThan(1)
|
||||||
|
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const item = items.nth(i)
|
||||||
|
const selected = (await item.getAttribute("data-selected")) === "true"
|
||||||
|
if (selected) continue
|
||||||
|
await item.click()
|
||||||
|
await expect(dialog).toHaveCount(0)
|
||||||
|
await expect.poll(async () => (await read(page)).model !== current.model, { timeout: 30_000 }).toBe(true)
|
||||||
|
return read(page)
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("Failed to choose a different model")
|
||||||
}
|
}
|
||||||
|
|
||||||
async function goto(page: Page, directory: string, sessionID?: string) {
|
async function goto(page: Page, directory: string, sessionID?: string) {
|
||||||
await page.goto(sessionPath(directory, sessionID))
|
await page.goto(sessionPath(directory, sessionID))
|
||||||
await waitSession(page, { directory, sessionID })
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
|
await expect.poll(async () => dirKey(await probe(page)), { timeout: 30_000 }).toBe(directory)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submit(page: Page, value: string) {
|
async function submit(page: Page, value: string) {
|
||||||
@@ -263,7 +224,7 @@ async function createWorkspace(page: Page, root: string, seen: string[]) {
|
|||||||
await page.getByRole("button", { name: "New workspace" }).first().click()
|
await page.getByRole("button", { name: "New workspace" }).first().click()
|
||||||
|
|
||||||
const next = await resolveSlug(await waitSlug(page, [root, ...seen]))
|
const next = await resolveSlug(await waitSlug(page, [root, ...seen]))
|
||||||
await waitSession(page, { directory: next.directory })
|
await expect(page).toHaveURL(new RegExp(`/${next.slug}/session(?:[/?#]|$)`))
|
||||||
return next
|
return next
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,30 +256,35 @@ async function newWorkspaceSession(page: Page, slug: string) {
|
|||||||
await button.click({ force: true })
|
await button.click({ force: true })
|
||||||
|
|
||||||
const next = await resolveSlug(await waitSlug(page))
|
const next = await resolveSlug(await waitSlug(page))
|
||||||
return waitSession(page, { directory: next.directory }).then((item) => item.directory)
|
await expect(page).toHaveURL(new RegExp(`/${next.slug}/session(?:[/?#]|$)`))
|
||||||
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
|
return currentDir(page)
|
||||||
}
|
}
|
||||||
|
|
||||||
test("session model restore per session without leaking into new sessions", async ({ page, withProject }) => {
|
test("session model and variant restore per session without leaking into new sessions", async ({
|
||||||
|
page,
|
||||||
|
withProject,
|
||||||
|
}) => {
|
||||||
await page.setViewportSize({ width: 1440, height: 900 })
|
await page.setViewportSize({ width: 1440, height: 900 })
|
||||||
|
|
||||||
await withProject(async ({ directory, gotoSession, trackSession }) => {
|
await withProject(async ({ directory, gotoSession, trackSession }) => {
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
|
|
||||||
const firstState = await chooseOtherModel(page)
|
await ensureVariant(page, directory)
|
||||||
const firstKey = await currentModel(page)
|
const firstState = await chooseDifferentVariant(page)
|
||||||
const first = await submit(page, `session variant ${Date.now()}`)
|
const first = await submit(page, `session variant ${Date.now()}`)
|
||||||
trackSession(first)
|
trackSession(first)
|
||||||
await waitUser(directory, first)
|
await waitUser(directory, first)
|
||||||
|
|
||||||
await page.reload()
|
await page.reload()
|
||||||
await waitSession(page, { directory, sessionID: first })
|
await expect(page.locator(promptSelector)).toBeVisible()
|
||||||
await waitFooter(page, firstState)
|
await waitFooter(page, firstState)
|
||||||
|
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
const fresh = await read(page)
|
const fresh = await ensureVariant(page, directory)
|
||||||
expect(fresh.model).not.toBe(firstState.model)
|
expect(fresh.variant).not.toBe(firstState.variant)
|
||||||
|
|
||||||
const secondState = await chooseOtherModel(page, [firstKey])
|
const secondState = await chooseOtherModel(page)
|
||||||
const second = await submit(page, `session model ${Date.now()}`)
|
const second = await submit(page, `session model ${Date.now()}`)
|
||||||
trackSession(second)
|
trackSession(second)
|
||||||
await waitUser(directory, second)
|
await waitUser(directory, second)
|
||||||
@@ -340,8 +306,8 @@ test("session model restore across workspaces", async ({ page, withProject }) =>
|
|||||||
await withProject(async ({ directory: root, slug, gotoSession, trackDirectory, trackSession }) => {
|
await withProject(async ({ directory: root, slug, gotoSession, trackDirectory, trackSession }) => {
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
|
|
||||||
const firstState = await chooseOtherModel(page)
|
await ensureVariant(page, root)
|
||||||
const firstKey = await currentModel(page)
|
const firstState = await chooseDifferentVariant(page)
|
||||||
const first = await submit(page, `root session ${Date.now()}`)
|
const first = await submit(page, `root session ${Date.now()}`)
|
||||||
trackSession(first, root)
|
trackSession(first, root)
|
||||||
await waitUser(root, first)
|
await waitUser(root, first)
|
||||||
@@ -353,8 +319,7 @@ test("session model restore across workspaces", async ({ page, withProject }) =>
|
|||||||
const oneDir = await newWorkspaceSession(page, one.slug)
|
const oneDir = await newWorkspaceSession(page, one.slug)
|
||||||
trackDirectory(oneDir)
|
trackDirectory(oneDir)
|
||||||
|
|
||||||
const secondState = await chooseOtherModel(page, [firstKey])
|
const secondState = await chooseOtherModel(page)
|
||||||
const secondKey = await currentModel(page)
|
|
||||||
const second = await submit(page, `workspace one ${Date.now()}`)
|
const second = await submit(page, `workspace one ${Date.now()}`)
|
||||||
trackSession(second, oneDir)
|
trackSession(second, oneDir)
|
||||||
await waitUser(oneDir, second)
|
await waitUser(oneDir, second)
|
||||||
@@ -363,7 +328,8 @@ test("session model restore across workspaces", async ({ page, withProject }) =>
|
|||||||
const twoDir = await newWorkspaceSession(page, two.slug)
|
const twoDir = await newWorkspaceSession(page, two.slug)
|
||||||
trackDirectory(twoDir)
|
trackDirectory(twoDir)
|
||||||
|
|
||||||
const thirdState = await chooseOtherModel(page, [firstKey, secondKey])
|
await ensureVariant(page, twoDir)
|
||||||
|
const thirdState = await chooseDifferentVariant(page)
|
||||||
const third = await submit(page, `workspace two ${Date.now()}`)
|
const third = await submit(page, `workspace two ${Date.now()}`)
|
||||||
trackSession(third, twoDir)
|
trackSession(third, twoDir)
|
||||||
await waitUser(twoDir, third)
|
await waitUser(twoDir, third)
|
||||||
|
|||||||
@@ -169,72 +169,7 @@ async function overflow(page: Parameters<typeof test>[0]["page"], file: string)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openReviewFile(page: Parameters<typeof test>[0]["page"], file: string) {
|
|
||||||
const row = page.locator(`[data-file="${file}"]`).first()
|
|
||||||
await expect(row).toBeVisible()
|
|
||||||
await row.hover()
|
|
||||||
|
|
||||||
const open = row.getByRole("button", { name: /^Open file$/i }).first()
|
|
||||||
await expect(open).toBeVisible()
|
|
||||||
await open.click()
|
|
||||||
|
|
||||||
const tab = page.getByRole("tab", { name: file }).first()
|
|
||||||
await expect(tab).toBeVisible()
|
|
||||||
await tab.click()
|
|
||||||
|
|
||||||
const viewer = page.locator('[data-component="file"][data-mode="text"]').first()
|
|
||||||
await expect(viewer).toBeVisible()
|
|
||||||
return viewer
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fileComment(page: Parameters<typeof test>[0]["page"], note: string) {
|
|
||||||
const viewer = page.locator('[data-component="file"][data-mode="text"]').first()
|
|
||||||
await expect(viewer).toBeVisible()
|
|
||||||
|
|
||||||
const line = viewer.locator('diffs-container [data-line="2"]').first()
|
|
||||||
await expect(line).toBeVisible()
|
|
||||||
await line.hover()
|
|
||||||
|
|
||||||
const add = viewer.getByRole("button", { name: /^Comment$/ }).first()
|
|
||||||
await expect(add).toBeVisible()
|
|
||||||
await add.click()
|
|
||||||
|
|
||||||
const area = viewer.locator('[data-slot="line-comment-textarea"]').first()
|
|
||||||
await expect(area).toBeVisible()
|
|
||||||
await area.fill(note)
|
|
||||||
|
|
||||||
const submit = viewer.locator('[data-slot="line-comment-action"][data-variant="primary"]').first()
|
|
||||||
await expect(submit).toBeEnabled()
|
|
||||||
await submit.click()
|
|
||||||
|
|
||||||
await expect(viewer.locator('[data-slot="line-comment-content"]').filter({ hasText: note }).first()).toBeVisible()
|
|
||||||
await expect(viewer.locator('[data-slot="line-comment-tools"]').first()).toBeVisible()
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fileOverflow(page: Parameters<typeof test>[0]["page"]) {
|
|
||||||
const viewer = page.locator('[data-component="file"][data-mode="text"]').first()
|
|
||||||
const view = page.locator('[role="tabpanel"] .scroll-view__viewport').first()
|
|
||||||
const pop = viewer.locator('[data-slot="line-comment-popover"][data-inline-body]').first()
|
|
||||||
const tools = viewer.locator('[data-slot="line-comment-tools"]').first()
|
|
||||||
|
|
||||||
const [width, viewBox, popBox, toolsBox] = await Promise.all([
|
|
||||||
view.evaluate((el) => el.scrollWidth - el.clientWidth),
|
|
||||||
view.boundingBox(),
|
|
||||||
pop.boundingBox(),
|
|
||||||
tools.boundingBox(),
|
|
||||||
])
|
|
||||||
|
|
||||||
if (!viewBox || !popBox || !toolsBox) return null
|
|
||||||
|
|
||||||
return {
|
|
||||||
width,
|
|
||||||
pop: popBox.x + popBox.width - (viewBox.x + viewBox.width),
|
|
||||||
tools: toolsBox.x + toolsBox.width - (viewBox.x + viewBox.width),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test("review applies inline comment clicks without horizontal overflow", async ({ page, withProject }) => {
|
test("review applies inline comment clicks without horizontal overflow", async ({ page, withProject }) => {
|
||||||
test.skip(true, "Flaky in CI for now.")
|
|
||||||
test.setTimeout(180_000)
|
test.setTimeout(180_000)
|
||||||
|
|
||||||
const tag = `review-comment-${Date.now()}`
|
const tag = `review-comment-${Date.now()}`
|
||||||
@@ -283,57 +218,6 @@ test("review applies inline comment clicks without horizontal overflow", async (
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("review file comments submit on click without clipping actions", async ({ page, withProject }) => {
|
|
||||||
test.skip(true, "Flaky in CI for now.")
|
|
||||||
test.setTimeout(180_000)
|
|
||||||
|
|
||||||
const tag = `review-file-comment-${Date.now()}`
|
|
||||||
const file = `review-file-comment-${tag}.txt`
|
|
||||||
const note = `comment ${tag}`
|
|
||||||
|
|
||||||
await page.setViewportSize({ width: 1280, height: 900 })
|
|
||||||
|
|
||||||
await withProject(async (project) => {
|
|
||||||
const sdk = createSdk(project.directory)
|
|
||||||
|
|
||||||
await withSession(sdk, `e2e review file comment ${tag}`, async (session) => {
|
|
||||||
await patch(sdk, session.id, seed([{ file, mark: tag }]))
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(
|
|
||||||
async () => {
|
|
||||||
const diff = await sdk.session.diff({ sessionID: session.id }).then((res) => res.data ?? [])
|
|
||||||
return diff.length
|
|
||||||
},
|
|
||||||
{ timeout: 60_000 },
|
|
||||||
)
|
|
||||||
.toBe(1)
|
|
||||||
|
|
||||||
await project.gotoSession(session.id)
|
|
||||||
await show(page)
|
|
||||||
|
|
||||||
const tab = page.getByRole("tab", { name: /Review/i }).first()
|
|
||||||
await expect(tab).toBeVisible()
|
|
||||||
await tab.click()
|
|
||||||
|
|
||||||
await expand(page)
|
|
||||||
await waitMark(page, file, tag)
|
|
||||||
await openReviewFile(page, file)
|
|
||||||
await fileComment(page, note)
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(async () => (await fileOverflow(page))?.width ?? Number.POSITIVE_INFINITY, { timeout: 10_000 })
|
|
||||||
.toBeLessThanOrEqual(1)
|
|
||||||
await expect
|
|
||||||
.poll(async () => (await fileOverflow(page))?.pop ?? Number.POSITIVE_INFINITY, { timeout: 10_000 })
|
|
||||||
.toBeLessThanOrEqual(1)
|
|
||||||
await expect
|
|
||||||
.poll(async () => (await fileOverflow(page))?.tools ?? Number.POSITIVE_INFINITY, { timeout: 10_000 })
|
|
||||||
.toBeLessThanOrEqual(1)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
test("review keeps scroll position after a live diff update", async ({ page, withProject }) => {
|
test("review keeps scroll position after a live diff update", async ({ page, withProject }) => {
|
||||||
test.skip(Boolean(process.env.CI), "Flaky in CI for now.")
|
test.skip(Boolean(process.env.CI), "Flaky in CI for now.")
|
||||||
test.setTimeout(180_000)
|
test.setTimeout(180_000)
|
||||||
|
|||||||
@@ -49,13 +49,13 @@ async function seedConversation(input: {
|
|||||||
return { prompt, userMessageID }
|
return { prompt, userMessageID }
|
||||||
}
|
}
|
||||||
|
|
||||||
test("slash undo sets revert and restores prior prompt", async ({ page, withBackendProject }) => {
|
test("slash undo sets revert and restores prior prompt", async ({ page, withProject }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
const token = `undo_${Date.now()}`
|
const token = `undo_${Date.now()}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withProject(async (project) => {
|
||||||
const sdk = project.sdk
|
const sdk = createSdk(project.directory)
|
||||||
|
|
||||||
await withSession(sdk, `e2e undo ${Date.now()}`, async (session) => {
|
await withSession(sdk, `e2e undo ${Date.now()}`, async (session) => {
|
||||||
await project.gotoSession(session.id)
|
await project.gotoSession(session.id)
|
||||||
@@ -81,13 +81,13 @@ test("slash undo sets revert and restores prior prompt", async ({ page, withBack
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("slash redo clears revert and restores latest state", async ({ page, withBackendProject }) => {
|
test("slash redo clears revert and restores latest state", async ({ page, withProject }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
const token = `redo_${Date.now()}`
|
const token = `redo_${Date.now()}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withProject(async (project) => {
|
||||||
const sdk = project.sdk
|
const sdk = createSdk(project.directory)
|
||||||
|
|
||||||
await withSession(sdk, `e2e redo ${Date.now()}`, async (session) => {
|
await withSession(sdk, `e2e redo ${Date.now()}`, async (session) => {
|
||||||
await project.gotoSession(session.id)
|
await project.gotoSession(session.id)
|
||||||
@@ -128,14 +128,14 @@ test("slash redo clears revert and restores latest state", async ({ page, withBa
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("slash undo/redo traverses multi-step revert stack", async ({ page, withBackendProject }) => {
|
test("slash undo/redo traverses multi-step revert stack", async ({ page, withProject }) => {
|
||||||
test.setTimeout(120_000)
|
test.setTimeout(120_000)
|
||||||
|
|
||||||
const firstToken = `undo_redo_first_${Date.now()}`
|
const firstToken = `undo_redo_first_${Date.now()}`
|
||||||
const secondToken = `undo_redo_second_${Date.now()}`
|
const secondToken = `undo_redo_second_${Date.now()}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withProject(async (project) => {
|
||||||
const sdk = project.sdk
|
const sdk = createSdk(project.directory)
|
||||||
|
|
||||||
await withSession(sdk, `e2e undo redo stack ${Date.now()}`, async (session) => {
|
await withSession(sdk, `e2e undo redo stack ${Date.now()}`, async (session) => {
|
||||||
await project.gotoSession(session.id)
|
await project.gotoSession(session.id)
|
||||||
|
|||||||
@@ -31,152 +31,144 @@ async function seedMessage(sdk: Sdk, sessionID: string) {
|
|||||||
.toBeGreaterThan(0)
|
.toBeGreaterThan(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
test("session can be renamed via header menu", async ({ page, withBackendProject }) => {
|
test("session can be renamed via header menu", async ({ page, sdk, gotoSession }) => {
|
||||||
const stamp = Date.now()
|
const stamp = Date.now()
|
||||||
const originalTitle = `e2e rename test ${stamp}`
|
const originalTitle = `e2e rename test ${stamp}`
|
||||||
const renamedTitle = `e2e renamed ${stamp}`
|
const renamedTitle = `e2e renamed ${stamp}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withSession(sdk, originalTitle, async (session) => {
|
||||||
await withSession(project.sdk, originalTitle, async (session) => {
|
await seedMessage(sdk, session.id)
|
||||||
await seedMessage(project.sdk, session.id)
|
await gotoSession(session.id)
|
||||||
await project.gotoSession(session.id)
|
await expect(page.getByRole("heading", { level: 1 }).first()).toHaveText(originalTitle)
|
||||||
await expect(page.getByRole("heading", { level: 1 }).first()).toHaveText(originalTitle)
|
|
||||||
|
|
||||||
const menu = await openSessionMoreMenu(page, session.id)
|
const menu = await openSessionMoreMenu(page, session.id)
|
||||||
await clickMenuItem(menu, /rename/i)
|
await clickMenuItem(menu, /rename/i)
|
||||||
|
|
||||||
const input = page.locator(".scroll-view__viewport").locator(inlineInputSelector).first()
|
const input = page.locator(".scroll-view__viewport").locator(inlineInputSelector).first()
|
||||||
await expect(input).toBeVisible()
|
await expect(input).toBeVisible()
|
||||||
await expect(input).toBeFocused()
|
await expect(input).toBeFocused()
|
||||||
await input.fill(renamedTitle)
|
await input.fill(renamedTitle)
|
||||||
await expect(input).toHaveValue(renamedTitle)
|
await expect(input).toHaveValue(renamedTitle)
|
||||||
await input.press("Enter")
|
await input.press("Enter")
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
const data = await sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
||||||
return data?.title
|
return data?.title
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.toBe(renamedTitle)
|
.toBe(renamedTitle)
|
||||||
|
|
||||||
await expect(page.getByRole("heading", { level: 1 }).first()).toHaveText(renamedTitle)
|
await expect(page.getByRole("heading", { level: 1 }).first()).toHaveText(renamedTitle)
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("session can be archived via header menu", async ({ page, withBackendProject }) => {
|
test("session can be archived via header menu", async ({ page, sdk, gotoSession }) => {
|
||||||
const stamp = Date.now()
|
const stamp = Date.now()
|
||||||
const title = `e2e archive test ${stamp}`
|
const title = `e2e archive test ${stamp}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withSession(sdk, title, async (session) => {
|
||||||
await withSession(project.sdk, title, async (session) => {
|
await seedMessage(sdk, session.id)
|
||||||
await seedMessage(project.sdk, session.id)
|
await gotoSession(session.id)
|
||||||
await project.gotoSession(session.id)
|
const menu = await openSessionMoreMenu(page, session.id)
|
||||||
const menu = await openSessionMoreMenu(page, session.id)
|
await clickMenuItem(menu, /archive/i)
|
||||||
await clickMenuItem(menu, /archive/i)
|
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
const data = await sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
||||||
return data?.time?.archived
|
return data?.time?.archived
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.not.toBeUndefined()
|
.not.toBeUndefined()
|
||||||
|
|
||||||
await openSidebar(page)
|
await openSidebar(page)
|
||||||
await expect(page.locator(sessionItemSelector(session.id))).toHaveCount(0)
|
await expect(page.locator(sessionItemSelector(session.id))).toHaveCount(0)
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("session can be deleted via header menu", async ({ page, withBackendProject }) => {
|
test("session can be deleted via header menu", async ({ page, sdk, gotoSession }) => {
|
||||||
const stamp = Date.now()
|
const stamp = Date.now()
|
||||||
const title = `e2e delete test ${stamp}`
|
const title = `e2e delete test ${stamp}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withSession(sdk, title, async (session) => {
|
||||||
await withSession(project.sdk, title, async (session) => {
|
await seedMessage(sdk, session.id)
|
||||||
await seedMessage(project.sdk, session.id)
|
await gotoSession(session.id)
|
||||||
await project.gotoSession(session.id)
|
const menu = await openSessionMoreMenu(page, session.id)
|
||||||
const menu = await openSessionMoreMenu(page, session.id)
|
await clickMenuItem(menu, /delete/i)
|
||||||
await clickMenuItem(menu, /delete/i)
|
await confirmDialog(page, /delete/i)
|
||||||
await confirmDialog(page, /delete/i)
|
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session
|
const data = await sdk.session
|
||||||
.get({ sessionID: session.id })
|
.get({ sessionID: session.id })
|
||||||
.then((r) => r.data)
|
.then((r) => r.data)
|
||||||
.catch(() => undefined)
|
.catch(() => undefined)
|
||||||
return data?.id
|
return data?.id
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.toBeUndefined()
|
.toBeUndefined()
|
||||||
|
|
||||||
await openSidebar(page)
|
await openSidebar(page)
|
||||||
await expect(page.locator(sessionItemSelector(session.id))).toHaveCount(0)
|
await expect(page.locator(sessionItemSelector(session.id))).toHaveCount(0)
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("session can be shared and unshared via header button", async ({ page, withBackendProject }) => {
|
test("session can be shared and unshared via header button", async ({ page, sdk, gotoSession }) => {
|
||||||
test.skip(shareDisabled, "Share is disabled in this environment (OPENCODE_DISABLE_SHARE).")
|
test.skip(shareDisabled, "Share is disabled in this environment (OPENCODE_DISABLE_SHARE).")
|
||||||
|
|
||||||
const stamp = Date.now()
|
const stamp = Date.now()
|
||||||
const title = `e2e share test ${stamp}`
|
const title = `e2e share test ${stamp}`
|
||||||
|
|
||||||
await withBackendProject(async (project) => {
|
await withSession(sdk, title, async (session) => {
|
||||||
await withSession(project.sdk, title, async (session) => {
|
await seedMessage(sdk, session.id)
|
||||||
await seedMessage(project.sdk, session.id)
|
await gotoSession(session.id)
|
||||||
await project.gotoSession(session.id)
|
|
||||||
|
|
||||||
const shared = await openSharePopover(page)
|
const shared = await openSharePopover(page)
|
||||||
const publish = shared.popoverBody.getByRole("button", { name: "Publish" }).first()
|
const publish = shared.popoverBody.getByRole("button", { name: "Publish" }).first()
|
||||||
await expect(publish).toBeVisible({ timeout: 30_000 })
|
await expect(publish).toBeVisible({ timeout: 30_000 })
|
||||||
await publish.click()
|
await publish.click()
|
||||||
|
|
||||||
await expect(shared.popoverBody.getByRole("button", { name: "Unpublish" }).first()).toBeVisible({
|
await expect(shared.popoverBody.getByRole("button", { name: "Unpublish" }).first()).toBeVisible({
|
||||||
timeout: 30_000,
|
timeout: 30_000,
|
||||||
})
|
})
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
const data = await sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
||||||
return data?.share?.url || undefined
|
return data?.share?.url || undefined
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.not.toBeUndefined()
|
.not.toBeUndefined()
|
||||||
|
|
||||||
const unpublish = shared.popoverBody.getByRole("button", { name: "Unpublish" }).first()
|
const unpublish = shared.popoverBody.getByRole("button", { name: "Unpublish" }).first()
|
||||||
await expect(unpublish).toBeVisible({ timeout: 30_000 })
|
await expect(unpublish).toBeVisible({ timeout: 30_000 })
|
||||||
await unpublish.click()
|
await unpublish.click()
|
||||||
|
|
||||||
await expect(shared.popoverBody.getByRole("button", { name: "Publish" }).first()).toBeVisible({
|
await expect(shared.popoverBody.getByRole("button", { name: "Publish" }).first()).toBeVisible({
|
||||||
timeout: 30_000,
|
timeout: 30_000,
|
||||||
})
|
})
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(
|
.poll(
|
||||||
async () => {
|
async () => {
|
||||||
const data = await project.sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
const data = await sdk.session.get({ sessionID: session.id }).then((r) => r.data)
|
||||||
return data?.share?.url || undefined
|
return data?.share?.url || undefined
|
||||||
},
|
},
|
||||||
{ timeout: 30_000 },
|
{ timeout: 30_000 },
|
||||||
)
|
)
|
||||||
.toBeUndefined()
|
.toBeUndefined()
|
||||||
|
|
||||||
const unshared = await openSharePopover(page)
|
const unshared = await openSharePopover(page)
|
||||||
await expect(unshared.popoverBody.getByRole("button", { name: "Publish" }).first()).toBeVisible({
|
await expect(unshared.popoverBody.getByRole("button", { name: "Publish" }).first()).toBeVisible({
|
||||||
timeout: 30_000,
|
timeout: 30_000,
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -241,7 +241,7 @@ test("changing file open keybind works", async ({ page, gotoSession }) => {
|
|||||||
await expect(keybindButton).toBeVisible()
|
await expect(keybindButton).toBeVisible()
|
||||||
|
|
||||||
const initialKeybind = await keybindButton.textContent()
|
const initialKeybind = await keybindButton.textContent()
|
||||||
expect(initialKeybind).toContain("K")
|
expect(initialKeybind).toContain("P")
|
||||||
|
|
||||||
await keybindButton.click()
|
await keybindButton.click()
|
||||||
await expect(keybindButton).toHaveText(/press/i)
|
await expect(keybindButton).toHaveText(/press/i)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { test, expect, settingsKey } from "../fixtures"
|
|||||||
import { closeDialog, openSettings } from "../actions"
|
import { closeDialog, openSettings } from "../actions"
|
||||||
import {
|
import {
|
||||||
settingsColorSchemeSelector,
|
settingsColorSchemeSelector,
|
||||||
settingsCodeFontSelector,
|
settingsFontSelector,
|
||||||
settingsLanguageSelectSelector,
|
settingsLanguageSelectSelector,
|
||||||
settingsNotificationsAgentSelector,
|
settingsNotificationsAgentSelector,
|
||||||
settingsNotificationsErrorsSelector,
|
settingsNotificationsErrorsSelector,
|
||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
settingsSoundsErrorsSelector,
|
settingsSoundsErrorsSelector,
|
||||||
settingsSoundsPermissionsSelector,
|
settingsSoundsPermissionsSelector,
|
||||||
settingsThemeSelector,
|
settingsThemeSelector,
|
||||||
settingsUIFontSelector,
|
|
||||||
settingsUpdatesStartupSelector,
|
settingsUpdatesStartupSelector,
|
||||||
} from "../selectors"
|
} from "../selectors"
|
||||||
|
|
||||||
@@ -153,199 +152,39 @@ test("legacy oc-1 theme migrates to oc-2", async ({ page, gotoSession }) => {
|
|||||||
.toBeNull()
|
.toBeNull()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("typing a code font with spaces persists and updates CSS variable", async ({ page, gotoSession }) => {
|
test("changing font persists in localStorage and updates CSS variable", async ({ page, gotoSession }) => {
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
|
|
||||||
const dialog = await openSettings(page)
|
const dialog = await openSettings(page)
|
||||||
const input = dialog.locator(settingsCodeFontSelector)
|
const select = dialog.locator(settingsFontSelector)
|
||||||
await expect(input).toBeVisible()
|
await expect(select).toBeVisible()
|
||||||
await expect(input).toHaveAttribute("placeholder", "System Mono")
|
|
||||||
|
|
||||||
const initialFontFamily = await page.evaluate(() =>
|
const initialFontFamily = await page.evaluate(() => {
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
return getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono")
|
||||||
)
|
})
|
||||||
const initialUIFamily = await page.evaluate(() =>
|
expect(initialFontFamily).toContain("IBM Plex Mono")
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
|
||||||
expect(initialFontFamily).toContain("ui-monospace")
|
|
||||||
|
|
||||||
const next = "Test Mono"
|
await select.locator('[data-slot="select-select-trigger"]').click()
|
||||||
|
|
||||||
await input.click()
|
const items = page.locator('[data-slot="select-select-item"]')
|
||||||
await input.clear()
|
await items.nth(2).click()
|
||||||
await input.pressSequentially(next)
|
|
||||||
await expect(input).toHaveValue(next)
|
|
||||||
|
|
||||||
await expect
|
await page.waitForTimeout(100)
|
||||||
.poll(async () => {
|
|
||||||
return await page.evaluate((key) => {
|
|
||||||
const raw = localStorage.getItem(key)
|
|
||||||
return raw ? JSON.parse(raw) : null
|
|
||||||
}, settingsKey)
|
|
||||||
})
|
|
||||||
.toMatchObject({
|
|
||||||
appearance: {
|
|
||||||
mono: next,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const newFontFamily = await page.evaluate(() =>
|
const stored = await page.evaluate((key) => {
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
const raw = localStorage.getItem(key)
|
||||||
)
|
return raw ? JSON.parse(raw) : null
|
||||||
const newUIFamily = await page.evaluate(() =>
|
}, settingsKey)
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
expect(stored?.appearance?.font).not.toBe("ibm-plex-mono")
|
||||||
expect(newFontFamily).toContain(next)
|
|
||||||
|
const newFontFamily = await page.evaluate(() => {
|
||||||
|
return getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono")
|
||||||
|
})
|
||||||
expect(newFontFamily).not.toBe(initialFontFamily)
|
expect(newFontFamily).not.toBe(initialFontFamily)
|
||||||
expect(newUIFamily).toBe(initialUIFamily)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("typing a UI font with spaces persists and updates CSS variable", async ({ page, gotoSession }) => {
|
test("color scheme and font rehydrate after reload", async ({ page, gotoSession }) => {
|
||||||
await gotoSession()
|
|
||||||
|
|
||||||
const dialog = await openSettings(page)
|
|
||||||
const input = dialog.locator(settingsUIFontSelector)
|
|
||||||
await expect(input).toBeVisible()
|
|
||||||
await expect(input).toHaveAttribute("placeholder", "System Sans")
|
|
||||||
|
|
||||||
const initialFontFamily = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
|
||||||
const initialCodeFamily = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
|
||||||
)
|
|
||||||
expect(initialFontFamily).toContain("ui-sans-serif")
|
|
||||||
|
|
||||||
const next = "Test Sans"
|
|
||||||
|
|
||||||
await input.click()
|
|
||||||
await input.clear()
|
|
||||||
await input.pressSequentially(next)
|
|
||||||
await expect(input).toHaveValue(next)
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
return await page.evaluate((key) => {
|
|
||||||
const raw = localStorage.getItem(key)
|
|
||||||
return raw ? JSON.parse(raw) : null
|
|
||||||
}, settingsKey)
|
|
||||||
})
|
|
||||||
.toMatchObject({
|
|
||||||
appearance: {
|
|
||||||
sans: next,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const newFontFamily = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
|
||||||
const newCodeFamily = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
|
||||||
)
|
|
||||||
expect(newFontFamily).toContain(next)
|
|
||||||
expect(newFontFamily).not.toBe(initialFontFamily)
|
|
||||||
expect(newCodeFamily).toBe(initialCodeFamily)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("clearing the code font field restores the default placeholder and stack", async ({ page, gotoSession }) => {
|
|
||||||
await gotoSession()
|
|
||||||
|
|
||||||
const dialog = await openSettings(page)
|
|
||||||
const input = dialog.locator(settingsCodeFontSelector)
|
|
||||||
await expect(input).toBeVisible()
|
|
||||||
|
|
||||||
await input.click()
|
|
||||||
await input.clear()
|
|
||||||
await input.pressSequentially("Reset Mono")
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
return await page.evaluate((key) => {
|
|
||||||
const raw = localStorage.getItem(key)
|
|
||||||
return raw ? JSON.parse(raw) : null
|
|
||||||
}, settingsKey)
|
|
||||||
})
|
|
||||||
.toMatchObject({
|
|
||||||
appearance: {
|
|
||||||
mono: "Reset Mono",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await input.clear()
|
|
||||||
await input.press("Space")
|
|
||||||
await expect(input).toHaveValue("")
|
|
||||||
await expect(input).toHaveAttribute("placeholder", "System Mono")
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
return await page.evaluate((key) => {
|
|
||||||
const raw = localStorage.getItem(key)
|
|
||||||
return raw ? JSON.parse(raw) : null
|
|
||||||
}, settingsKey)
|
|
||||||
})
|
|
||||||
.toMatchObject({
|
|
||||||
appearance: {
|
|
||||||
mono: "",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const fontFamily = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
|
||||||
)
|
|
||||||
expect(fontFamily).toContain("ui-monospace")
|
|
||||||
expect(fontFamily).not.toContain("Reset Mono")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("clearing the UI font field restores the default placeholder and stack", async ({ page, gotoSession }) => {
|
|
||||||
await gotoSession()
|
|
||||||
|
|
||||||
const dialog = await openSettings(page)
|
|
||||||
const input = dialog.locator(settingsUIFontSelector)
|
|
||||||
await expect(input).toBeVisible()
|
|
||||||
|
|
||||||
await input.click()
|
|
||||||
await input.clear()
|
|
||||||
await input.pressSequentially("Reset Sans")
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
return await page.evaluate((key) => {
|
|
||||||
const raw = localStorage.getItem(key)
|
|
||||||
return raw ? JSON.parse(raw) : null
|
|
||||||
}, settingsKey)
|
|
||||||
})
|
|
||||||
.toMatchObject({
|
|
||||||
appearance: {
|
|
||||||
sans: "Reset Sans",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await input.clear()
|
|
||||||
await input.press("Space")
|
|
||||||
await expect(input).toHaveValue("")
|
|
||||||
await expect(input).toHaveAttribute("placeholder", "System Sans")
|
|
||||||
|
|
||||||
await expect
|
|
||||||
.poll(async () => {
|
|
||||||
return await page.evaluate((key) => {
|
|
||||||
const raw = localStorage.getItem(key)
|
|
||||||
return raw ? JSON.parse(raw) : null
|
|
||||||
}, settingsKey)
|
|
||||||
})
|
|
||||||
.toMatchObject({
|
|
||||||
appearance: {
|
|
||||||
sans: "",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const fontFamily = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
|
||||||
expect(fontFamily).toContain("ui-sans-serif")
|
|
||||||
expect(fontFamily).not.toContain("Reset Sans")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("color scheme, code font, and UI font rehydrate after reload", async ({ page, gotoSession }) => {
|
|
||||||
await gotoSession()
|
await gotoSession()
|
||||||
|
|
||||||
const dialog = await openSettings(page)
|
const dialog = await openSettings(page)
|
||||||
@@ -356,35 +195,31 @@ test("color scheme, code font, and UI font rehydrate after reload", async ({ pag
|
|||||||
await page.locator('[data-slot="select-select-item"]').filter({ hasText: "Dark" }).click()
|
await page.locator('[data-slot="select-select-item"]').filter({ hasText: "Dark" }).click()
|
||||||
await expect(page.locator("html")).toHaveAttribute("data-color-scheme", "dark")
|
await expect(page.locator("html")).toHaveAttribute("data-color-scheme", "dark")
|
||||||
|
|
||||||
const code = dialog.locator(settingsCodeFontSelector)
|
const fontSelect = dialog.locator(settingsFontSelector)
|
||||||
const ui = dialog.locator(settingsUIFontSelector)
|
await expect(fontSelect).toBeVisible()
|
||||||
await expect(code).toBeVisible()
|
|
||||||
await expect(ui).toBeVisible()
|
|
||||||
|
|
||||||
const initialMono = await page.evaluate(() =>
|
const initialFontFamily = await page.evaluate(() => {
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
return getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim()
|
||||||
)
|
})
|
||||||
const initialSans = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
|
||||||
|
|
||||||
const initialSettings = await page.evaluate((key) => {
|
const initialSettings = await page.evaluate((key) => {
|
||||||
const raw = localStorage.getItem(key)
|
const raw = localStorage.getItem(key)
|
||||||
return raw ? JSON.parse(raw) : null
|
return raw ? JSON.parse(raw) : null
|
||||||
}, settingsKey)
|
}, settingsKey)
|
||||||
|
|
||||||
const mono = initialSettings?.appearance?.mono === "Reload Mono" ? "Reload Mono 2" : "Reload Mono"
|
const currentFont =
|
||||||
const sans = initialSettings?.appearance?.sans === "Reload Sans" ? "Reload Sans 2" : "Reload Sans"
|
(await fontSelect.locator('[data-slot="select-select-trigger-value"]').textContent())?.trim() ?? ""
|
||||||
|
await fontSelect.locator('[data-slot="select-select-trigger"]').click()
|
||||||
|
|
||||||
await code.click()
|
const fontItems = page.locator('[data-slot="select-select-item"]')
|
||||||
await code.clear()
|
expect(await fontItems.count()).toBeGreaterThan(1)
|
||||||
await code.pressSequentially(mono)
|
|
||||||
await expect(code).toHaveValue(mono)
|
|
||||||
|
|
||||||
await ui.click()
|
if (currentFont) {
|
||||||
await ui.clear()
|
await fontItems.filter({ hasNotText: currentFont }).first().click()
|
||||||
await ui.pressSequentially(sans)
|
}
|
||||||
await expect(ui).toHaveValue(sans)
|
if (!currentFont) {
|
||||||
|
await fontItems.nth(1).click()
|
||||||
|
}
|
||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => {
|
.poll(async () => {
|
||||||
@@ -395,8 +230,7 @@ test("color scheme, code font, and UI font rehydrate after reload", async ({ pag
|
|||||||
})
|
})
|
||||||
.toMatchObject({
|
.toMatchObject({
|
||||||
appearance: {
|
appearance: {
|
||||||
mono,
|
font: expect.any(String),
|
||||||
sans,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -405,18 +239,11 @@ test("color scheme, code font, and UI font rehydrate after reload", async ({ pag
|
|||||||
return raw ? JSON.parse(raw) : null
|
return raw ? JSON.parse(raw) : null
|
||||||
}, settingsKey)
|
}, settingsKey)
|
||||||
|
|
||||||
const updatedMono = await page.evaluate(() =>
|
const updatedFontFamily = await page.evaluate(() => {
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
return getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim()
|
||||||
)
|
})
|
||||||
const updatedSans = await page.evaluate(() =>
|
expect(updatedFontFamily).not.toBe(initialFontFamily)
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
expect(updatedSettings?.appearance?.font).not.toBe(initialSettings?.appearance?.font)
|
||||||
)
|
|
||||||
expect(updatedMono).toContain(mono)
|
|
||||||
expect(updatedMono).not.toBe(initialMono)
|
|
||||||
expect(updatedSans).toContain(sans)
|
|
||||||
expect(updatedSans).not.toBe(initialSans)
|
|
||||||
expect(updatedSettings?.appearance?.mono).toBe(mono)
|
|
||||||
expect(updatedSettings?.appearance?.sans).toBe(sans)
|
|
||||||
|
|
||||||
await closeDialog(page, dialog)
|
await closeDialog(page, dialog)
|
||||||
await page.reload()
|
await page.reload()
|
||||||
@@ -432,8 +259,7 @@ test("color scheme, code font, and UI font rehydrate after reload", async ({ pag
|
|||||||
})
|
})
|
||||||
.toMatchObject({
|
.toMatchObject({
|
||||||
appearance: {
|
appearance: {
|
||||||
mono,
|
font: updatedSettings?.appearance?.font,
|
||||||
sans,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -444,32 +270,17 @@ test("color scheme, code font, and UI font rehydrate after reload", async ({ pag
|
|||||||
|
|
||||||
await expect
|
await expect
|
||||||
.poll(async () => {
|
.poll(async () => {
|
||||||
return await page.evaluate(() =>
|
return await page.evaluate(() => {
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
return getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim()
|
||||||
)
|
})
|
||||||
})
|
})
|
||||||
.toContain(mono)
|
.not.toBe(initialFontFamily)
|
||||||
|
|
||||||
await expect
|
const rehydratedFontFamily = await page.evaluate(() => {
|
||||||
.poll(async () => {
|
return getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim()
|
||||||
return await page.evaluate(() =>
|
})
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
expect(rehydratedFontFamily).not.toBe(initialFontFamily)
|
||||||
)
|
expect(rehydratedSettings?.appearance?.font).toBe(updatedSettings?.appearance?.font)
|
||||||
})
|
|
||||||
.toContain(sans)
|
|
||||||
|
|
||||||
const rehydratedMono = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono").trim(),
|
|
||||||
)
|
|
||||||
const rehydratedSans = await page.evaluate(() =>
|
|
||||||
getComputedStyle(document.documentElement).getPropertyValue("--font-family-sans").trim(),
|
|
||||||
)
|
|
||||||
expect(rehydratedMono).toContain(mono)
|
|
||||||
expect(rehydratedMono).not.toBe(initialMono)
|
|
||||||
expect(rehydratedSans).toContain(sans)
|
|
||||||
expect(rehydratedSans).not.toBe(initialSans)
|
|
||||||
expect(rehydratedSettings?.appearance?.mono).toBe(mono)
|
|
||||||
expect(rehydratedSettings?.appearance?.sans).toBe(sans)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test("toggling notification agent switch updates localStorage", async ({ page, gotoSession }) => {
|
test("toggling notification agent switch updates localStorage", async ({ page, gotoSession }) => {
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import {
|
import { cleanupSession, closeSidebar, hoverSessionItem } from "../actions"
|
||||||
defocus,
|
|
||||||
cleanupSession,
|
|
||||||
cleanupTestProject,
|
|
||||||
closeSidebar,
|
|
||||||
createTestProject,
|
|
||||||
hoverSessionItem,
|
|
||||||
openSidebar,
|
|
||||||
waitSession,
|
|
||||||
} from "../actions"
|
|
||||||
import { projectSwitchSelector } from "../selectors"
|
import { projectSwitchSelector } from "../selectors"
|
||||||
import { dirSlug } from "../utils"
|
|
||||||
|
|
||||||
test("collapsed sidebar popover stays open when archiving a session", async ({ page, slug, sdk, gotoSession }) => {
|
test("collapsed sidebar popover stays open when archiving a session", async ({ page, slug, sdk, gotoSession }) => {
|
||||||
const stamp = Date.now()
|
const stamp = Date.now()
|
||||||
@@ -47,72 +37,3 @@ test("collapsed sidebar popover stays open when archiving a session", async ({ p
|
|||||||
await cleanupSession({ sdk, sessionID: two.id })
|
await cleanupSession({ sdk, sessionID: two.id })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
test("open sidebar project popover stays closed after clicking avatar", async ({ page, withProject }) => {
|
|
||||||
await page.setViewportSize({ width: 1400, height: 800 })
|
|
||||||
|
|
||||||
const other = await createTestProject()
|
|
||||||
const slug = dirSlug(other)
|
|
||||||
|
|
||||||
try {
|
|
||||||
await withProject(
|
|
||||||
async () => {
|
|
||||||
await openSidebar(page)
|
|
||||||
|
|
||||||
const project = page.locator(projectSwitchSelector(slug)).first()
|
|
||||||
const card = page.locator('[data-component="hover-card-content"]')
|
|
||||||
|
|
||||||
await expect(project).toBeVisible()
|
|
||||||
await project.hover()
|
|
||||||
await expect(card.getByText(/recent sessions/i)).toBeVisible()
|
|
||||||
|
|
||||||
await page.mouse.down()
|
|
||||||
await expect(card).toHaveCount(0)
|
|
||||||
await page.mouse.up()
|
|
||||||
|
|
||||||
await waitSession(page, { directory: other })
|
|
||||||
await expect(card).toHaveCount(0)
|
|
||||||
},
|
|
||||||
{ extra: [other] },
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
await cleanupTestProject(other)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test("open sidebar project switch activates on first tabbed enter", async ({ page, withProject }) => {
|
|
||||||
await page.setViewportSize({ width: 1400, height: 800 })
|
|
||||||
|
|
||||||
const other = await createTestProject()
|
|
||||||
const slug = dirSlug(other)
|
|
||||||
|
|
||||||
try {
|
|
||||||
await withProject(
|
|
||||||
async () => {
|
|
||||||
await openSidebar(page)
|
|
||||||
await defocus(page)
|
|
||||||
|
|
||||||
const project = page.locator(projectSwitchSelector(slug)).first()
|
|
||||||
|
|
||||||
await expect(project).toBeVisible()
|
|
||||||
|
|
||||||
let hit = false
|
|
||||||
for (let i = 0; i < 20; i++) {
|
|
||||||
hit = await project.evaluate((el) => {
|
|
||||||
return el.matches(":focus") || !!el.parentElement?.matches(":focus")
|
|
||||||
})
|
|
||||||
if (hit) break
|
|
||||||
await page.keyboard.press("Tab")
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(hit).toBe(true)
|
|
||||||
|
|
||||||
await page.keyboard.press("Enter")
|
|
||||||
await waitSession(page, { directory: other })
|
|
||||||
},
|
|
||||||
{ extra: [other] },
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
await cleanupTestProject(other)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Page } from "@playwright/test"
|
import type { Page } from "@playwright/test"
|
||||||
import { runTerminal, waitTerminalReady } from "../actions"
|
import { runTerminal, waitTerminalReady } from "../actions"
|
||||||
import { test, expect } from "../fixtures"
|
import { test, expect } from "../fixtures"
|
||||||
import { dropdownMenuContentSelector, terminalSelector } from "../selectors"
|
import { terminalSelector } from "../selectors"
|
||||||
import { terminalToggleKey, workspacePersistKey } from "../utils"
|
import { terminalToggleKey, workspacePersistKey } from "../utils"
|
||||||
|
|
||||||
type State = {
|
type State = {
|
||||||
@@ -130,39 +130,3 @@ test("closing the active terminal tab falls back to the previous tab", async ({
|
|||||||
.toEqual({ count: 1, first: true })
|
.toEqual({ count: 1, first: true })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test("terminal tab can be renamed from the context menu", async ({ page, withProject }) => {
|
|
||||||
await withProject(async ({ directory, gotoSession }) => {
|
|
||||||
const key = workspacePersistKey(directory, "terminal")
|
|
||||||
const rename = `E2E term ${Date.now()}`
|
|
||||||
const tab = page.locator('#terminal-panel [data-slot="tabs-trigger"]').first()
|
|
||||||
|
|
||||||
await gotoSession()
|
|
||||||
await open(page)
|
|
||||||
|
|
||||||
await expect(tab).toContainText(/Terminal 1/)
|
|
||||||
await tab.click({ button: "right" })
|
|
||||||
|
|
||||||
const menu = page.locator(dropdownMenuContentSelector).first()
|
|
||||||
await expect(menu).toBeVisible()
|
|
||||||
await menu.getByRole("menuitem", { name: /^Rename$/i }).click()
|
|
||||||
await expect(menu).toHaveCount(0)
|
|
||||||
|
|
||||||
const input = page.locator('#terminal-panel input[type="text"]').first()
|
|
||||||
await expect(input).toBeVisible()
|
|
||||||
await input.fill(rename)
|
|
||||||
await input.press("Enter")
|
|
||||||
|
|
||||||
await expect(input).toHaveCount(0)
|
|
||||||
await expect(tab).toContainText(rename)
|
|
||||||
await expect
|
|
||||||
.poll(
|
|
||||||
async () => {
|
|
||||||
const state = await store(page, key)
|
|
||||||
return state?.all[0]?.title
|
|
||||||
},
|
|
||||||
{ timeout: 5_000 },
|
|
||||||
)
|
|
||||||
.toBe(rename)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -26,21 +26,21 @@ export const serverNamePattern = new RegExp(`(?:${serverNames.map(escape).join("
|
|||||||
export const modKey = process.platform === "darwin" ? "Meta" : "Control"
|
export const modKey = process.platform === "darwin" ? "Meta" : "Control"
|
||||||
export const terminalToggleKey = "Control+Backquote"
|
export const terminalToggleKey = "Control+Backquote"
|
||||||
|
|
||||||
export function createSdk(directory?: string, baseUrl = serverUrl) {
|
export function createSdk(directory?: string) {
|
||||||
return createOpencodeClient({ baseUrl, directory, throwOnError: true })
|
return createOpencodeClient({ baseUrl: serverUrl, directory, throwOnError: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resolveDirectory(directory: string, baseUrl = serverUrl) {
|
export async function resolveDirectory(directory: string) {
|
||||||
return createSdk(directory, baseUrl)
|
return createSdk(directory)
|
||||||
.path.get()
|
.path.get()
|
||||||
.then((x) => x.data?.directory ?? directory)
|
.then((x) => x.data?.directory ?? directory)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getWorktree(baseUrl = serverUrl) {
|
export async function getWorktree() {
|
||||||
const sdk = createSdk(undefined, baseUrl)
|
const sdk = createSdk()
|
||||||
const result = await sdk.path.get()
|
const result = await sdk.path.get()
|
||||||
const data = result.data
|
const data = result.data
|
||||||
if (!data?.worktree) throw new Error(`Failed to resolve a worktree from ${baseUrl}/path`)
|
if (!data?.worktree) throw new Error(`Failed to resolve a worktree from ${serverUrl}/path`)
|
||||||
return data.worktree
|
return data.worktree
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<html lang="en" style="background-color: var(--background-base)">
|
<html lang="en" style="background-color: var(--background-base)">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, interactive-widget=resizes-content" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>OpenCode</title>
|
<title>OpenCode</title>
|
||||||
<link rel="icon" type="image/png" href="/favicon-96x96-v3.png" sizes="96x96" />
|
<link rel="icon" type="image/png" href="/favicon-96x96-v3.png" sizes="96x96" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon-v3.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon-v3.svg" />
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode-ai/app",
|
"name": "@opencode-ai/app",
|
||||||
"version": "1.3.13",
|
"version": "1.2.27",
|
||||||
"description": "",
|
"description": "",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
@@ -51,11 +51,9 @@
|
|||||||
"@solid-primitives/resize-observer": "2.1.3",
|
"@solid-primitives/resize-observer": "2.1.3",
|
||||||
"@solid-primitives/scroll": "2.1.3",
|
"@solid-primitives/scroll": "2.1.3",
|
||||||
"@solid-primitives/storage": "catalog:",
|
"@solid-primitives/storage": "catalog:",
|
||||||
"@solid-primitives/timer": "1.4.4",
|
|
||||||
"@solid-primitives/websocket": "1.3.1",
|
"@solid-primitives/websocket": "1.3.1",
|
||||||
"@solidjs/meta": "catalog:",
|
"@solidjs/meta": "catalog:",
|
||||||
"@solidjs/router": "catalog:",
|
"@solidjs/router": "catalog:",
|
||||||
"@tanstack/solid-query": "5.91.4",
|
|
||||||
"@thisbeyond/solid-dnd": "0.7.5",
|
"@thisbeyond/solid-dnd": "0.7.5",
|
||||||
"diff": "catalog:",
|
"diff": "catalog:",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ const serverEnv = {
|
|||||||
OPENCODE_E2E_PROJECT_DIR: repoDir,
|
OPENCODE_E2E_PROJECT_DIR: repoDir,
|
||||||
OPENCODE_E2E_SESSION_TITLE: "E2E Session",
|
OPENCODE_E2E_SESSION_TITLE: "E2E Session",
|
||||||
OPENCODE_E2E_MESSAGE: "Seeded for UI e2e",
|
OPENCODE_E2E_MESSAGE: "Seeded for UI e2e",
|
||||||
OPENCODE_E2E_MODEL: process.env.OPENCODE_E2E_MODEL ?? "opencode/gpt-5-nano",
|
OPENCODE_E2E_MODEL: "opencode/gpt-5-nano",
|
||||||
OPENCODE_CLIENT: "app",
|
OPENCODE_CLIENT: "app",
|
||||||
OPENCODE_STRICT_CONFIG_DEPS: "true",
|
OPENCODE_STRICT_CONFIG_DEPS: "true",
|
||||||
} satisfies Record<string, string>
|
} satisfies Record<string, string>
|
||||||
|
|||||||
+16
-27
@@ -6,10 +6,9 @@ import { MarkedProvider } from "@opencode-ai/ui/context/marked"
|
|||||||
import { File } from "@opencode-ai/ui/file"
|
import { File } from "@opencode-ai/ui/file"
|
||||||
import { Font } from "@opencode-ai/ui/font"
|
import { Font } from "@opencode-ai/ui/font"
|
||||||
import { Splash } from "@opencode-ai/ui/logo"
|
import { Splash } from "@opencode-ai/ui/logo"
|
||||||
import { ThemeProvider } from "@opencode-ai/ui/theme/context"
|
import { ThemeProvider } from "@opencode-ai/ui/theme"
|
||||||
import { MetaProvider } from "@solidjs/meta"
|
import { MetaProvider } from "@solidjs/meta"
|
||||||
import { type BaseRouterProps, Navigate, Route, Router } from "@solidjs/router"
|
import { type BaseRouterProps, Navigate, Route, Router } from "@solidjs/router"
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/solid-query"
|
|
||||||
import { type Duration, Effect } from "effect"
|
import { type Duration, Effect } from "effect"
|
||||||
import {
|
import {
|
||||||
type Component,
|
type Component,
|
||||||
@@ -32,11 +31,12 @@ import { FileProvider } from "@/context/file"
|
|||||||
import { GlobalSDKProvider } from "@/context/global-sdk"
|
import { GlobalSDKProvider } from "@/context/global-sdk"
|
||||||
import { GlobalSyncProvider } from "@/context/global-sync"
|
import { GlobalSyncProvider } from "@/context/global-sync"
|
||||||
import { HighlightsProvider } from "@/context/highlights"
|
import { HighlightsProvider } from "@/context/highlights"
|
||||||
import { LanguageProvider, type Locale, useLanguage } from "@/context/language"
|
import { LanguageProvider, useLanguage } from "@/context/language"
|
||||||
import { LayoutProvider } from "@/context/layout"
|
import { LayoutProvider } from "@/context/layout"
|
||||||
import { ModelsProvider } from "@/context/models"
|
import { ModelsProvider } from "@/context/models"
|
||||||
import { NotificationProvider } from "@/context/notification"
|
import { NotificationProvider } from "@/context/notification"
|
||||||
import { PermissionProvider } from "@/context/permission"
|
import { PermissionProvider } from "@/context/permission"
|
||||||
|
import { usePlatform } from "@/context/platform"
|
||||||
import { PromptProvider } from "@/context/prompt"
|
import { PromptProvider } from "@/context/prompt"
|
||||||
import { ServerConnection, ServerProvider, serverName, useServer } from "@/context/server"
|
import { ServerConnection, ServerProvider, serverName, useServer } from "@/context/server"
|
||||||
import { SettingsProvider } from "@/context/settings"
|
import { SettingsProvider } from "@/context/settings"
|
||||||
@@ -47,14 +47,9 @@ import { ErrorPage } from "./pages/error"
|
|||||||
import { useCheckServerHealth } from "./utils/server-health"
|
import { useCheckServerHealth } from "./utils/server-health"
|
||||||
|
|
||||||
const HomeRoute = lazy(() => import("@/pages/home"))
|
const HomeRoute = lazy(() => import("@/pages/home"))
|
||||||
const loadSession = () => import("@/pages/session")
|
const Session = lazy(() => import("@/pages/session"))
|
||||||
const Session = lazy(loadSession)
|
|
||||||
const Loading = () => <div class="size-full" />
|
const Loading = () => <div class="size-full" />
|
||||||
|
|
||||||
if (typeof location === "object" && /\/session(?:\/|$)/.test(location.pathname)) {
|
|
||||||
void loadSession()
|
|
||||||
}
|
|
||||||
|
|
||||||
const SessionRoute = () => (
|
const SessionRoute = () => (
|
||||||
<SessionProviders>
|
<SessionProviders>
|
||||||
<Session />
|
<Session />
|
||||||
@@ -81,9 +76,9 @@ declare global {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function QueryProvider(props: ParentProps) {
|
function MarkedProviderWithNativeParser(props: ParentProps) {
|
||||||
const client = new QueryClient()
|
const platform = usePlatform()
|
||||||
return <QueryClientProvider client={client}>{props.children}</QueryClientProvider>
|
return <MarkedProvider nativeParser={platform.parseMarkdown}>{props.children}</MarkedProvider>
|
||||||
}
|
}
|
||||||
|
|
||||||
function AppShellProviders(props: ParentProps) {
|
function AppShellProviders(props: ParentProps) {
|
||||||
@@ -129,7 +124,7 @@ function RouterRoot(props: ParentProps<{ appChildren?: JSX.Element }>) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AppBaseProviders(props: ParentProps<{ locale?: Locale }>) {
|
export function AppBaseProviders(props: ParentProps) {
|
||||||
return (
|
return (
|
||||||
<MetaProvider>
|
<MetaProvider>
|
||||||
<Font />
|
<Font />
|
||||||
@@ -138,16 +133,14 @@ export function AppBaseProviders(props: ParentProps<{ locale?: Locale }>) {
|
|||||||
void window.api?.setTitlebar?.({ mode })
|
void window.api?.setTitlebar?.({ mode })
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<LanguageProvider locale={props.locale}>
|
<LanguageProvider>
|
||||||
<UiI18nBridge>
|
<UiI18nBridge>
|
||||||
<ErrorBoundary fallback={(error) => <ErrorPage error={error} />}>
|
<ErrorBoundary fallback={(error) => <ErrorPage error={error} />}>
|
||||||
<QueryProvider>
|
<DialogProvider>
|
||||||
<DialogProvider>
|
<MarkedProviderWithNativeParser>
|
||||||
<MarkedProvider>
|
<FileComponentProvider component={File}>{props.children}</FileComponentProvider>
|
||||||
<FileComponentProvider component={File}>{props.children}</FileComponentProvider>
|
</MarkedProviderWithNativeParser>
|
||||||
</MarkedProvider>
|
</DialogProvider>
|
||||||
</DialogProvider>
|
|
||||||
</QueryProvider>
|
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
</UiI18nBridge>
|
</UiI18nBridge>
|
||||||
</LanguageProvider>
|
</LanguageProvider>
|
||||||
@@ -183,7 +176,7 @@ function ConnectionGate(props: ParentProps<{ disableHealthCheck?: boolean }>) {
|
|||||||
}
|
}
|
||||||
}).pipe(
|
}).pipe(
|
||||||
effectMinDuration(checkMode() === "blocking" ? "1.2 seconds" : 0),
|
effectMinDuration(checkMode() === "blocking" ? "1.2 seconds" : 0),
|
||||||
Effect.timeoutOrElse({ duration: "10 seconds", orElse: () => Effect.succeed(false) }),
|
Effect.timeoutOrElse({ duration: "10 seconds", onTimeout: () => Effect.succeed(false) }),
|
||||||
Effect.ensuring(Effect.sync(() => setCheckMode("background"))),
|
Effect.ensuring(Effect.sync(() => setCheckMode("background"))),
|
||||||
Effect.runPromise,
|
Effect.runPromise,
|
||||||
),
|
),
|
||||||
@@ -283,11 +276,7 @@ export function AppInterface(props: {
|
|||||||
disableHealthCheck?: boolean
|
disableHealthCheck?: boolean
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<ServerProvider
|
<ServerProvider defaultServer={props.defaultServer} servers={props.servers}>
|
||||||
defaultServer={props.defaultServer}
|
|
||||||
disableHealthCheck={props.disableHealthCheck}
|
|
||||||
servers={props.servers}
|
|
||||||
>
|
|
||||||
<ConnectionGate disableHealthCheck={props.disableHealthCheck}>
|
<ConnectionGate disableHealthCheck={props.disableHealthCheck}>
|
||||||
<ServerKey>
|
<ServerKey>
|
||||||
<GlobalSDKProvider>
|
<GlobalSDKProvider>
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ function Cell(props: { bad?: boolean; dim?: boolean; label: string; tip: string;
|
|||||||
<Tooltip value={props.tip} placement="top">
|
<Tooltip value={props.tip} placement="top">
|
||||||
<div
|
<div
|
||||||
classList={{
|
classList={{
|
||||||
"flex min-h-[42px] w-full min-w-0 flex-col items-center justify-center rounded-[8px] px-0.5 py-1 text-center": true,
|
"flex min-h-[42px] w-full min-w-0 flex-col items-center justify-center rounded-[8px] bg-white/5 px-0.5 py-1 text-center": true,
|
||||||
"col-span-2": !!props.wide,
|
"col-span-2": !!props.wide,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -363,7 +363,11 @@ export function DebugBar() {
|
|||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
aria-label={language.t("debugBar.ariaLabel")}
|
aria-label={language.t("debugBar.ariaLabel")}
|
||||||
class="pointer-events-auto fixed bottom-3 right-3 z-50 w-[308px] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-xl border border-border-base bg-surface-raised-stronger-non-alpha p-0.5 text-text-strong shadow-[var(--shadow-lg-border-base)] sm:bottom-4 sm:right-4 sm:w-[324px]"
|
class="pointer-events-auto fixed bottom-3 right-3 z-50 w-[308px] max-w-[calc(100vw-1.5rem)] overflow-hidden rounded-xl border p-0.5 text-text-on-interactive-base shadow-[var(--shadow-lg-border-base)] sm:bottom-4 sm:right-4 sm:w-[324px]"
|
||||||
|
style={{
|
||||||
|
"background-color": "color-mix(in srgb, var(--icon-interactive-base) 42%, black)",
|
||||||
|
"border-color": "color-mix(in srgb, white 14%, transparent)",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<div class="grid grid-cols-5 gap-px font-mono">
|
<div class="grid grid-cols-5 gap-px font-mono">
|
||||||
<Cell
|
<Cell
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ProviderAuthAuthorization, ProviderAuthMethod } from "@opencode-ai/sdk/v2/client"
|
import type { ProviderAuthAuthorization } from "@opencode-ai/sdk/v2/client"
|
||||||
import { Button } from "@opencode-ai/ui/button"
|
import { Button } from "@opencode-ai/ui/button"
|
||||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
@@ -9,26 +9,20 @@ import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
|
|||||||
import { Spinner } from "@opencode-ai/ui/spinner"
|
import { Spinner } from "@opencode-ai/ui/spinner"
|
||||||
import { TextField } from "@opencode-ai/ui/text-field"
|
import { TextField } from "@opencode-ai/ui/text-field"
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
import { createEffect, createMemo, createResource, Match, onCleanup, onMount, Switch } from "solid-js"
|
import { createMemo, Match, onCleanup, onMount, Switch } from "solid-js"
|
||||||
import { createStore, produce } from "solid-js/store"
|
import { createStore, produce } from "solid-js/store"
|
||||||
import { Link } from "@/components/link"
|
import { Link } from "@/components/link"
|
||||||
|
import { useLanguage } from "@/context/language"
|
||||||
import { useGlobalSDK } from "@/context/global-sdk"
|
import { useGlobalSDK } from "@/context/global-sdk"
|
||||||
import { useGlobalSync } from "@/context/global-sync"
|
import { useGlobalSync } from "@/context/global-sync"
|
||||||
import { useLanguage } from "@/context/language"
|
import { DialogSelectModel } from "./dialog-select-model"
|
||||||
import { useProviders } from "@/hooks/use-providers"
|
import { DialogSelectProvider } from "./dialog-select-provider"
|
||||||
|
|
||||||
export function DialogConnectProvider(props: { provider: string }) {
|
export function DialogConnectProvider(props: { provider: string }) {
|
||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const globalSync = useGlobalSync()
|
const globalSync = useGlobalSync()
|
||||||
const globalSDK = useGlobalSDK()
|
const globalSDK = useGlobalSDK()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const providers = useProviders()
|
|
||||||
|
|
||||||
const all = () => {
|
|
||||||
void import("./dialog-select-provider").then((x) => {
|
|
||||||
dialog.show(() => <x.DialogSelectProvider />)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const alive = { value: true }
|
const alive = { value: true }
|
||||||
const timer = { current: undefined as ReturnType<typeof setTimeout> | undefined }
|
const timer = { current: undefined as ReturnType<typeof setTimeout> | undefined }
|
||||||
@@ -40,30 +34,16 @@ export function DialogConnectProvider(props: { provider: string }) {
|
|||||||
timer.current = undefined
|
timer.current = undefined
|
||||||
})
|
})
|
||||||
|
|
||||||
const provider = createMemo(
|
const provider = createMemo(() => globalSync.data.provider.all.find((x) => x.id === props.provider)!)
|
||||||
|
const methods = createMemo(
|
||||||
() =>
|
() =>
|
||||||
providers.all().find((x) => x.id === props.provider) ??
|
globalSync.data.provider_auth[props.provider] ?? [
|
||||||
globalSync.data.provider.all.find((x) => x.id === props.provider)!,
|
{
|
||||||
|
type: "api",
|
||||||
|
label: language.t("provider.connect.method.apiKey"),
|
||||||
|
},
|
||||||
|
],
|
||||||
)
|
)
|
||||||
const fallback = createMemo<ProviderAuthMethod[]>(() => [
|
|
||||||
{
|
|
||||||
type: "api" as const,
|
|
||||||
label: language.t("provider.connect.method.apiKey"),
|
|
||||||
},
|
|
||||||
])
|
|
||||||
const [auth] = createResource(
|
|
||||||
() => props.provider,
|
|
||||||
async () => {
|
|
||||||
const cached = globalSync.data.provider_auth[props.provider]
|
|
||||||
if (cached) return cached
|
|
||||||
const res = await globalSDK.client.provider.auth()
|
|
||||||
if (!alive.value) return fallback()
|
|
||||||
globalSync.set("provider_auth", res.data ?? {})
|
|
||||||
return res.data?.[props.provider] ?? fallback()
|
|
||||||
},
|
|
||||||
)
|
|
||||||
const loading = createMemo(() => auth.loading && !globalSync.data.provider_auth[props.provider])
|
|
||||||
const methods = createMemo(() => auth.latest ?? globalSync.data.provider_auth[props.provider] ?? fallback())
|
|
||||||
const [store, setStore] = createStore({
|
const [store, setStore] = createStore({
|
||||||
methodIndex: undefined as undefined | number,
|
methodIndex: undefined as undefined | number,
|
||||||
authorization: undefined as undefined | ProviderAuthAuthorization,
|
authorization: undefined as undefined | ProviderAuthAuthorization,
|
||||||
@@ -198,11 +178,7 @@ export function DialogConnectProvider(props: { provider: string }) {
|
|||||||
index: 0,
|
index: 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
const prompts = createMemo<NonNullable<ProviderAuthMethod["prompts"]>>(() => {
|
const prompts = createMemo(() => method()?.prompts ?? [])
|
||||||
const value = method()
|
|
||||||
if (value?.type !== "oauth") return []
|
|
||||||
return value.prompts ?? []
|
|
||||||
})
|
|
||||||
const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => {
|
const matches = (prompt: NonNullable<ReturnType<typeof prompts>[number]>, value: Record<string, string>) => {
|
||||||
if (!prompt.when) return true
|
if (!prompt.when) return true
|
||||||
const actual = value[prompt.when.key]
|
const actual = value[prompt.when.key]
|
||||||
@@ -321,12 +297,8 @@ export function DialogConnectProvider(props: { provider: string }) {
|
|||||||
listRef?.onKeyDown(e)
|
listRef?.onKeyDown(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
let auto = false
|
onMount(() => {
|
||||||
createEffect(() => {
|
|
||||||
if (auto) return
|
|
||||||
if (loading()) return
|
|
||||||
if (methods().length === 1) {
|
if (methods().length === 1) {
|
||||||
auto = true
|
|
||||||
selectMethod(0)
|
selectMethod(0)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -344,7 +316,7 @@ export function DialogConnectProvider(props: { provider: string }) {
|
|||||||
|
|
||||||
function goBack() {
|
function goBack() {
|
||||||
if (methods().length === 1) {
|
if (methods().length === 1) {
|
||||||
all()
|
dialog.show(() => <DialogSelectProvider />)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (store.authorization) {
|
if (store.authorization) {
|
||||||
@@ -355,7 +327,7 @@ export function DialogConnectProvider(props: { provider: string }) {
|
|||||||
dispatch({ type: "method.reset" })
|
dispatch({ type: "method.reset" })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
all()
|
dialog.show(() => <DialogSelectProvider />)
|
||||||
}
|
}
|
||||||
|
|
||||||
function MethodSelection() {
|
function MethodSelection() {
|
||||||
@@ -602,14 +574,6 @@ export function DialogConnectProvider(props: { provider: string }) {
|
|||||||
<div class="px-2.5 pb-10 flex flex-col gap-6">
|
<div class="px-2.5 pb-10 flex flex-col gap-6">
|
||||||
<div onKeyDown={handleKey} tabIndex={0} autofocus={store.methodIndex === undefined ? true : undefined}>
|
<div onKeyDown={handleKey} tabIndex={0} autofocus={store.methodIndex === undefined ? true : undefined}>
|
||||||
<Switch>
|
<Switch>
|
||||||
<Match when={loading()}>
|
|
||||||
<div class="text-14-regular text-text-base">
|
|
||||||
<div class="flex items-center gap-x-2">
|
|
||||||
<Spinner />
|
|
||||||
<span>{language.t("provider.connect.status.inProgress")}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Match>
|
|
||||||
<Match when={store.methodIndex === undefined}>
|
<Match when={store.methodIndex === undefined}>
|
||||||
<MethodSelection />
|
<MethodSelection />
|
||||||
</Match>
|
</Match>
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ export type FormState = {
|
|||||||
apiKey: string
|
apiKey: string
|
||||||
models: ModelRow[]
|
models: ModelRow[]
|
||||||
headers: HeaderRow[]
|
headers: HeaderRow[]
|
||||||
|
saving: boolean
|
||||||
err: {
|
err: {
|
||||||
providerID?: string
|
providerID?: string
|
||||||
name?: string
|
name?: string
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ describe("validateCustomProvider", () => {
|
|||||||
{ row: "h0", key: " X-Test ", value: " enabled ", err: {} },
|
{ row: "h0", key: " X-Test ", value: " enabled ", err: {} },
|
||||||
{ row: "h1", key: "", value: "", err: {} },
|
{ row: "h1", key: "", value: "", err: {} },
|
||||||
],
|
],
|
||||||
|
saving: false,
|
||||||
err: {},
|
err: {},
|
||||||
},
|
},
|
||||||
t,
|
t,
|
||||||
@@ -59,6 +60,7 @@ describe("validateCustomProvider", () => {
|
|||||||
{ row: "h0", key: "Authorization", value: "one", err: {} },
|
{ row: "h0", key: "Authorization", value: "one", err: {} },
|
||||||
{ row: "h1", key: "authorization", value: "two", err: {} },
|
{ row: "h1", key: "authorization", value: "two", err: {} },
|
||||||
],
|
],
|
||||||
|
saving: false,
|
||||||
err: {},
|
err: {},
|
||||||
},
|
},
|
||||||
t,
|
t,
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { useDialog } from "@opencode-ai/ui/context/dialog"
|
|||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
import { IconButton } from "@opencode-ai/ui/icon-button"
|
import { IconButton } from "@opencode-ai/ui/icon-button"
|
||||||
import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
|
import { ProviderIcon } from "@opencode-ai/ui/provider-icon"
|
||||||
import { useMutation } from "@tanstack/solid-query"
|
|
||||||
import { TextField } from "@opencode-ai/ui/text-field"
|
import { TextField } from "@opencode-ai/ui/text-field"
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
import { batch, For } from "solid-js"
|
import { batch, For } from "solid-js"
|
||||||
@@ -32,6 +31,7 @@ export function DialogCustomProvider(props: Props) {
|
|||||||
apiKey: "",
|
apiKey: "",
|
||||||
models: [modelRow()],
|
models: [modelRow()],
|
||||||
headers: [headerRow()],
|
headers: [headerRow()],
|
||||||
|
saving: false,
|
||||||
err: {},
|
err: {},
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -116,49 +116,48 @@ export function DialogCustomProvider(props: Props) {
|
|||||||
return output.result
|
return output.result
|
||||||
}
|
}
|
||||||
|
|
||||||
const saveMutation = useMutation(() => ({
|
const save = async (e: SubmitEvent) => {
|
||||||
mutationFn: async (result: NonNullable<ReturnType<typeof validate>>) => {
|
e.preventDefault()
|
||||||
const disabledProviders = globalSync.data.config.disabled_providers ?? []
|
if (form.saving) return
|
||||||
const nextDisabled = disabledProviders.filter((id) => id !== result.providerID)
|
|
||||||
|
|
||||||
if (result.key) {
|
const result = validate()
|
||||||
await globalSDK.client.auth.set({
|
if (!result) return
|
||||||
|
|
||||||
|
setForm("saving", true)
|
||||||
|
|
||||||
|
const disabledProviders = globalSync.data.config.disabled_providers ?? []
|
||||||
|
const nextDisabled = disabledProviders.filter((id) => id !== result.providerID)
|
||||||
|
|
||||||
|
const auth = result.key
|
||||||
|
? globalSDK.client.auth.set({
|
||||||
providerID: result.providerID,
|
providerID: result.providerID,
|
||||||
auth: {
|
auth: {
|
||||||
type: "api",
|
type: "api",
|
||||||
key: result.key,
|
key: result.key,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
: Promise.resolve()
|
||||||
|
|
||||||
await globalSync.updateConfig({
|
auth
|
||||||
provider: { [result.providerID]: result.config },
|
.then(() =>
|
||||||
disabled_providers: nextDisabled,
|
globalSync.updateConfig({ provider: { [result.providerID]: result.config }, disabled_providers: nextDisabled }),
|
||||||
|
)
|
||||||
|
.then(() => {
|
||||||
|
dialog.close()
|
||||||
|
showToast({
|
||||||
|
variant: "success",
|
||||||
|
icon: "circle-check",
|
||||||
|
title: language.t("provider.connect.toast.connected.title", { provider: result.name }),
|
||||||
|
description: language.t("provider.connect.toast.connected.description", { provider: result.name }),
|
||||||
|
})
|
||||||
})
|
})
|
||||||
return result
|
.catch((err: unknown) => {
|
||||||
},
|
const message = err instanceof Error ? err.message : String(err)
|
||||||
onSuccess: (result) => {
|
showToast({ title: language.t("common.requestFailed"), description: message })
|
||||||
dialog.close()
|
})
|
||||||
showToast({
|
.finally(() => {
|
||||||
variant: "success",
|
setForm("saving", false)
|
||||||
icon: "circle-check",
|
|
||||||
title: language.t("provider.connect.toast.connected.title", { provider: result.name }),
|
|
||||||
description: language.t("provider.connect.toast.connected.description", { provider: result.name }),
|
|
||||||
})
|
})
|
||||||
},
|
|
||||||
onError: (err) => {
|
|
||||||
const message = err instanceof Error ? err.message : String(err)
|
|
||||||
showToast({ title: language.t("common.requestFailed"), description: message })
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
const save = (e: SubmitEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
if (saveMutation.isPending) return
|
|
||||||
|
|
||||||
const result = validate()
|
|
||||||
if (!result) return
|
|
||||||
saveMutation.mutate(result)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -313,14 +312,8 @@ export function DialogCustomProvider(props: Props) {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button
|
<Button class="w-auto self-start" type="submit" size="large" variant="primary" disabled={form.saving}>
|
||||||
class="w-auto self-start"
|
{form.saving ? language.t("common.saving") : language.t("common.submit")}
|
||||||
type="submit"
|
|
||||||
size="large"
|
|
||||||
variant="primary"
|
|
||||||
disabled={saveMutation.isPending}
|
|
||||||
>
|
|
||||||
{saveMutation.isPending ? language.t("common.saving") : language.t("common.submit")}
|
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { Button } from "@opencode-ai/ui/button"
|
|||||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
import { TextField } from "@opencode-ai/ui/text-field"
|
import { TextField } from "@opencode-ai/ui/text-field"
|
||||||
import { useMutation } from "@tanstack/solid-query"
|
|
||||||
import { Icon } from "@opencode-ai/ui/icon"
|
import { Icon } from "@opencode-ai/ui/icon"
|
||||||
import { createMemo, For, Show } from "solid-js"
|
import { createMemo, For, Show } from "solid-js"
|
||||||
import { createStore } from "solid-js/store"
|
import { createStore } from "solid-js/store"
|
||||||
@@ -29,6 +28,7 @@ export function DialogEditProject(props: { project: LocalProject }) {
|
|||||||
color: props.project.icon?.color || "pink",
|
color: props.project.icon?.color || "pink",
|
||||||
iconUrl: props.project.icon?.override || "",
|
iconUrl: props.project.icon?.override || "",
|
||||||
startup: props.project.commands?.start ?? "",
|
startup: props.project.commands?.start ?? "",
|
||||||
|
saving: false,
|
||||||
dragOver: false,
|
dragOver: false,
|
||||||
iconHover: false,
|
iconHover: false,
|
||||||
})
|
})
|
||||||
@@ -71,37 +71,38 @@ export function DialogEditProject(props: { project: LocalProject }) {
|
|||||||
setStore("iconUrl", "")
|
setStore("iconUrl", "")
|
||||||
}
|
}
|
||||||
|
|
||||||
const saveMutation = useMutation(() => ({
|
async function handleSubmit(e: SubmitEvent) {
|
||||||
mutationFn: async () => {
|
|
||||||
const name = store.name.trim() === folderName() ? "" : store.name.trim()
|
|
||||||
const start = store.startup.trim()
|
|
||||||
|
|
||||||
if (props.project.id && props.project.id !== "global") {
|
|
||||||
await globalSDK.client.project.update({
|
|
||||||
projectID: props.project.id,
|
|
||||||
directory: props.project.worktree,
|
|
||||||
name,
|
|
||||||
icon: { color: store.color, override: store.iconUrl },
|
|
||||||
commands: { start },
|
|
||||||
})
|
|
||||||
globalSync.project.icon(props.project.worktree, store.iconUrl || undefined)
|
|
||||||
dialog.close()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
globalSync.project.meta(props.project.worktree, {
|
|
||||||
name,
|
|
||||||
icon: { color: store.color, override: store.iconUrl || undefined },
|
|
||||||
commands: { start: start || undefined },
|
|
||||||
})
|
|
||||||
dialog.close()
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
function handleSubmit(e: SubmitEvent) {
|
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
if (saveMutation.isPending) return
|
|
||||||
saveMutation.mutate()
|
await Promise.resolve()
|
||||||
|
.then(async () => {
|
||||||
|
setStore("saving", true)
|
||||||
|
const name = store.name.trim() === folderName() ? "" : store.name.trim()
|
||||||
|
const start = store.startup.trim()
|
||||||
|
|
||||||
|
if (props.project.id && props.project.id !== "global") {
|
||||||
|
await globalSDK.client.project.update({
|
||||||
|
projectID: props.project.id,
|
||||||
|
directory: props.project.worktree,
|
||||||
|
name,
|
||||||
|
icon: { color: store.color, override: store.iconUrl },
|
||||||
|
commands: { start },
|
||||||
|
})
|
||||||
|
globalSync.project.icon(props.project.worktree, store.iconUrl || undefined)
|
||||||
|
dialog.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
globalSync.project.meta(props.project.worktree, {
|
||||||
|
name,
|
||||||
|
icon: { color: store.color, override: store.iconUrl || undefined },
|
||||||
|
commands: { start: start || undefined },
|
||||||
|
})
|
||||||
|
dialog.close()
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
setStore("saving", false)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -245,8 +246,8 @@ export function DialogEditProject(props: { project: LocalProject }) {
|
|||||||
<Button type="button" variant="ghost" size="large" onClick={() => dialog.close()}>
|
<Button type="button" variant="ghost" size="large" onClick={() => dialog.close()}>
|
||||||
{language.t("common.cancel")}
|
{language.t("common.cancel")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="submit" variant="primary" size="large" disabled={saveMutation.isPending}>
|
<Button type="submit" variant="primary" size="large" disabled={store.saving}>
|
||||||
{saveMutation.isPending ? language.t("common.saving") : language.t("common.save")}
|
{store.saving ? language.t("common.saving") : language.t("common.save")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
import { useMutation } from "@tanstack/solid-query"
|
import { Component, createMemo, createSignal, Show } from "solid-js"
|
||||||
import { Component, createEffect, createMemo, on, Show } from "solid-js"
|
|
||||||
import { createStore } from "solid-js/store"
|
|
||||||
import { useSync } from "@/context/sync"
|
import { useSync } from "@/context/sync"
|
||||||
import { useSDK } from "@/context/sdk"
|
import { useSDK } from "@/context/sdk"
|
||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
import { List } from "@opencode-ai/ui/list"
|
import { List } from "@opencode-ai/ui/list"
|
||||||
import { Switch } from "@opencode-ai/ui/switch"
|
import { Switch } from "@opencode-ai/ui/switch"
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
|
|
||||||
const statusLabels = {
|
const statusLabels = {
|
||||||
@@ -20,48 +17,7 @@ export const DialogSelectMcp: Component = () => {
|
|||||||
const sync = useSync()
|
const sync = useSync()
|
||||||
const sdk = useSDK()
|
const sdk = useSDK()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const [state, setState] = createStore({
|
const [loading, setLoading] = createSignal<string | null>(null)
|
||||||
done: false,
|
|
||||||
loading: false,
|
|
||||||
})
|
|
||||||
|
|
||||||
createEffect(
|
|
||||||
on(
|
|
||||||
() => sync.data.mcp_ready,
|
|
||||||
(ready, prev) => {
|
|
||||||
if (!ready && prev) setState("done", false)
|
|
||||||
},
|
|
||||||
{ defer: true },
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
if (state.done || state.loading) return
|
|
||||||
if (sync.data.mcp_ready) {
|
|
||||||
setState("done", true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setState("loading", true)
|
|
||||||
void sdk.client.mcp
|
|
||||||
.status()
|
|
||||||
.then((result) => {
|
|
||||||
sync.set("mcp", result.data ?? {})
|
|
||||||
sync.set("mcp_ready", true)
|
|
||||||
setState("done", true)
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
setState("done", true)
|
|
||||||
showToast({
|
|
||||||
variant: "error",
|
|
||||||
title: language.t("common.requestFailed"),
|
|
||||||
description: err instanceof Error ? err.message : String(err),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
setState("loading", false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
const items = createMemo(() =>
|
const items = createMemo(() =>
|
||||||
Object.entries(sync.data.mcp ?? {})
|
Object.entries(sync.data.mcp ?? {})
|
||||||
@@ -69,8 +25,10 @@ export const DialogSelectMcp: Component = () => {
|
|||||||
.sort((a, b) => a.name.localeCompare(b.name)),
|
.sort((a, b) => a.name.localeCompare(b.name)),
|
||||||
)
|
)
|
||||||
|
|
||||||
const toggle = useMutation(() => ({
|
const toggle = async (name: string) => {
|
||||||
mutationFn: async (name: string) => {
|
if (loading()) return
|
||||||
|
setLoading(name)
|
||||||
|
try {
|
||||||
const status = sync.data.mcp[name]
|
const status = sync.data.mcp[name]
|
||||||
if (status?.status === "connected") {
|
if (status?.status === "connected") {
|
||||||
await sdk.client.mcp.disconnect({ name })
|
await sdk.client.mcp.disconnect({ name })
|
||||||
@@ -80,8 +38,10 @@ export const DialogSelectMcp: Component = () => {
|
|||||||
|
|
||||||
const result = await sdk.client.mcp.status()
|
const result = await sdk.client.mcp.status()
|
||||||
if (result.data) sync.set("mcp", result.data)
|
if (result.data) sync.set("mcp", result.data)
|
||||||
},
|
} finally {
|
||||||
}))
|
setLoading(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const enabledCount = createMemo(() => items().filter((i) => i.status === "connected").length)
|
const enabledCount = createMemo(() => items().filter((i) => i.status === "connected").length)
|
||||||
const totalCount = createMemo(() => items().length)
|
const totalCount = createMemo(() => items().length)
|
||||||
@@ -99,8 +59,7 @@ export const DialogSelectMcp: Component = () => {
|
|||||||
filterKeys={["name", "status"]}
|
filterKeys={["name", "status"]}
|
||||||
sortBy={(a, b) => a.name.localeCompare(b.name)}
|
sortBy={(a, b) => a.name.localeCompare(b.name)}
|
||||||
onSelect={(x) => {
|
onSelect={(x) => {
|
||||||
if (!x || toggle.isPending) return
|
if (x) toggle(x.name)
|
||||||
toggle.mutate(x.name)
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{(i) => {
|
{(i) => {
|
||||||
@@ -124,7 +83,7 @@ export const DialogSelectMcp: Component = () => {
|
|||||||
<Show when={statusLabel()}>
|
<Show when={statusLabel()}>
|
||||||
<span class="text-11-regular text-text-weaker">{statusLabel()}</span>
|
<span class="text-11-regular text-text-weaker">{statusLabel()}</span>
|
||||||
</Show>
|
</Show>
|
||||||
<Show when={toggle.isPending && toggle.variables === i.name}>
|
<Show when={loading() === i.name}>
|
||||||
<span class="text-11-regular text-text-weak">{language.t("common.loading.ellipsis")}</span>
|
<span class="text-11-regular text-text-weak">{language.t("common.loading.ellipsis")}</span>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
@@ -133,14 +92,7 @@ export const DialogSelectMcp: Component = () => {
|
|||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
<div onClick={(e) => e.stopPropagation()}>
|
<div onClick={(e) => e.stopPropagation()}>
|
||||||
<Switch
|
<Switch checked={enabled()} disabled={loading() === i.name} onChange={() => toggle(i.name)} />
|
||||||
checked={enabled()}
|
|
||||||
disabled={toggle.isPending && toggle.variables === i.name}
|
|
||||||
onChange={() => {
|
|
||||||
if (toggle.isPending) return
|
|
||||||
toggle.mutate(i.name)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import { Tooltip } from "@opencode-ai/ui/tooltip"
|
|||||||
import { type Component, Show } from "solid-js"
|
import { type Component, Show } from "solid-js"
|
||||||
import { useLocal } from "@/context/local"
|
import { useLocal } from "@/context/local"
|
||||||
import { popularProviders, useProviders } from "@/hooks/use-providers"
|
import { popularProviders, useProviders } from "@/hooks/use-providers"
|
||||||
|
import { DialogConnectProvider } from "./dialog-connect-provider"
|
||||||
|
import { DialogSelectProvider } from "./dialog-select-provider"
|
||||||
import { ModelTooltip } from "./model-tooltip"
|
import { ModelTooltip } from "./model-tooltip"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
|
|
||||||
@@ -19,18 +21,6 @@ export const DialogSelectModelUnpaid: Component<{ model?: ModelState }> = (props
|
|||||||
const providers = useProviders()
|
const providers = useProviders()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
|
|
||||||
const connect = (provider: string) => {
|
|
||||||
void import("./dialog-connect-provider").then((x) => {
|
|
||||||
dialog.show(() => <x.DialogConnectProvider provider={provider} />)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const all = () => {
|
|
||||||
void import("./dialog-select-provider").then((x) => {
|
|
||||||
dialog.show(() => <x.DialogSelectProvider />)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
let listRef: ListRef | undefined
|
let listRef: ListRef | undefined
|
||||||
const handleKeyDown = (e: KeyboardEvent) => {
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
if (e.key === "Escape") return
|
if (e.key === "Escape") return
|
||||||
@@ -101,7 +91,7 @@ export const DialogSelectModelUnpaid: Component<{ model?: ModelState }> = (props
|
|||||||
}}
|
}}
|
||||||
onSelect={(x) => {
|
onSelect={(x) => {
|
||||||
if (!x) return
|
if (!x) return
|
||||||
connect(x.id)
|
dialog.show(() => <DialogConnectProvider provider={x.id} />)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{(i) => (
|
{(i) => (
|
||||||
@@ -132,7 +122,9 @@ export const DialogSelectModelUnpaid: Component<{ model?: ModelState }> = (props
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
class="w-full justify-start px-[11px] py-3.5 gap-4.5 text-14-medium"
|
class="w-full justify-start px-[11px] py-3.5 gap-4.5 text-14-medium"
|
||||||
icon="dot-grid"
|
icon="dot-grid"
|
||||||
onClick={all}
|
onClick={() => {
|
||||||
|
dialog.show(() => <DialogSelectProvider />)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{language.t("dialog.provider.viewAll")}
|
{language.t("dialog.provider.viewAll")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import { Tag } from "@opencode-ai/ui/tag"
|
|||||||
import { Dialog } from "@opencode-ai/ui/dialog"
|
import { Dialog } from "@opencode-ai/ui/dialog"
|
||||||
import { List } from "@opencode-ai/ui/list"
|
import { List } from "@opencode-ai/ui/list"
|
||||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||||
|
import { DialogSelectProvider } from "./dialog-select-provider"
|
||||||
|
import { DialogManageModels } from "./dialog-manage-models"
|
||||||
import { ModelTooltip } from "./model-tooltip"
|
import { ModelTooltip } from "./model-tooltip"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
|
|
||||||
@@ -105,16 +107,12 @@ export function ModelSelectorPopover(props: {
|
|||||||
|
|
||||||
const handleManage = () => {
|
const handleManage = () => {
|
||||||
setStore("open", false)
|
setStore("open", false)
|
||||||
void import("./dialog-manage-models").then((x) => {
|
dialog.show(() => <DialogManageModels />)
|
||||||
dialog.show(() => <x.DialogManageModels />)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleConnectProvider = () => {
|
const handleConnectProvider = () => {
|
||||||
setStore("open", false)
|
setStore("open", false)
|
||||||
void import("./dialog-select-provider").then((x) => {
|
dialog.show(() => <DialogSelectProvider />)
|
||||||
dialog.show(() => <x.DialogSelectProvider />)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
|
|
||||||
@@ -195,29 +193,26 @@ export const DialogSelectModel: Component<{ provider?: string; model?: ModelStat
|
|||||||
const dialog = useDialog()
|
const dialog = useDialog()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
|
|
||||||
const provider = () => {
|
|
||||||
void import("./dialog-select-provider").then((x) => {
|
|
||||||
dialog.show(() => <x.DialogSelectProvider />)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const manage = () => {
|
|
||||||
void import("./dialog-manage-models").then((x) => {
|
|
||||||
dialog.show(() => <x.DialogManageModels />)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog
|
<Dialog
|
||||||
title={language.t("dialog.model.select.title")}
|
title={language.t("dialog.model.select.title")}
|
||||||
action={
|
action={
|
||||||
<Button class="h-7 -my-1 text-14-medium" icon="plus-small" tabIndex={-1} onClick={provider}>
|
<Button
|
||||||
|
class="h-7 -my-1 text-14-medium"
|
||||||
|
icon="plus-small"
|
||||||
|
tabIndex={-1}
|
||||||
|
onClick={() => dialog.show(() => <DialogSelectProvider />)}
|
||||||
|
>
|
||||||
{language.t("command.provider.connect")}
|
{language.t("command.provider.connect")}
|
||||||
</Button>
|
</Button>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<ModelList provider={props.provider} model={props.model} onSelect={() => dialog.close()} />
|
<ModelList provider={props.provider} model={props.model} onSelect={() => dialog.close()} />
|
||||||
<Button variant="ghost" class="ml-3 mt-5 mb-6 text-text-base self-start" onClick={manage}>
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
class="ml-3 mt-5 mb-6 text-text-base self-start"
|
||||||
|
onClick={() => dialog.show(() => <DialogManageModels />)}
|
||||||
|
>
|
||||||
{language.t("dialog.model.manage")}
|
{language.t("dialog.model.manage")}
|
||||||
</Button>
|
</Button>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import { Icon } from "@opencode-ai/ui/icon"
|
|||||||
import { IconButton } from "@opencode-ai/ui/icon-button"
|
import { IconButton } from "@opencode-ai/ui/icon-button"
|
||||||
import { List } from "@opencode-ai/ui/list"
|
import { List } from "@opencode-ai/ui/list"
|
||||||
import { TextField } from "@opencode-ai/ui/text-field"
|
import { TextField } from "@opencode-ai/ui/text-field"
|
||||||
import { useMutation } from "@tanstack/solid-query"
|
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
import { useNavigate } from "@solidjs/router"
|
import { useNavigate } from "@solidjs/router"
|
||||||
import { createEffect, createMemo, createResource, onCleanup, Show } from "solid-js"
|
import { createEffect, createMemo, createResource, onCleanup, Show } from "solid-js"
|
||||||
@@ -187,6 +186,7 @@ export function DialogSelectServer() {
|
|||||||
name: "",
|
name: "",
|
||||||
username: DEFAULT_USERNAME,
|
username: DEFAULT_USERNAME,
|
||||||
password: "",
|
password: "",
|
||||||
|
adding: false,
|
||||||
error: "",
|
error: "",
|
||||||
showForm: false,
|
showForm: false,
|
||||||
status: undefined as boolean | undefined,
|
status: undefined as boolean | undefined,
|
||||||
@@ -198,6 +198,7 @@ export function DialogSelectServer() {
|
|||||||
username: "",
|
username: "",
|
||||||
password: "",
|
password: "",
|
||||||
error: "",
|
error: "",
|
||||||
|
busy: false,
|
||||||
status: undefined as boolean | undefined,
|
status: undefined as boolean | undefined,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -208,6 +209,7 @@ export function DialogSelectServer() {
|
|||||||
name: "",
|
name: "",
|
||||||
username: DEFAULT_USERNAME,
|
username: DEFAULT_USERNAME,
|
||||||
password: "",
|
password: "",
|
||||||
|
adding: false,
|
||||||
error: "",
|
error: "",
|
||||||
showForm: false,
|
showForm: false,
|
||||||
status: undefined,
|
status: undefined,
|
||||||
@@ -222,78 +224,10 @@ export function DialogSelectServer() {
|
|||||||
password: "",
|
password: "",
|
||||||
error: "",
|
error: "",
|
||||||
status: undefined,
|
status: undefined,
|
||||||
|
busy: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const addMutation = useMutation(() => ({
|
|
||||||
mutationFn: async (value: string) => {
|
|
||||||
const normalized = normalizeServerUrl(value)
|
|
||||||
if (!normalized) {
|
|
||||||
resetAdd()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const conn: ServerConnection.Http = {
|
|
||||||
type: "http",
|
|
||||||
http: { url: normalized },
|
|
||||||
}
|
|
||||||
if (store.addServer.name.trim()) conn.displayName = store.addServer.name.trim()
|
|
||||||
if (store.addServer.password) conn.http.password = store.addServer.password
|
|
||||||
if (store.addServer.password && store.addServer.username) conn.http.username = store.addServer.username
|
|
||||||
const result = await checkServerHealth(conn.http)
|
|
||||||
if (!result.healthy) {
|
|
||||||
setStore("addServer", { error: language.t("dialog.server.add.error") })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
resetAdd()
|
|
||||||
await select(conn, true)
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
const editMutation = useMutation(() => ({
|
|
||||||
mutationFn: async (input: { original: ServerConnection.Any; value: string }) => {
|
|
||||||
if (input.original.type !== "http") return
|
|
||||||
const normalized = normalizeServerUrl(input.value)
|
|
||||||
if (!normalized) {
|
|
||||||
resetEdit()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const name = store.editServer.name.trim() || undefined
|
|
||||||
const username = store.editServer.username || undefined
|
|
||||||
const password = store.editServer.password || undefined
|
|
||||||
const existingName = input.original.displayName
|
|
||||||
if (
|
|
||||||
normalized === input.original.http.url &&
|
|
||||||
name === existingName &&
|
|
||||||
username === input.original.http.username &&
|
|
||||||
password === input.original.http.password
|
|
||||||
) {
|
|
||||||
resetEdit()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const conn: ServerConnection.Http = {
|
|
||||||
type: "http",
|
|
||||||
displayName: name,
|
|
||||||
http: { url: normalized, username, password },
|
|
||||||
}
|
|
||||||
const result = await checkServerHealth(conn.http)
|
|
||||||
if (!result.healthy) {
|
|
||||||
setStore("editServer", { error: language.t("dialog.server.add.error") })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (normalized === input.original.http.url) {
|
|
||||||
server.add(conn)
|
|
||||||
} else {
|
|
||||||
replaceServer(input.original, conn)
|
|
||||||
}
|
|
||||||
|
|
||||||
resetEdit()
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
|
|
||||||
const replaceServer = (original: ServerConnection.Http, next: ServerConnection.Http) => {
|
const replaceServer = (original: ServerConnection.Http, next: ServerConnection.Http) => {
|
||||||
const active = server.key
|
const active = server.key
|
||||||
const newConn = server.add(next)
|
const newConn = server.add(next)
|
||||||
@@ -362,7 +296,7 @@ export function DialogSelectServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleAddChange = (value: string) => {
|
const handleAddChange = (value: string) => {
|
||||||
if (addMutation.isPending) return
|
if (store.addServer.adding) return
|
||||||
setStore("addServer", { url: value, error: "" })
|
setStore("addServer", { url: value, error: "" })
|
||||||
void previewStatus(value, store.addServer.username, store.addServer.password, (next) =>
|
void previewStatus(value, store.addServer.username, store.addServer.password, (next) =>
|
||||||
setStore("addServer", { status: next }),
|
setStore("addServer", { status: next }),
|
||||||
@@ -370,12 +304,12 @@ export function DialogSelectServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleAddNameChange = (value: string) => {
|
const handleAddNameChange = (value: string) => {
|
||||||
if (addMutation.isPending) return
|
if (store.addServer.adding) return
|
||||||
setStore("addServer", { name: value, error: "" })
|
setStore("addServer", { name: value, error: "" })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleAddUsernameChange = (value: string) => {
|
const handleAddUsernameChange = (value: string) => {
|
||||||
if (addMutation.isPending) return
|
if (store.addServer.adding) return
|
||||||
setStore("addServer", { username: value, error: "" })
|
setStore("addServer", { username: value, error: "" })
|
||||||
void previewStatus(store.addServer.url, value, store.addServer.password, (next) =>
|
void previewStatus(store.addServer.url, value, store.addServer.password, (next) =>
|
||||||
setStore("addServer", { status: next }),
|
setStore("addServer", { status: next }),
|
||||||
@@ -383,7 +317,7 @@ export function DialogSelectServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleAddPasswordChange = (value: string) => {
|
const handleAddPasswordChange = (value: string) => {
|
||||||
if (addMutation.isPending) return
|
if (store.addServer.adding) return
|
||||||
setStore("addServer", { password: value, error: "" })
|
setStore("addServer", { password: value, error: "" })
|
||||||
void previewStatus(store.addServer.url, store.addServer.username, value, (next) =>
|
void previewStatus(store.addServer.url, store.addServer.username, value, (next) =>
|
||||||
setStore("addServer", { status: next }),
|
setStore("addServer", { status: next }),
|
||||||
@@ -391,7 +325,7 @@ export function DialogSelectServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleEditChange = (value: string) => {
|
const handleEditChange = (value: string) => {
|
||||||
if (editMutation.isPending) return
|
if (store.editServer.busy) return
|
||||||
setStore("editServer", { value, error: "" })
|
setStore("editServer", { value, error: "" })
|
||||||
void previewStatus(value, store.editServer.username, store.editServer.password, (next) =>
|
void previewStatus(value, store.editServer.username, store.editServer.password, (next) =>
|
||||||
setStore("editServer", { status: next }),
|
setStore("editServer", { status: next }),
|
||||||
@@ -399,12 +333,12 @@ export function DialogSelectServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleEditNameChange = (value: string) => {
|
const handleEditNameChange = (value: string) => {
|
||||||
if (editMutation.isPending) return
|
if (store.editServer.busy) return
|
||||||
setStore("editServer", { name: value, error: "" })
|
setStore("editServer", { name: value, error: "" })
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleEditUsernameChange = (value: string) => {
|
const handleEditUsernameChange = (value: string) => {
|
||||||
if (editMutation.isPending) return
|
if (store.editServer.busy) return
|
||||||
setStore("editServer", { username: value, error: "" })
|
setStore("editServer", { username: value, error: "" })
|
||||||
void previewStatus(store.editServer.value, value, store.editServer.password, (next) =>
|
void previewStatus(store.editServer.value, value, store.editServer.password, (next) =>
|
||||||
setStore("editServer", { status: next }),
|
setStore("editServer", { status: next }),
|
||||||
@@ -412,13 +346,85 @@ export function DialogSelectServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleEditPasswordChange = (value: string) => {
|
const handleEditPasswordChange = (value: string) => {
|
||||||
if (editMutation.isPending) return
|
if (store.editServer.busy) return
|
||||||
setStore("editServer", { password: value, error: "" })
|
setStore("editServer", { password: value, error: "" })
|
||||||
void previewStatus(store.editServer.value, store.editServer.username, value, (next) =>
|
void previewStatus(store.editServer.value, store.editServer.username, value, (next) =>
|
||||||
setStore("editServer", { status: next }),
|
setStore("editServer", { status: next }),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleAdd(value: string) {
|
||||||
|
if (store.addServer.adding) return
|
||||||
|
const normalized = normalizeServerUrl(value)
|
||||||
|
if (!normalized) {
|
||||||
|
resetAdd()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setStore("addServer", { adding: true, error: "" })
|
||||||
|
|
||||||
|
const conn: ServerConnection.Http = {
|
||||||
|
type: "http",
|
||||||
|
http: { url: normalized },
|
||||||
|
}
|
||||||
|
if (store.addServer.name.trim()) conn.displayName = store.addServer.name.trim()
|
||||||
|
if (store.addServer.password) conn.http.password = store.addServer.password
|
||||||
|
if (store.addServer.password && store.addServer.username) conn.http.username = store.addServer.username
|
||||||
|
const result = await checkServerHealth(conn.http)
|
||||||
|
setStore("addServer", { adding: false })
|
||||||
|
if (!result.healthy) {
|
||||||
|
setStore("addServer", { error: language.t("dialog.server.add.error") })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resetAdd()
|
||||||
|
await select(conn, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleEdit(original: ServerConnection.Any, value: string) {
|
||||||
|
if (store.editServer.busy || original.type !== "http") return
|
||||||
|
const normalized = normalizeServerUrl(value)
|
||||||
|
if (!normalized) {
|
||||||
|
resetEdit()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const name = store.editServer.name.trim() || undefined
|
||||||
|
const username = store.editServer.username || undefined
|
||||||
|
const password = store.editServer.password || undefined
|
||||||
|
const existingName = original.displayName
|
||||||
|
if (
|
||||||
|
normalized === original.http.url &&
|
||||||
|
name === existingName &&
|
||||||
|
username === original.http.username &&
|
||||||
|
password === original.http.password
|
||||||
|
) {
|
||||||
|
resetEdit()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setStore("editServer", { busy: true, error: "" })
|
||||||
|
|
||||||
|
const conn: ServerConnection.Http = {
|
||||||
|
type: "http",
|
||||||
|
displayName: name,
|
||||||
|
http: { url: normalized, username, password },
|
||||||
|
}
|
||||||
|
const result = await checkServerHealth(conn.http)
|
||||||
|
setStore("editServer", { busy: false })
|
||||||
|
if (!result.healthy) {
|
||||||
|
setStore("editServer", { error: language.t("dialog.server.add.error") })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (normalized === original.http.url) {
|
||||||
|
server.add(conn)
|
||||||
|
} else {
|
||||||
|
replaceServer(original, conn)
|
||||||
|
}
|
||||||
|
|
||||||
|
resetEdit()
|
||||||
|
}
|
||||||
|
|
||||||
const mode = createMemo<"list" | "add" | "edit">(() => {
|
const mode = createMemo<"list" | "add" | "edit">(() => {
|
||||||
if (store.editServer.id) return "edit"
|
if (store.editServer.id) return "edit"
|
||||||
if (store.addServer.showForm) return "add"
|
if (store.addServer.showForm) return "add"
|
||||||
@@ -458,26 +464,23 @@ export function DialogSelectServer() {
|
|||||||
password: conn.http.password ?? "",
|
password: conn.http.password ?? "",
|
||||||
error: "",
|
error: "",
|
||||||
status: store.status[ServerConnection.key(conn)]?.healthy,
|
status: store.status[ServerConnection.key(conn)]?.healthy,
|
||||||
|
busy: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const submitForm = () => {
|
const submitForm = () => {
|
||||||
if (mode() === "add") {
|
if (mode() === "add") {
|
||||||
if (addMutation.isPending) return
|
void handleAdd(store.addServer.url)
|
||||||
setStore("addServer", { error: "" })
|
|
||||||
addMutation.mutate(store.addServer.url)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const original = editing()
|
const original = editing()
|
||||||
if (!original) return
|
if (!original) return
|
||||||
if (editMutation.isPending) return
|
void handleEdit(original, store.editServer.value)
|
||||||
setStore("editServer", { error: "" })
|
|
||||||
editMutation.mutate({ original, value: store.editServer.value })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const isFormMode = createMemo(() => mode() !== "list")
|
const isFormMode = createMemo(() => mode() !== "list")
|
||||||
const isAddMode = createMemo(() => mode() === "add")
|
const isAddMode = createMemo(() => mode() === "add")
|
||||||
const formBusy = createMemo(() => (isAddMode() ? addMutation.isPending : editMutation.isPending))
|
const formBusy = createMemo(() => (isAddMode() ? store.addServer.adding : store.editServer.busy))
|
||||||
|
|
||||||
const formTitle = createMemo(() => {
|
const formTitle = createMemo(() => {
|
||||||
if (!isFormMode()) return language.t("dialog.server.title")
|
if (!isFormMode()) return language.t("dialog.server.title")
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { IconButton } from "@opencode-ai/ui/icon-button"
|
|||||||
import { Select } from "@opencode-ai/ui/select"
|
import { Select } from "@opencode-ai/ui/select"
|
||||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||||
import { ModelSelectorPopover } from "@/components/dialog-select-model"
|
import { ModelSelectorPopover } from "@/components/dialog-select-model"
|
||||||
|
import { DialogSelectModelUnpaid } from "@/components/dialog-select-model-unpaid"
|
||||||
import { useProviders } from "@/hooks/use-providers"
|
import { useProviders } from "@/hooks/use-providers"
|
||||||
import { useCommand } from "@/context/command"
|
import { useCommand } from "@/context/command"
|
||||||
import { Persist, persisted } from "@/utils/persist"
|
import { Persist, persisted } from "@/utils/persist"
|
||||||
@@ -571,7 +572,6 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
const open = recent()
|
const open = recent()
|
||||||
const seen = new Set(open)
|
const seen = new Set(open)
|
||||||
const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true }))
|
const pinned: AtOption[] = open.map((path) => ({ type: "file", path, display: path, recent: true }))
|
||||||
if (!query.trim()) return [...agents, ...pinned]
|
|
||||||
const paths = await files.searchFilesAndDirectories(query)
|
const paths = await files.searchFilesAndDirectories(query)
|
||||||
const fileOptions: AtOption[] = paths
|
const fileOptions: AtOption[] = paths
|
||||||
.filter((path) => !seen.has(path))
|
.filter((path) => !seen.has(path))
|
||||||
@@ -624,18 +624,17 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
if (!cmd) return
|
if (!cmd) return
|
||||||
promptProbe.select(cmd.id)
|
promptProbe.select(cmd.id)
|
||||||
closePopover()
|
closePopover()
|
||||||
const images = imageAttachments()
|
|
||||||
|
|
||||||
if (cmd.type === "custom") {
|
if (cmd.type === "custom") {
|
||||||
const text = `/${cmd.trigger} `
|
const text = `/${cmd.trigger} `
|
||||||
setEditorText(text)
|
setEditorText(text)
|
||||||
prompt.set([{ type: "text", content: text, start: 0, end: text.length }, ...images], text.length)
|
prompt.set([{ type: "text", content: text, start: 0, end: text.length }], text.length)
|
||||||
focusEditorEnd()
|
focusEditorEnd()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
clearEditor()
|
clearEditor()
|
||||||
prompt.set([...DEFAULT_PROMPT, ...images], 0)
|
prompt.set([{ type: "text", content: "", start: 0, end: 0 }], 0)
|
||||||
command.trigger(cmd.id, "slash")
|
command.trigger(cmd.id, "slash")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1044,7 +1043,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
const { addAttachments, removeAttachment, handlePaste } = createPromptAttachments({
|
const { addAttachment, removeAttachment, handlePaste } = createPromptAttachments({
|
||||||
editor: () => editorRef,
|
editor: () => editorRef,
|
||||||
isDialogActive: () => !!dialog.active,
|
isDialogActive: () => !!dialog.active,
|
||||||
setDraggingType: (type) => setStore("draggingType", type),
|
setDraggingType: (type) => setStore("draggingType", type),
|
||||||
@@ -1344,9 +1343,6 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
autocapitalize={store.mode === "normal" ? "sentences" : "off"}
|
autocapitalize={store.mode === "normal" ? "sentences" : "off"}
|
||||||
autocorrect={store.mode === "normal" ? "on" : "off"}
|
autocorrect={store.mode === "normal" ? "on" : "off"}
|
||||||
spellcheck={store.mode === "normal"}
|
spellcheck={store.mode === "normal"}
|
||||||
inputMode="text"
|
|
||||||
// @ts-expect-error
|
|
||||||
autocomplete="off"
|
|
||||||
onInput={handleInput}
|
onInput={handleInput}
|
||||||
onPaste={handlePaste}
|
onPaste={handlePaste}
|
||||||
onCompositionStart={handleCompositionStart}
|
onCompositionStart={handleCompositionStart}
|
||||||
@@ -1387,12 +1383,11 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
<input
|
<input
|
||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
multiple
|
|
||||||
accept={ACCEPTED_FILE_TYPES.join(",")}
|
accept={ACCEPTED_FILE_TYPES.join(",")}
|
||||||
class="hidden"
|
class="hidden"
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const list = e.currentTarget.files
|
const file = e.currentTarget.files?.[0]
|
||||||
if (list) void addAttachments(Array.from(list))
|
if (file) void addAttachment(file)
|
||||||
e.currentTarget.value = ""
|
e.currentTarget.value = ""
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -1497,15 +1492,11 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
size="normal"
|
size="normal"
|
||||||
class="min-w-0 max-w-[320px] text-13-regular text-text-base group"
|
class="min-w-0 max-w-[320px] text-13-regular text-text-base group"
|
||||||
style={control()}
|
style={control()}
|
||||||
onClick={() => {
|
onClick={() => dialog.show(() => <DialogSelectModelUnpaid model={local.model} />)}
|
||||||
void import("@/components/dialog-select-model-unpaid").then((x) => {
|
|
||||||
dialog.show(() => <x.DialogSelectModelUnpaid model={local.model} />)
|
|
||||||
})
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Show when={local.model.current()?.provider?.id}>
|
<Show when={local.model.current()?.provider?.id}>
|
||||||
<ProviderIcon
|
<ProviderIcon
|
||||||
id={local.model.current()?.provider?.id ?? ""}
|
id={local.model.current()!.provider.id}
|
||||||
class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
|
class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
|
||||||
style={{ "will-change": "opacity", transform: "translateZ(0)" }}
|
style={{ "will-change": "opacity", transform: "translateZ(0)" }}
|
||||||
/>
|
/>
|
||||||
@@ -1537,7 +1528,7 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
|
|||||||
>
|
>
|
||||||
<Show when={local.model.current()?.provider?.id}>
|
<Show when={local.model.current()?.provider?.id}>
|
||||||
<ProviderIcon
|
<ProviderIcon
|
||||||
id={local.model.current()?.provider?.id ?? ""}
|
id={local.model.current()!.provider.id}
|
||||||
class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
|
class="size-4 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity duration-150"
|
||||||
style={{ "will-change": "opacity", transform: "translateZ(0)" }}
|
style={{ "will-change": "opacity", transform: "translateZ(0)" }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -71,18 +71,6 @@ export function createPromptAttachments(input: PromptAttachmentsInput) {
|
|||||||
|
|
||||||
const addAttachment = (file: File) => add(file)
|
const addAttachment = (file: File) => add(file)
|
||||||
|
|
||||||
const addAttachments = async (files: File[], toast = true) => {
|
|
||||||
let found = false
|
|
||||||
|
|
||||||
for (const file of files) {
|
|
||||||
const ok = await add(file, false)
|
|
||||||
if (ok) found = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!found && files.length > 0 && toast) warn()
|
|
||||||
return found
|
|
||||||
}
|
|
||||||
|
|
||||||
const removeAttachment = (id: string) => {
|
const removeAttachment = (id: string) => {
|
||||||
const current = prompt.current()
|
const current = prompt.current()
|
||||||
const next = current.filter((part) => part.type !== "image" || part.id !== id)
|
const next = current.filter((part) => part.type !== "image" || part.id !== id)
|
||||||
@@ -96,14 +84,18 @@ export function createPromptAttachments(input: PromptAttachmentsInput) {
|
|||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
|
|
||||||
const files = Array.from(clipboardData.items).flatMap((item) => {
|
const items = Array.from(clipboardData.items)
|
||||||
if (item.kind !== "file") return []
|
const fileItems = items.filter((item) => item.kind === "file")
|
||||||
const file = item.getAsFile()
|
|
||||||
return file ? [file] : []
|
|
||||||
})
|
|
||||||
|
|
||||||
if (files.length > 0) {
|
if (fileItems.length > 0) {
|
||||||
await addAttachments(files)
|
let found = false
|
||||||
|
for (const item of fileItems) {
|
||||||
|
const file = item.getAsFile()
|
||||||
|
if (!file) continue
|
||||||
|
const ok = await add(file, false)
|
||||||
|
if (ok) found = true
|
||||||
|
}
|
||||||
|
if (!found) warn()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +169,12 @@ export function createPromptAttachments(input: PromptAttachmentsInput) {
|
|||||||
const dropped = event.dataTransfer?.files
|
const dropped = event.dataTransfer?.files
|
||||||
if (!dropped) return
|
if (!dropped) return
|
||||||
|
|
||||||
await addAttachments(Array.from(dropped))
|
let found = false
|
||||||
|
for (const file of Array.from(dropped)) {
|
||||||
|
const ok = await add(file, false)
|
||||||
|
if (ok) found = true
|
||||||
|
}
|
||||||
|
if (!found && dropped.length > 0) warn()
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
@@ -194,7 +191,6 @@ export function createPromptAttachments(input: PromptAttachmentsInput) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
addAttachment,
|
addAttachment,
|
||||||
addAttachments,
|
|
||||||
removeAttachment,
|
removeAttachment,
|
||||||
handlePaste,
|
handlePaste,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,32 +49,6 @@ describe("buildRequestParts", () => {
|
|||||||
expect(result.optimisticParts.every((part) => part.sessionID === "ses_1" && part.messageID === "msg_1")).toBe(true)
|
expect(result.optimisticParts.every((part) => part.sessionID === "ses_1" && part.messageID === "msg_1")).toBe(true)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("keeps multiple uploaded attachments in order", () => {
|
|
||||||
const result = buildRequestParts({
|
|
||||||
prompt: [{ type: "text", content: "check these", start: 0, end: 11 }],
|
|
||||||
context: [],
|
|
||||||
images: [
|
|
||||||
{ type: "image", id: "img_1", filename: "a.png", mime: "image/png", dataUrl: "data:image/png;base64,AAA" },
|
|
||||||
{
|
|
||||||
type: "image",
|
|
||||||
id: "img_2",
|
|
||||||
filename: "b.pdf",
|
|
||||||
mime: "application/pdf",
|
|
||||||
dataUrl: "data:application/pdf;base64,BBB",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
text: "check these",
|
|
||||||
messageID: "msg_multi",
|
|
||||||
sessionID: "ses_multi",
|
|
||||||
sessionDirectory: "/repo",
|
|
||||||
})
|
|
||||||
|
|
||||||
const files = result.requestParts.filter((part) => part.type === "file" && part.url.startsWith("data:"))
|
|
||||||
|
|
||||||
expect(files).toHaveLength(2)
|
|
||||||
expect(files.map((part) => (part.type === "file" ? part.filename : ""))).toEqual(["a.png", "b.pdf"])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("deduplicates context files when prompt already includes same path", () => {
|
test("deduplicates context files when prompt already includes same path", () => {
|
||||||
const prompt: Prompt = [{ type: "file", path: "src/foo.ts", content: "@src/foo.ts", start: 0, end: 11 }]
|
const prompt: Prompt = [{ type: "file", path: "src/foo.ts", content: "@src/foo.ts", start: 0, end: 11 }]
|
||||||
|
|
||||||
@@ -100,30 +74,6 @@ describe("buildRequestParts", () => {
|
|||||||
expect(synthetic).toHaveLength(1)
|
expect(synthetic).toHaveLength(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("adds file parts for @mentions inside comment text", () => {
|
|
||||||
const result = buildRequestParts({
|
|
||||||
prompt: [{ type: "text", content: "look", start: 0, end: 4 }],
|
|
||||||
context: [
|
|
||||||
{
|
|
||||||
key: "ctx:comment-mention",
|
|
||||||
type: "file",
|
|
||||||
path: "src/review.ts",
|
|
||||||
comment: "Compare with @src/shared.ts and @src/review.ts.",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
images: [],
|
|
||||||
text: "look",
|
|
||||||
messageID: "msg_comment_mentions",
|
|
||||||
sessionID: "ses_comment_mentions",
|
|
||||||
sessionDirectory: "/repo",
|
|
||||||
})
|
|
||||||
|
|
||||||
const files = result.requestParts.filter((part) => part.type === "file")
|
|
||||||
expect(files).toHaveLength(2)
|
|
||||||
expect(files.some((part) => part.type === "file" && part.url === "file:///repo/src/review.ts")).toBe(true)
|
|
||||||
expect(files.some((part) => part.type === "file" && part.url === "file:///repo/src/shared.ts")).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("handles Windows paths correctly (simulated on macOS)", () => {
|
test("handles Windows paths correctly (simulated on macOS)", () => {
|
||||||
const prompt: Prompt = [{ type: "file", path: "src\\foo.ts", content: "@src\\foo.ts", start: 0, end: 11 }]
|
const prompt: Prompt = [{ type: "file", path: "src\\foo.ts", content: "@src\\foo.ts", start: 0, end: 11 }]
|
||||||
|
|
||||||
|
|||||||
@@ -39,16 +39,6 @@ const absolute = (directory: string, path: string) => {
|
|||||||
const fileQuery = (selection: FileSelection | undefined) =>
|
const fileQuery = (selection: FileSelection | undefined) =>
|
||||||
selection ? `?start=${selection.startLine}&end=${selection.endLine}` : ""
|
selection ? `?start=${selection.startLine}&end=${selection.endLine}` : ""
|
||||||
|
|
||||||
const mention = /(^|[\s([{"'])@(\S+)/g
|
|
||||||
|
|
||||||
const parseCommentMentions = (comment: string) => {
|
|
||||||
return Array.from(comment.matchAll(mention)).flatMap((match) => {
|
|
||||||
const path = (match[2] ?? "").replace(/[.,!?;:)}\]"']+$/, "")
|
|
||||||
if (!path) return []
|
|
||||||
return [path]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const isFileAttachment = (part: Prompt[number]): part is FileAttachmentPart => part.type === "file"
|
const isFileAttachment = (part: Prompt[number]): part is FileAttachmentPart => part.type === "file"
|
||||||
const isAgentAttachment = (part: Prompt[number]): part is AgentPart => part.type === "agent"
|
const isAgentAttachment = (part: Prompt[number]): part is AgentPart => part.type === "agent"
|
||||||
|
|
||||||
@@ -148,21 +138,6 @@ export function buildRequestParts(input: BuildRequestPartsInput) {
|
|||||||
|
|
||||||
if (!comment) return [filePart]
|
if (!comment) return [filePart]
|
||||||
|
|
||||||
const mentions = parseCommentMentions(comment).flatMap((path) => {
|
|
||||||
const url = `file://${encodeFilePath(absolute(input.sessionDirectory, path))}`
|
|
||||||
if (used.has(url)) return []
|
|
||||||
used.add(url)
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
id: Identifier.ascending("part"),
|
|
||||||
type: "file",
|
|
||||||
mime: "text/plain",
|
|
||||||
url,
|
|
||||||
filename: getFilename(path),
|
|
||||||
} satisfies PromptRequestPart,
|
|
||||||
]
|
|
||||||
})
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
id: Identifier.ascending("part"),
|
id: Identifier.ascending("part"),
|
||||||
@@ -178,7 +153,6 @@ export function buildRequestParts(input: BuildRequestPartsInput) {
|
|||||||
}),
|
}),
|
||||||
} satisfies PromptRequestPart,
|
} satisfies PromptRequestPart,
|
||||||
filePart,
|
filePart,
|
||||||
...mentions,
|
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
import { ACCEPTED_FILE_TYPES, ACCEPTED_IMAGE_TYPES } from "@/constants/file-picker"
|
export const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"]
|
||||||
|
|
||||||
export { ACCEPTED_FILE_TYPES }
|
|
||||||
|
|
||||||
const IMAGE_MIMES = new Set(ACCEPTED_IMAGE_TYPES)
|
const IMAGE_MIMES = new Set(ACCEPTED_IMAGE_TYPES)
|
||||||
const IMAGE_EXTS = new Map([
|
const IMAGE_EXTS = new Map([
|
||||||
@@ -20,6 +18,61 @@ const TEXT_MIMES = new Set([
|
|||||||
"application/yaml",
|
"application/yaml",
|
||||||
])
|
])
|
||||||
|
|
||||||
|
export const ACCEPTED_FILE_TYPES = [
|
||||||
|
...ACCEPTED_IMAGE_TYPES,
|
||||||
|
"application/pdf",
|
||||||
|
"text/*",
|
||||||
|
"application/json",
|
||||||
|
"application/ld+json",
|
||||||
|
"application/toml",
|
||||||
|
"application/x-toml",
|
||||||
|
"application/x-yaml",
|
||||||
|
"application/xml",
|
||||||
|
"application/yaml",
|
||||||
|
".c",
|
||||||
|
".cc",
|
||||||
|
".cjs",
|
||||||
|
".conf",
|
||||||
|
".cpp",
|
||||||
|
".css",
|
||||||
|
".csv",
|
||||||
|
".cts",
|
||||||
|
".env",
|
||||||
|
".go",
|
||||||
|
".gql",
|
||||||
|
".graphql",
|
||||||
|
".h",
|
||||||
|
".hh",
|
||||||
|
".hpp",
|
||||||
|
".htm",
|
||||||
|
".html",
|
||||||
|
".ini",
|
||||||
|
".java",
|
||||||
|
".js",
|
||||||
|
".json",
|
||||||
|
".jsx",
|
||||||
|
".log",
|
||||||
|
".md",
|
||||||
|
".mdx",
|
||||||
|
".mjs",
|
||||||
|
".mts",
|
||||||
|
".py",
|
||||||
|
".rb",
|
||||||
|
".rs",
|
||||||
|
".sass",
|
||||||
|
".scss",
|
||||||
|
".sh",
|
||||||
|
".sql",
|
||||||
|
".toml",
|
||||||
|
".ts",
|
||||||
|
".tsx",
|
||||||
|
".txt",
|
||||||
|
".xml",
|
||||||
|
".yaml",
|
||||||
|
".yml",
|
||||||
|
".zsh",
|
||||||
|
]
|
||||||
|
|
||||||
const SAMPLE = 4096
|
const SAMPLE = 4096
|
||||||
|
|
||||||
function kind(type: string) {
|
function kind(type: string) {
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ describe("prompt-input history", () => {
|
|||||||
test("canNavigateHistoryAtCursor only allows prompt boundaries", () => {
|
test("canNavigateHistoryAtCursor only allows prompt boundaries", () => {
|
||||||
const value = "a\nb\nc"
|
const value = "a\nb\nc"
|
||||||
|
|
||||||
expect(canNavigateHistoryAtCursor("up", value, 0)).toBe(false)
|
expect(canNavigateHistoryAtCursor("up", value, 0)).toBe(true)
|
||||||
expect(canNavigateHistoryAtCursor("down", value, 0)).toBe(false)
|
expect(canNavigateHistoryAtCursor("down", value, 0)).toBe(false)
|
||||||
|
|
||||||
expect(canNavigateHistoryAtCursor("up", value, 2)).toBe(false)
|
expect(canNavigateHistoryAtCursor("up", value, 2)).toBe(false)
|
||||||
@@ -135,14 +135,11 @@ describe("prompt-input history", () => {
|
|||||||
expect(canNavigateHistoryAtCursor("up", value, 5)).toBe(false)
|
expect(canNavigateHistoryAtCursor("up", value, 5)).toBe(false)
|
||||||
expect(canNavigateHistoryAtCursor("down", value, 5)).toBe(true)
|
expect(canNavigateHistoryAtCursor("down", value, 5)).toBe(true)
|
||||||
|
|
||||||
expect(canNavigateHistoryAtCursor("up", "abc", 0)).toBe(false)
|
expect(canNavigateHistoryAtCursor("up", "abc", 0)).toBe(true)
|
||||||
expect(canNavigateHistoryAtCursor("down", "abc", 3)).toBe(true)
|
expect(canNavigateHistoryAtCursor("down", "abc", 3)).toBe(true)
|
||||||
expect(canNavigateHistoryAtCursor("up", "abc", 1)).toBe(false)
|
expect(canNavigateHistoryAtCursor("up", "abc", 1)).toBe(false)
|
||||||
expect(canNavigateHistoryAtCursor("down", "abc", 1)).toBe(false)
|
expect(canNavigateHistoryAtCursor("down", "abc", 1)).toBe(false)
|
||||||
|
|
||||||
expect(canNavigateHistoryAtCursor("up", "", 0)).toBe(true)
|
|
||||||
expect(canNavigateHistoryAtCursor("down", "", 0)).toBe(true)
|
|
||||||
|
|
||||||
expect(canNavigateHistoryAtCursor("up", "abc", 0, true)).toBe(true)
|
expect(canNavigateHistoryAtCursor("up", "abc", 0, true)).toBe(true)
|
||||||
expect(canNavigateHistoryAtCursor("up", "abc", 3, true)).toBe(true)
|
expect(canNavigateHistoryAtCursor("up", "abc", 3, true)).toBe(true)
|
||||||
expect(canNavigateHistoryAtCursor("down", "abc", 0, true)).toBe(true)
|
expect(canNavigateHistoryAtCursor("down", "abc", 0, true)).toBe(true)
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export function canNavigateHistoryAtCursor(direction: "up" | "down", text: strin
|
|||||||
const atStart = position === 0
|
const atStart = position === 0
|
||||||
const atEnd = position === text.length
|
const atEnd = position === text.length
|
||||||
if (inHistory) return atStart || atEnd
|
if (inHistory) return atStart || atEnd
|
||||||
if (direction === "up") return position === 0 && text.length === 0
|
if (direction === "up") return position === 0
|
||||||
return position === text.length
|
return position === text.length
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { useFile } from "@/context/file"
|
|||||||
import { useLayout } from "@/context/layout"
|
import { useLayout } from "@/context/layout"
|
||||||
import { useSync } from "@/context/sync"
|
import { useSync } from "@/context/sync"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { useProviders } from "@/hooks/use-providers"
|
|
||||||
import { getSessionContextMetrics } from "@/components/session/session-context-metrics"
|
import { getSessionContextMetrics } from "@/components/session/session-context-metrics"
|
||||||
import { useSessionLayout } from "@/pages/session/session-layout"
|
import { useSessionLayout } from "@/pages/session/session-layout"
|
||||||
import { createSessionTabs } from "@/pages/session/helpers"
|
import { createSessionTabs } from "@/pages/session/helpers"
|
||||||
@@ -33,7 +32,6 @@ export function SessionContextUsage(props: SessionContextUsageProps) {
|
|||||||
const file = useFile()
|
const file = useFile()
|
||||||
const layout = useLayout()
|
const layout = useLayout()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const providers = useProviders()
|
|
||||||
const { params, tabs, view } = useSessionLayout()
|
const { params, tabs, view } = useSessionLayout()
|
||||||
|
|
||||||
const variant = createMemo(() => props.variant ?? "button")
|
const variant = createMemo(() => props.variant ?? "button")
|
||||||
@@ -52,7 +50,7 @@ export function SessionContextUsage(props: SessionContextUsageProps) {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const metrics = createMemo(() => getSessionContextMetrics(messages(), providers.all()))
|
const metrics = createMemo(() => getSessionContextMetrics(messages(), sync.data.provider.all))
|
||||||
const context = createMemo(() => metrics().context)
|
const context = createMemo(() => metrics().context)
|
||||||
const cost = createMemo(() => {
|
const cost = createMemo(() => {
|
||||||
return usd().format(metrics().totalCost)
|
return usd().format(metrics().totalCost)
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import { Markdown } from "@opencode-ai/ui/markdown"
|
|||||||
import { ScrollView } from "@opencode-ai/ui/scroll-view"
|
import { ScrollView } from "@opencode-ai/ui/scroll-view"
|
||||||
import type { Message, Part, UserMessage } from "@opencode-ai/sdk/v2/client"
|
import type { Message, Part, UserMessage } from "@opencode-ai/sdk/v2/client"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { useProviders } from "@/hooks/use-providers"
|
|
||||||
import { useSessionLayout } from "@/pages/session/session-layout"
|
import { useSessionLayout } from "@/pages/session/session-layout"
|
||||||
import { getSessionContextMetrics } from "./session-context-metrics"
|
import { getSessionContextMetrics } from "./session-context-metrics"
|
||||||
import { estimateSessionContextBreakdown, type SessionContextBreakdownKey } from "./session-context-breakdown"
|
import { estimateSessionContextBreakdown, type SessionContextBreakdownKey } from "./session-context-breakdown"
|
||||||
@@ -93,7 +92,6 @@ const emptyUserMessages: UserMessage[] = []
|
|||||||
export function SessionContextTab() {
|
export function SessionContextTab() {
|
||||||
const sync = useSync()
|
const sync = useSync()
|
||||||
const language = useLanguage()
|
const language = useLanguage()
|
||||||
const providers = useProviders()
|
|
||||||
const { params, view } = useSessionLayout()
|
const { params, view } = useSessionLayout()
|
||||||
|
|
||||||
const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined))
|
const info = createMemo(() => (params.id ? sync.session.get(params.id) : undefined))
|
||||||
@@ -132,7 +130,7 @@ export function SessionContextTab() {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const metrics = createMemo(() => getSessionContextMetrics(messages(), providers.all()))
|
const metrics = createMemo(() => getSessionContextMetrics(messages(), sync.data.provider.all))
|
||||||
const ctx = createMemo(() => metrics().context)
|
const ctx = createMemo(() => metrics().context)
|
||||||
const formatter = createMemo(() => createSessionContextFormatter(language.intl()))
|
const formatter = createMemo(() => createSessionContextFormatter(language.intl()))
|
||||||
|
|
||||||
@@ -269,14 +267,14 @@ export function SessionContextTab() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ScrollView
|
<ScrollView
|
||||||
class="@container h-full"
|
class="@container h-full pb-10"
|
||||||
viewportRef={(el) => {
|
viewportRef={(el) => {
|
||||||
scroll = el
|
scroll = el
|
||||||
restoreScroll()
|
restoreScroll()
|
||||||
}}
|
}}
|
||||||
onScroll={handleScroll}
|
onScroll={handleScroll}
|
||||||
>
|
>
|
||||||
<div class="px-6 pt-4 pb-10 flex flex-col gap-10">
|
<div class="px-6 pt-4 flex flex-col gap-10">
|
||||||
<div class="grid grid-cols-1 @[32rem]:grid-cols-2 gap-4">
|
<div class="grid grid-cols-1 @[32rem]:grid-cols-2 gap-4">
|
||||||
<For each={stats}>
|
<For each={stats}>
|
||||||
{(stat) => <Stat label={language.t(stat.label as Parameters<typeof language.t>[0])} value={stat.value()} />}
|
{(stat) => <Stat label={language.t(stat.label as Parameters<typeof language.t>[0])} value={stat.value()} />}
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ export function SortableTerminalTab(props: { terminal: LocalPTY; onClose?: () =>
|
|||||||
})
|
})
|
||||||
let input: HTMLInputElement | undefined
|
let input: HTMLInputElement | undefined
|
||||||
let blurFrame: number | undefined
|
let blurFrame: number | undefined
|
||||||
let editRequested = false
|
|
||||||
|
|
||||||
const isDefaultTitle = () => {
|
const isDefaultTitle = () => {
|
||||||
const number = props.terminal.titleNumber
|
const number = props.terminal.titleNumber
|
||||||
@@ -169,14 +168,8 @@ export function SortableTerminalTab(props: { terminal: LocalPTY; onClose?: () =>
|
|||||||
left: `${store.menuPosition.x}px`,
|
left: `${store.menuPosition.x}px`,
|
||||||
top: `${store.menuPosition.y}px`,
|
top: `${store.menuPosition.y}px`,
|
||||||
}}
|
}}
|
||||||
onCloseAutoFocus={(e) => {
|
|
||||||
if (!editRequested) return
|
|
||||||
e.preventDefault()
|
|
||||||
editRequested = false
|
|
||||||
requestAnimationFrame(() => edit())
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<DropdownMenu.Item onSelect={() => (editRequested = true)}>
|
<DropdownMenu.Item onSelect={edit}>
|
||||||
<Icon name="edit" class="w-4 h-4 mr-2" />
|
<Icon name="edit" class="w-4 h-4 mr-2" />
|
||||||
{language.t("common.rename")}
|
{language.t("common.rename")}
|
||||||
</DropdownMenu.Item>
|
</DropdownMenu.Item>
|
||||||
|
|||||||
@@ -1,43 +1,27 @@
|
|||||||
import { Component, Show, createMemo, createResource, onMount, type JSX } from "solid-js"
|
import { Component, Show, createMemo, createResource, type JSX } from "solid-js"
|
||||||
import { createStore } from "solid-js/store"
|
import { createStore } from "solid-js/store"
|
||||||
import { Button } from "@opencode-ai/ui/button"
|
import { Button } from "@opencode-ai/ui/button"
|
||||||
import { Icon } from "@opencode-ai/ui/icon"
|
import { Icon } from "@opencode-ai/ui/icon"
|
||||||
import { Select } from "@opencode-ai/ui/select"
|
import { Select } from "@opencode-ai/ui/select"
|
||||||
import { Switch } from "@opencode-ai/ui/switch"
|
import { Switch } from "@opencode-ai/ui/switch"
|
||||||
import { TextField } from "@opencode-ai/ui/text-field"
|
|
||||||
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
import { Tooltip } from "@opencode-ai/ui/tooltip"
|
||||||
import { useTheme, type ColorScheme } from "@opencode-ai/ui/theme/context"
|
import { useTheme, type ColorScheme } from "@opencode-ai/ui/theme"
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { usePlatform } from "@/context/platform"
|
import { usePlatform } from "@/context/platform"
|
||||||
import {
|
import { useSettings, monoFontFamily } from "@/context/settings"
|
||||||
monoDefault,
|
import { playSound, SOUND_OPTIONS } from "@/utils/sound"
|
||||||
monoFontFamily,
|
|
||||||
monoInput,
|
|
||||||
sansDefault,
|
|
||||||
sansFontFamily,
|
|
||||||
sansInput,
|
|
||||||
useSettings,
|
|
||||||
} from "@/context/settings"
|
|
||||||
import { playSoundById, SOUND_OPTIONS } from "@/utils/sound"
|
|
||||||
import { Link } from "./link"
|
import { Link } from "./link"
|
||||||
import { SettingsList } from "./settings-list"
|
import { SettingsList } from "./settings-list"
|
||||||
|
|
||||||
let demoSoundState = {
|
let demoSoundState = {
|
||||||
cleanup: undefined as (() => void) | undefined,
|
cleanup: undefined as (() => void) | undefined,
|
||||||
timeout: undefined as NodeJS.Timeout | undefined,
|
timeout: undefined as NodeJS.Timeout | undefined,
|
||||||
run: 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
type ThemeOption = {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// To prevent audio from overlapping/playing very quickly when navigating the settings menus,
|
// To prevent audio from overlapping/playing very quickly when navigating the settings menus,
|
||||||
// delay the playback by 100ms during quick selection changes and pause existing sounds.
|
// delay the playback by 100ms during quick selection changes and pause existing sounds.
|
||||||
const stopDemoSound = () => {
|
const stopDemoSound = () => {
|
||||||
demoSoundState.run += 1
|
|
||||||
if (demoSoundState.cleanup) {
|
if (demoSoundState.cleanup) {
|
||||||
demoSoundState.cleanup()
|
demoSoundState.cleanup()
|
||||||
}
|
}
|
||||||
@@ -45,19 +29,12 @@ const stopDemoSound = () => {
|
|||||||
demoSoundState.cleanup = undefined
|
demoSoundState.cleanup = undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const playDemoSound = (id: string | undefined) => {
|
const playDemoSound = (src: string | undefined) => {
|
||||||
stopDemoSound()
|
stopDemoSound()
|
||||||
if (!id) return
|
if (!src) return
|
||||||
|
|
||||||
const run = ++demoSoundState.run
|
|
||||||
demoSoundState.timeout = setTimeout(() => {
|
demoSoundState.timeout = setTimeout(() => {
|
||||||
void playSoundById(id).then((cleanup) => {
|
demoSoundState.cleanup = playSound(src)
|
||||||
if (demoSoundState.run !== run) {
|
|
||||||
cleanup?.()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
demoSoundState.cleanup = cleanup
|
|
||||||
})
|
|
||||||
}, 100)
|
}, 100)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,10 +44,6 @@ export const SettingsGeneral: Component = () => {
|
|||||||
const platform = usePlatform()
|
const platform = usePlatform()
|
||||||
const settings = useSettings()
|
const settings = useSettings()
|
||||||
|
|
||||||
onMount(() => {
|
|
||||||
void theme.loadThemes()
|
|
||||||
})
|
|
||||||
|
|
||||||
const [store, setStore] = createStore({
|
const [store, setStore] = createStore({
|
||||||
checking: false,
|
checking: false,
|
||||||
})
|
})
|
||||||
@@ -131,7 +104,9 @@ export const SettingsGeneral: Component = () => {
|
|||||||
.finally(() => setStore("checking", false))
|
.finally(() => setStore("checking", false))
|
||||||
}
|
}
|
||||||
|
|
||||||
const themeOptions = createMemo<ThemeOption[]>(() => theme.ids().map((id) => ({ id, name: theme.name(id) })))
|
const themeOptions = createMemo(() =>
|
||||||
|
Object.entries(theme.themes()).map(([id, def]) => ({ id, name: def.name ?? id })),
|
||||||
|
)
|
||||||
|
|
||||||
const colorSchemeOptions = createMemo((): { value: ColorScheme; label: string }[] => [
|
const colorSchemeOptions = createMemo((): { value: ColorScheme; label: string }[] => [
|
||||||
{ value: "system", label: language.t("theme.scheme.system") },
|
{ value: "system", label: language.t("theme.scheme.system") },
|
||||||
@@ -151,10 +126,25 @@ export const SettingsGeneral: Component = () => {
|
|||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
|
|
||||||
const noneSound = { id: "none", label: "sound.option.none" } as const
|
const fontOptions = [
|
||||||
|
{ value: "ibm-plex-mono", label: "font.option.ibmPlexMono" },
|
||||||
|
{ value: "cascadia-code", label: "font.option.cascadiaCode" },
|
||||||
|
{ value: "fira-code", label: "font.option.firaCode" },
|
||||||
|
{ value: "hack", label: "font.option.hack" },
|
||||||
|
{ value: "inconsolata", label: "font.option.inconsolata" },
|
||||||
|
{ value: "intel-one-mono", label: "font.option.intelOneMono" },
|
||||||
|
{ value: "iosevka", label: "font.option.iosevka" },
|
||||||
|
{ value: "jetbrains-mono", label: "font.option.jetbrainsMono" },
|
||||||
|
{ value: "meslo-lgs", label: "font.option.mesloLgs" },
|
||||||
|
{ value: "roboto-mono", label: "font.option.robotoMono" },
|
||||||
|
{ value: "source-code-pro", label: "font.option.sourceCodePro" },
|
||||||
|
{ value: "ubuntu-mono", label: "font.option.ubuntuMono" },
|
||||||
|
{ value: "geist-mono", label: "font.option.geistMono" },
|
||||||
|
] as const
|
||||||
|
const fontOptionsList = [...fontOptions]
|
||||||
|
|
||||||
|
const noneSound = { id: "none", label: "sound.option.none", src: undefined } as const
|
||||||
const soundOptions = [noneSound, ...SOUND_OPTIONS]
|
const soundOptions = [noneSound, ...SOUND_OPTIONS]
|
||||||
const mono = () => monoInput(settings.appearance.font())
|
|
||||||
const sans = () => sansInput(settings.appearance.uiFont())
|
|
||||||
|
|
||||||
const soundSelectProps = (
|
const soundSelectProps = (
|
||||||
enabled: () => boolean,
|
enabled: () => boolean,
|
||||||
@@ -168,7 +158,7 @@ export const SettingsGeneral: Component = () => {
|
|||||||
label: (o: (typeof soundOptions)[number]) => language.t(o.label),
|
label: (o: (typeof soundOptions)[number]) => language.t(o.label),
|
||||||
onHighlight: (option: (typeof soundOptions)[number] | undefined) => {
|
onHighlight: (option: (typeof soundOptions)[number] | undefined) => {
|
||||||
if (!option) return
|
if (!option) return
|
||||||
playDemoSound(option.id === "none" ? undefined : option.id)
|
playDemoSound(option.src)
|
||||||
},
|
},
|
||||||
onSelect: (option: (typeof soundOptions)[number] | undefined) => {
|
onSelect: (option: (typeof soundOptions)[number] | undefined) => {
|
||||||
if (!option) return
|
if (!option) return
|
||||||
@@ -179,7 +169,7 @@ export const SettingsGeneral: Component = () => {
|
|||||||
}
|
}
|
||||||
setEnabled(true)
|
setEnabled(true)
|
||||||
set(option.id)
|
set(option.id)
|
||||||
playDemoSound(option.id)
|
playDemoSound(option.src)
|
||||||
},
|
},
|
||||||
variant: "secondary" as const,
|
variant: "secondary" as const,
|
||||||
size: "small" as const,
|
size: "small" as const,
|
||||||
@@ -321,50 +311,28 @@ export const SettingsGeneral: Component = () => {
|
|||||||
/>
|
/>
|
||||||
</SettingsRow>
|
</SettingsRow>
|
||||||
|
|
||||||
<SettingsRow
|
|
||||||
title={language.t("settings.general.row.uiFont.title")}
|
|
||||||
description={language.t("settings.general.row.uiFont.description")}
|
|
||||||
>
|
|
||||||
<div class="w-full sm:w-[220px]">
|
|
||||||
<TextField
|
|
||||||
data-action="settings-ui-font"
|
|
||||||
label={language.t("settings.general.row.uiFont.title")}
|
|
||||||
hideLabel
|
|
||||||
type="text"
|
|
||||||
value={sans()}
|
|
||||||
onChange={(value) => settings.appearance.setUIFont(value)}
|
|
||||||
placeholder={sansDefault}
|
|
||||||
spellcheck={false}
|
|
||||||
autocorrect="off"
|
|
||||||
autocomplete="off"
|
|
||||||
autocapitalize="off"
|
|
||||||
class="text-12-regular"
|
|
||||||
style={{ "font-family": sansFontFamily(settings.appearance.uiFont()) }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</SettingsRow>
|
|
||||||
|
|
||||||
<SettingsRow
|
<SettingsRow
|
||||||
title={language.t("settings.general.row.font.title")}
|
title={language.t("settings.general.row.font.title")}
|
||||||
description={language.t("settings.general.row.font.description")}
|
description={language.t("settings.general.row.font.description")}
|
||||||
>
|
>
|
||||||
<div class="w-full sm:w-[220px]">
|
<Select
|
||||||
<TextField
|
data-action="settings-font"
|
||||||
data-action="settings-code-font"
|
options={fontOptionsList}
|
||||||
label={language.t("settings.general.row.font.title")}
|
current={fontOptionsList.find((o) => o.value === settings.appearance.font())}
|
||||||
hideLabel
|
value={(o) => o.value}
|
||||||
type="text"
|
label={(o) => language.t(o.label)}
|
||||||
value={mono()}
|
onSelect={(option) => option && settings.appearance.setFont(option.value)}
|
||||||
onChange={(value) => settings.appearance.setFont(value)}
|
variant="secondary"
|
||||||
placeholder={monoDefault}
|
size="small"
|
||||||
spellcheck={false}
|
triggerVariant="settings"
|
||||||
autocorrect="off"
|
triggerStyle={{ "font-family": monoFontFamily(settings.appearance.font()), "min-width": "180px" }}
|
||||||
autocomplete="off"
|
>
|
||||||
autocapitalize="off"
|
{(option) => (
|
||||||
class="text-12-regular"
|
<span style={{ "font-family": monoFontFamily(option?.value) }}>
|
||||||
style={{ "font-family": monoFontFamily(settings.appearance.font()) }}
|
{option ? language.t(option.label) : ""}
|
||||||
/>
|
</span>
|
||||||
</div>
|
)}
|
||||||
|
</Select>
|
||||||
</SettingsRow>
|
</SettingsRow>
|
||||||
</SettingsList>
|
</SettingsList>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,445 +0,0 @@
|
|||||||
import { Button } from "@opencode-ai/ui/button"
|
|
||||||
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
|
||||||
import { Icon } from "@opencode-ai/ui/icon"
|
|
||||||
import { Switch } from "@opencode-ai/ui/switch"
|
|
||||||
import { Tabs } from "@opencode-ai/ui/tabs"
|
|
||||||
import { useMutation } from "@tanstack/solid-query"
|
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
|
||||||
import { useNavigate } from "@solidjs/router"
|
|
||||||
import { type Accessor, createEffect, createMemo, For, type JSXElement, onCleanup, Show } from "solid-js"
|
|
||||||
import { createStore, reconcile } from "solid-js/store"
|
|
||||||
import { ServerHealthIndicator, ServerRow } from "@/components/server/server-row"
|
|
||||||
import { useLanguage } from "@/context/language"
|
|
||||||
import { usePlatform } from "@/context/platform"
|
|
||||||
import { useSDK } from "@/context/sdk"
|
|
||||||
import { normalizeServerUrl, ServerConnection, useServer } from "@/context/server"
|
|
||||||
import { useSync } from "@/context/sync"
|
|
||||||
import { useCheckServerHealth, type ServerHealth } from "@/utils/server-health"
|
|
||||||
|
|
||||||
const pollMs = 10_000
|
|
||||||
|
|
||||||
const pluginEmptyMessage = (value: string, file: string): JSXElement => {
|
|
||||||
const parts = value.split(file)
|
|
||||||
if (parts.length === 1) return value
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{parts[0]}
|
|
||||||
<code class="bg-surface-raised-base px-1.5 py-0.5 rounded-sm text-text-base">{file}</code>
|
|
||||||
{parts.slice(1).join(file)}
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const listServersByHealth = (
|
|
||||||
list: ServerConnection.Any[],
|
|
||||||
active: ServerConnection.Key | undefined,
|
|
||||||
status: Record<ServerConnection.Key, ServerHealth | undefined>,
|
|
||||||
) => {
|
|
||||||
if (!list.length) return list
|
|
||||||
const order = new Map(list.map((url, index) => [url, index] as const))
|
|
||||||
const rank = (value?: ServerHealth) => {
|
|
||||||
if (value?.healthy === true) return 0
|
|
||||||
if (value?.healthy === false) return 2
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
return list.slice().sort((a, b) => {
|
|
||||||
if (ServerConnection.key(a) === active) return -1
|
|
||||||
if (ServerConnection.key(b) === active) return 1
|
|
||||||
const diff = rank(status[ServerConnection.key(a)]) - rank(status[ServerConnection.key(b)])
|
|
||||||
if (diff !== 0) return diff
|
|
||||||
return (order.get(a) ?? 0) - (order.get(b) ?? 0)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const useServerHealth = (servers: Accessor<ServerConnection.Any[]>, enabled: Accessor<boolean>) => {
|
|
||||||
const checkServerHealth = useCheckServerHealth()
|
|
||||||
const [status, setStatus] = createStore({} as Record<ServerConnection.Key, ServerHealth | undefined>)
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
if (!enabled()) {
|
|
||||||
setStatus(reconcile({}))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const list = servers()
|
|
||||||
let dead = false
|
|
||||||
|
|
||||||
const refresh = async () => {
|
|
||||||
const results: Record<string, ServerHealth> = {}
|
|
||||||
await Promise.all(
|
|
||||||
list.map(async (conn) => {
|
|
||||||
results[ServerConnection.key(conn)] = await checkServerHealth(conn.http)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
if (dead) return
|
|
||||||
setStatus(reconcile(results))
|
|
||||||
}
|
|
||||||
|
|
||||||
void refresh()
|
|
||||||
const id = setInterval(() => void refresh(), pollMs)
|
|
||||||
onCleanup(() => {
|
|
||||||
dead = true
|
|
||||||
clearInterval(id)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
return status
|
|
||||||
}
|
|
||||||
|
|
||||||
const useDefaultServerKey = (
|
|
||||||
get: (() => string | Promise<string | null | undefined> | null | undefined) | undefined,
|
|
||||||
) => {
|
|
||||||
const [state, setState] = createStore({
|
|
||||||
url: undefined as string | undefined,
|
|
||||||
tick: 0,
|
|
||||||
})
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
state.tick
|
|
||||||
let dead = false
|
|
||||||
const result = get?.()
|
|
||||||
if (!result) {
|
|
||||||
setState("url", undefined)
|
|
||||||
onCleanup(() => {
|
|
||||||
dead = true
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result instanceof Promise) {
|
|
||||||
void result.then((next) => {
|
|
||||||
if (dead) return
|
|
||||||
setState("url", next ? normalizeServerUrl(next) : undefined)
|
|
||||||
})
|
|
||||||
onCleanup(() => {
|
|
||||||
dead = true
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
setState("url", normalizeServerUrl(result))
|
|
||||||
onCleanup(() => {
|
|
||||||
dead = true
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
return {
|
|
||||||
key: () => {
|
|
||||||
const u = state.url
|
|
||||||
if (!u) return
|
|
||||||
return ServerConnection.key({ type: "http", http: { url: u } })
|
|
||||||
},
|
|
||||||
refresh: () => setState("tick", (value) => value + 1),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const useMcpToggleMutation = () => {
|
|
||||||
const sync = useSync()
|
|
||||||
const sdk = useSDK()
|
|
||||||
const language = useLanguage()
|
|
||||||
|
|
||||||
return useMutation(() => ({
|
|
||||||
mutationFn: async (name: string) => {
|
|
||||||
const status = sync.data.mcp[name]
|
|
||||||
await (status?.status === "connected" ? sdk.client.mcp.disconnect({ name }) : sdk.client.mcp.connect({ name }))
|
|
||||||
const result = await sdk.client.mcp.status()
|
|
||||||
if (result.data) sync.set("mcp", result.data)
|
|
||||||
},
|
|
||||||
onError: (err) => {
|
|
||||||
showToast({
|
|
||||||
variant: "error",
|
|
||||||
title: language.t("common.requestFailed"),
|
|
||||||
description: err instanceof Error ? err.message : String(err),
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
export function StatusPopoverBody(props: { shown: Accessor<boolean> }) {
|
|
||||||
const sync = useSync()
|
|
||||||
const server = useServer()
|
|
||||||
const platform = usePlatform()
|
|
||||||
const dialog = useDialog()
|
|
||||||
const language = useLanguage()
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const sdk = useSDK()
|
|
||||||
|
|
||||||
const [load, setLoad] = createStore({
|
|
||||||
lspDone: false,
|
|
||||||
lspLoading: false,
|
|
||||||
mcpDone: false,
|
|
||||||
mcpLoading: false,
|
|
||||||
})
|
|
||||||
|
|
||||||
const fail = (err: unknown) => {
|
|
||||||
showToast({
|
|
||||||
variant: "error",
|
|
||||||
title: language.t("common.requestFailed"),
|
|
||||||
description: err instanceof Error ? err.message : String(err),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
createEffect(() => {
|
|
||||||
if (!props.shown()) return
|
|
||||||
|
|
||||||
if (!sync.data.mcp_ready && !load.mcpDone && !load.mcpLoading) {
|
|
||||||
setLoad("mcpLoading", true)
|
|
||||||
void sdk.client.mcp
|
|
||||||
.status()
|
|
||||||
.then((result) => {
|
|
||||||
sync.set("mcp", result.data ?? {})
|
|
||||||
sync.set("mcp_ready", true)
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
setLoad("mcpDone", true)
|
|
||||||
fail(err)
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
setLoad("mcpLoading", false)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!sync.data.lsp_ready && !load.lspDone && !load.lspLoading) {
|
|
||||||
setLoad("lspLoading", true)
|
|
||||||
void sdk.client.lsp
|
|
||||||
.status()
|
|
||||||
.then((result) => {
|
|
||||||
sync.set("lsp", result.data ?? [])
|
|
||||||
sync.set("lsp_ready", true)
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
setLoad("lspDone", true)
|
|
||||||
fail(err)
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
setLoad("lspLoading", false)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
let dialogRun = 0
|
|
||||||
let dialogDead = false
|
|
||||||
onCleanup(() => {
|
|
||||||
dialogDead = true
|
|
||||||
dialogRun += 1
|
|
||||||
})
|
|
||||||
const servers = createMemo(() => {
|
|
||||||
const current = server.current
|
|
||||||
const list = server.list
|
|
||||||
if (!current) return list
|
|
||||||
if (list.every((item) => ServerConnection.key(item) !== ServerConnection.key(current))) return [current, ...list]
|
|
||||||
return [current, ...list.filter((item) => ServerConnection.key(item) !== ServerConnection.key(current))]
|
|
||||||
})
|
|
||||||
const health = useServerHealth(servers, props.shown)
|
|
||||||
const sortedServers = createMemo(() => listServersByHealth(servers(), server.key, health))
|
|
||||||
const toggleMcp = useMcpToggleMutation()
|
|
||||||
const defaultServer = useDefaultServerKey(platform.getDefaultServer)
|
|
||||||
const mcpNames = createMemo(() => Object.keys(sync.data.mcp ?? {}).sort((a, b) => a.localeCompare(b)))
|
|
||||||
const mcpStatus = (name: string) => sync.data.mcp?.[name]?.status
|
|
||||||
const mcpConnected = createMemo(() => mcpNames().filter((name) => mcpStatus(name) === "connected").length)
|
|
||||||
const lspItems = createMemo(() => sync.data.lsp ?? [])
|
|
||||||
const lspCount = createMemo(() => lspItems().length)
|
|
||||||
const plugins = createMemo(() =>
|
|
||||||
(sync.data.config.plugin ?? []).map((item) => (typeof item === "string" ? item : item[0])),
|
|
||||||
)
|
|
||||||
const pluginCount = createMemo(() => plugins().length)
|
|
||||||
const pluginEmpty = createMemo(() => pluginEmptyMessage(language.t("dialog.plugins.empty"), "opencode.json"))
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div class="flex items-center gap-1 w-[360px] rounded-xl shadow-[var(--shadow-lg-border-base)]">
|
|
||||||
<Tabs
|
|
||||||
aria-label={language.t("status.popover.ariaLabel")}
|
|
||||||
class="tabs bg-background-strong rounded-xl overflow-hidden"
|
|
||||||
data-component="tabs"
|
|
||||||
data-active="servers"
|
|
||||||
defaultValue="servers"
|
|
||||||
variant="alt"
|
|
||||||
>
|
|
||||||
<Tabs.List data-slot="tablist" class="bg-transparent border-b-0 px-4 pt-2 pb-0 gap-4 h-10">
|
|
||||||
<Tabs.Trigger value="servers" data-slot="tab" class="text-12-regular">
|
|
||||||
{sortedServers().length > 0 ? `${sortedServers().length} ` : ""}
|
|
||||||
{language.t("status.popover.tab.servers")}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
<Tabs.Trigger value="mcp" data-slot="tab" class="text-12-regular">
|
|
||||||
{mcpConnected() > 0 ? `${mcpConnected()} ` : ""}
|
|
||||||
{language.t("status.popover.tab.mcp")}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
<Tabs.Trigger value="lsp" data-slot="tab" class="text-12-regular">
|
|
||||||
{lspCount() > 0 ? `${lspCount()} ` : ""}
|
|
||||||
{language.t("status.popover.tab.lsp")}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
<Tabs.Trigger value="plugins" data-slot="tab" class="text-12-regular">
|
|
||||||
{pluginCount() > 0 ? `${pluginCount()} ` : ""}
|
|
||||||
{language.t("status.popover.tab.plugins")}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Content value="servers">
|
|
||||||
<div class="flex flex-col px-2 pb-2">
|
|
||||||
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
|
||||||
<For each={sortedServers()}>
|
|
||||||
{(s) => {
|
|
||||||
const key = ServerConnection.key(s)
|
|
||||||
const blocked = () => health[key]?.healthy === false
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="flex items-center gap-2 w-full h-8 pl-3 pr-1.5 py-1.5 rounded-md transition-colors text-left"
|
|
||||||
classList={{
|
|
||||||
"hover:bg-surface-raised-base-hover": !blocked(),
|
|
||||||
"cursor-not-allowed": blocked(),
|
|
||||||
}}
|
|
||||||
aria-disabled={blocked()}
|
|
||||||
onClick={() => {
|
|
||||||
if (blocked()) return
|
|
||||||
navigate("/")
|
|
||||||
queueMicrotask(() => server.setActive(key))
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ServerHealthIndicator health={health[key]} />
|
|
||||||
<ServerRow
|
|
||||||
conn={s}
|
|
||||||
dimmed={blocked()}
|
|
||||||
status={health[key]}
|
|
||||||
class="flex items-center gap-2 w-full min-w-0"
|
|
||||||
nameClass="text-14-regular text-text-base truncate"
|
|
||||||
versionClass="text-12-regular text-text-weak truncate"
|
|
||||||
badge={
|
|
||||||
<Show when={key === defaultServer.key()}>
|
|
||||||
<span class="text-11-regular text-text-base bg-surface-base px-1.5 py-0.5 rounded-md">
|
|
||||||
{language.t("common.default")}
|
|
||||||
</span>
|
|
||||||
</Show>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<div class="flex-1" />
|
|
||||||
<Show when={server.current && key === ServerConnection.key(server.current)}>
|
|
||||||
<Icon name="check" size="small" class="text-icon-weak shrink-0" />
|
|
||||||
</Show>
|
|
||||||
</ServerRow>
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
</For>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
class="mt-3 self-start h-8 px-3 py-1.5"
|
|
||||||
onClick={() => {
|
|
||||||
const run = ++dialogRun
|
|
||||||
void import("./dialog-select-server").then((x) => {
|
|
||||||
if (dialogDead || dialogRun !== run) return
|
|
||||||
dialog.show(() => <x.DialogSelectServer />, defaultServer.refresh)
|
|
||||||
})
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{language.t("status.popover.action.manageServers")}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="mcp">
|
|
||||||
<div class="flex flex-col px-2 pb-2">
|
|
||||||
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
|
||||||
<Show
|
|
||||||
when={mcpNames().length > 0}
|
|
||||||
fallback={
|
|
||||||
<div class="text-14-regular text-text-base text-center my-auto">{language.t("dialog.mcp.empty")}</div>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<For each={mcpNames()}>
|
|
||||||
{(name) => {
|
|
||||||
const status = () => mcpStatus(name)
|
|
||||||
const enabled = () => status() === "connected"
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="flex items-center gap-2 w-full h-8 pl-3 pr-2 py-1 rounded-md hover:bg-surface-raised-base-hover transition-colors text-left"
|
|
||||||
onClick={() => {
|
|
||||||
if (toggleMcp.isPending) return
|
|
||||||
toggleMcp.mutate(name)
|
|
||||||
}}
|
|
||||||
disabled={toggleMcp.isPending && toggleMcp.variables === name}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
classList={{
|
|
||||||
"size-1.5 rounded-full shrink-0": true,
|
|
||||||
"bg-icon-success-base": status() === "connected",
|
|
||||||
"bg-icon-critical-base": status() === "failed",
|
|
||||||
"bg-border-weak-base": status() === "disabled",
|
|
||||||
"bg-icon-warning-base":
|
|
||||||
status() === "needs_auth" || status() === "needs_client_registration",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span class="text-14-regular text-text-base truncate flex-1">{name}</span>
|
|
||||||
<div onClick={(event) => event.stopPropagation()}>
|
|
||||||
<Switch
|
|
||||||
checked={enabled()}
|
|
||||||
disabled={toggleMcp.isPending && toggleMcp.variables === name}
|
|
||||||
onChange={() => {
|
|
||||||
if (toggleMcp.isPending) return
|
|
||||||
toggleMcp.mutate(name)
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
}}
|
|
||||||
</For>
|
|
||||||
</Show>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="lsp">
|
|
||||||
<div class="flex flex-col px-2 pb-2">
|
|
||||||
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
|
||||||
<Show
|
|
||||||
when={lspItems().length > 0}
|
|
||||||
fallback={
|
|
||||||
<div class="text-14-regular text-text-base text-center my-auto">{language.t("dialog.lsp.empty")}</div>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<For each={lspItems()}>
|
|
||||||
{(item) => (
|
|
||||||
<div class="flex items-center gap-2 w-full px-2 py-1">
|
|
||||||
<div
|
|
||||||
classList={{
|
|
||||||
"size-1.5 rounded-full shrink-0": true,
|
|
||||||
"bg-icon-success-base": item.status === "connected",
|
|
||||||
"bg-icon-critical-base": item.status === "error",
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<span class="text-14-regular text-text-base truncate">{item.name || item.id}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</Show>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="plugins">
|
|
||||||
<div class="flex flex-col px-2 pb-2">
|
|
||||||
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
|
||||||
<Show
|
|
||||||
when={plugins().length > 0}
|
|
||||||
fallback={<div class="text-14-regular text-text-base text-center my-auto">{pluginEmpty()}</div>}
|
|
||||||
>
|
|
||||||
<For each={plugins()}>
|
|
||||||
{(plugin) => (
|
|
||||||
<div class="flex items-center gap-2 w-full px-2 py-1">
|
|
||||||
<div class="size-1.5 rounded-full shrink-0 bg-icon-success-base" />
|
|
||||||
<span class="text-14-regular text-text-base truncate">{plugin}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</Show>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Tabs.Content>
|
|
||||||
</Tabs>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,24 +1,203 @@
|
|||||||
import { Button } from "@opencode-ai/ui/button"
|
import { Button } from "@opencode-ai/ui/button"
|
||||||
|
import { useDialog } from "@opencode-ai/ui/context/dialog"
|
||||||
import { Icon } from "@opencode-ai/ui/icon"
|
import { Icon } from "@opencode-ai/ui/icon"
|
||||||
import { Popover } from "@opencode-ai/ui/popover"
|
import { Popover } from "@opencode-ai/ui/popover"
|
||||||
import { Suspense, createMemo, createSignal, lazy, Show } from "solid-js"
|
import { Switch } from "@opencode-ai/ui/switch"
|
||||||
|
import { Tabs } from "@opencode-ai/ui/tabs"
|
||||||
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
|
import { useNavigate } from "@solidjs/router"
|
||||||
|
import { type Accessor, createEffect, createMemo, createSignal, For, type JSXElement, onCleanup, Show } from "solid-js"
|
||||||
|
import { createStore, reconcile } from "solid-js/store"
|
||||||
|
import { ServerHealthIndicator, ServerRow } from "@/components/server/server-row"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { useServer } from "@/context/server"
|
import { usePlatform } from "@/context/platform"
|
||||||
|
import { useSDK } from "@/context/sdk"
|
||||||
|
import { normalizeServerUrl, ServerConnection, useServer } from "@/context/server"
|
||||||
import { useSync } from "@/context/sync"
|
import { useSync } from "@/context/sync"
|
||||||
|
import { useCheckServerHealth, type ServerHealth } from "@/utils/server-health"
|
||||||
|
import { DialogSelectServer } from "./dialog-select-server"
|
||||||
|
|
||||||
const Body = lazy(() => import("./status-popover-body").then((x) => ({ default: x.StatusPopoverBody })))
|
const pollMs = 10_000
|
||||||
|
|
||||||
|
const pluginEmptyMessage = (value: string, file: string): JSXElement => {
|
||||||
|
const parts = value.split(file)
|
||||||
|
if (parts.length === 1) return value
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{parts[0]}
|
||||||
|
<code class="bg-surface-raised-base px-1.5 py-0.5 rounded-sm text-text-base">{file}</code>
|
||||||
|
{parts.slice(1).join(file)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const listServersByHealth = (
|
||||||
|
list: ServerConnection.Any[],
|
||||||
|
active: ServerConnection.Key | undefined,
|
||||||
|
status: Record<ServerConnection.Key, ServerHealth | undefined>,
|
||||||
|
) => {
|
||||||
|
if (!list.length) return list
|
||||||
|
const order = new Map(list.map((url, index) => [url, index] as const))
|
||||||
|
const rank = (value?: ServerHealth) => {
|
||||||
|
if (value?.healthy === true) return 0
|
||||||
|
if (value?.healthy === false) return 2
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return list.slice().sort((a, b) => {
|
||||||
|
if (ServerConnection.key(a) === active) return -1
|
||||||
|
if (ServerConnection.key(b) === active) return 1
|
||||||
|
const diff = rank(status[ServerConnection.key(a)]) - rank(status[ServerConnection.key(b)])
|
||||||
|
if (diff !== 0) return diff
|
||||||
|
return (order.get(a) ?? 0) - (order.get(b) ?? 0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const useServerHealth = (servers: Accessor<ServerConnection.Any[]>) => {
|
||||||
|
const checkServerHealth = useCheckServerHealth()
|
||||||
|
const [status, setStatus] = createStore({} as Record<ServerConnection.Key, ServerHealth | undefined>)
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
const list = servers()
|
||||||
|
let dead = false
|
||||||
|
|
||||||
|
const refresh = async () => {
|
||||||
|
const results: Record<string, ServerHealth> = {}
|
||||||
|
await Promise.all(
|
||||||
|
list.map(async (conn) => {
|
||||||
|
results[ServerConnection.key(conn)] = await checkServerHealth(conn.http)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
if (dead) return
|
||||||
|
setStatus(reconcile(results))
|
||||||
|
}
|
||||||
|
|
||||||
|
void refresh()
|
||||||
|
const id = setInterval(() => void refresh(), pollMs)
|
||||||
|
onCleanup(() => {
|
||||||
|
dead = true
|
||||||
|
clearInterval(id)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
const useDefaultServerKey = (
|
||||||
|
get: (() => string | Promise<string | null | undefined> | null | undefined) | undefined,
|
||||||
|
) => {
|
||||||
|
const [state, setState] = createStore({
|
||||||
|
url: undefined as string | undefined,
|
||||||
|
tick: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
state.tick
|
||||||
|
let dead = false
|
||||||
|
const result = get?.()
|
||||||
|
if (!result) {
|
||||||
|
setState("url", undefined)
|
||||||
|
onCleanup(() => {
|
||||||
|
dead = true
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result instanceof Promise) {
|
||||||
|
void result.then((next) => {
|
||||||
|
if (dead) return
|
||||||
|
setState("url", next ? normalizeServerUrl(next) : undefined)
|
||||||
|
})
|
||||||
|
onCleanup(() => {
|
||||||
|
dead = true
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setState("url", normalizeServerUrl(result))
|
||||||
|
onCleanup(() => {
|
||||||
|
dead = true
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
key: () => {
|
||||||
|
const u = state.url
|
||||||
|
if (!u) return
|
||||||
|
return ServerConnection.key({ type: "http", http: { url: u } })
|
||||||
|
},
|
||||||
|
refresh: () => setState("tick", (value) => value + 1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const useMcpToggle = (input: {
|
||||||
|
sync: ReturnType<typeof useSync>
|
||||||
|
sdk: ReturnType<typeof useSDK>
|
||||||
|
language: ReturnType<typeof useLanguage>
|
||||||
|
}) => {
|
||||||
|
const [loading, setLoading] = createSignal<string | null>(null)
|
||||||
|
|
||||||
|
const toggle = async (name: string) => {
|
||||||
|
if (loading()) return
|
||||||
|
setLoading(name)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const status = input.sync.data.mcp[name]
|
||||||
|
await (status?.status === "connected"
|
||||||
|
? input.sdk.client.mcp.disconnect({ name })
|
||||||
|
: input.sdk.client.mcp.connect({ name }))
|
||||||
|
const result = await input.sdk.client.mcp.status()
|
||||||
|
if (result.data) input.sync.set("mcp", result.data)
|
||||||
|
} catch (err) {
|
||||||
|
showToast({
|
||||||
|
variant: "error",
|
||||||
|
title: input.language.t("common.requestFailed"),
|
||||||
|
description: err instanceof Error ? err.message : String(err),
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setLoading(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { loading, toggle }
|
||||||
|
}
|
||||||
|
|
||||||
export function StatusPopover() {
|
export function StatusPopover() {
|
||||||
const language = useLanguage()
|
|
||||||
const server = useServer()
|
|
||||||
const sync = useSync()
|
const sync = useSync()
|
||||||
|
const sdk = useSDK()
|
||||||
|
const server = useServer()
|
||||||
|
const platform = usePlatform()
|
||||||
|
const dialog = useDialog()
|
||||||
|
const language = useLanguage()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const [shown, setShown] = createSignal(false)
|
const [shown, setShown] = createSignal(false)
|
||||||
const ready = createMemo(() => server.healthy() === false || sync.data.mcp_ready)
|
const servers = createMemo(() => {
|
||||||
const healthy = createMemo(() => {
|
const current = server.current
|
||||||
|
const list = server.list
|
||||||
|
if (!current) return list
|
||||||
|
if (list.every((item) => ServerConnection.key(item) !== ServerConnection.key(current))) return [current, ...list]
|
||||||
|
return [current, ...list.filter((item) => ServerConnection.key(item) !== ServerConnection.key(current))]
|
||||||
|
})
|
||||||
|
const health = useServerHealth(servers)
|
||||||
|
const sortedServers = createMemo(() => listServersByHealth(servers(), server.key, health))
|
||||||
|
const mcp = useMcpToggle({ sync, sdk, language })
|
||||||
|
const defaultServer = useDefaultServerKey(platform.getDefaultServer)
|
||||||
|
const mcpNames = createMemo(() => Object.keys(sync.data.mcp ?? {}).sort((a, b) => a.localeCompare(b)))
|
||||||
|
const mcpStatus = (name: string) => sync.data.mcp?.[name]?.status
|
||||||
|
const mcpConnected = createMemo(() => mcpNames().filter((name) => mcpStatus(name) === "connected").length)
|
||||||
|
const lspItems = createMemo(() => sync.data.lsp ?? [])
|
||||||
|
const lspCount = createMemo(() => lspItems().length)
|
||||||
|
const plugins = createMemo(() => sync.data.config.plugin ?? [])
|
||||||
|
const pluginCount = createMemo(() => plugins().length)
|
||||||
|
const pluginEmpty = createMemo(() => pluginEmptyMessage(language.t("dialog.plugins.empty"), "opencode.json"))
|
||||||
|
const overallHealthy = createMemo(() => {
|
||||||
const serverHealthy = server.healthy() === true
|
const serverHealthy = server.healthy() === true
|
||||||
const mcp = Object.values(sync.data.mcp ?? {})
|
const anyMcpIssue = mcpNames().some((name) => {
|
||||||
const issue = mcp.some((item) => item.status !== "connected" && item.status !== "disabled")
|
const status = mcpStatus(name)
|
||||||
return serverHealthy && !issue
|
return status !== "connected" && status !== "disabled"
|
||||||
|
})
|
||||||
|
return serverHealthy && !anyMcpIssue
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -40,9 +219,9 @@ export function StatusPopover() {
|
|||||||
<div
|
<div
|
||||||
classList={{
|
classList={{
|
||||||
"absolute -top-px -right-px size-1.5 rounded-full": true,
|
"absolute -top-px -right-px size-1.5 rounded-full": true,
|
||||||
"bg-icon-success-base": ready() && healthy(),
|
"bg-icon-success-base": overallHealthy(),
|
||||||
"bg-icon-critical-base": server.healthy() === false || (ready() && !healthy()),
|
"bg-icon-critical-base": !overallHealthy() && server.healthy() !== undefined,
|
||||||
"bg-border-weak-base": server.healthy() === undefined || !ready(),
|
"bg-border-weak-base": server.healthy() === undefined,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -52,15 +231,193 @@ export function StatusPopover() {
|
|||||||
placement="bottom-end"
|
placement="bottom-end"
|
||||||
shift={-168}
|
shift={-168}
|
||||||
>
|
>
|
||||||
<Show when={shown()}>
|
<div class="flex items-center gap-1 w-[360px] rounded-xl shadow-[var(--shadow-lg-border-base)]">
|
||||||
<Suspense
|
<Tabs
|
||||||
fallback={
|
aria-label={language.t("status.popover.ariaLabel")}
|
||||||
<div class="w-[360px] h-14 rounded-xl bg-background-strong shadow-[var(--shadow-lg-border-base)]" />
|
class="tabs bg-background-strong rounded-xl overflow-hidden"
|
||||||
}
|
data-component="tabs"
|
||||||
|
data-active="servers"
|
||||||
|
defaultValue="servers"
|
||||||
|
variant="alt"
|
||||||
>
|
>
|
||||||
<Body shown={shown} />
|
<Tabs.List data-slot="tablist" class="bg-transparent border-b-0 px-4 pt-2 pb-0 gap-4 h-10">
|
||||||
</Suspense>
|
<Tabs.Trigger value="servers" data-slot="tab" class="text-12-regular">
|
||||||
</Show>
|
{sortedServers().length > 0 ? `${sortedServers().length} ` : ""}
|
||||||
|
{language.t("status.popover.tab.servers")}
|
||||||
|
</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="mcp" data-slot="tab" class="text-12-regular">
|
||||||
|
{mcpConnected() > 0 ? `${mcpConnected()} ` : ""}
|
||||||
|
{language.t("status.popover.tab.mcp")}
|
||||||
|
</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="lsp" data-slot="tab" class="text-12-regular">
|
||||||
|
{lspCount() > 0 ? `${lspCount()} ` : ""}
|
||||||
|
{language.t("status.popover.tab.lsp")}
|
||||||
|
</Tabs.Trigger>
|
||||||
|
<Tabs.Trigger value="plugins" data-slot="tab" class="text-12-regular">
|
||||||
|
{pluginCount() > 0 ? `${pluginCount()} ` : ""}
|
||||||
|
{language.t("status.popover.tab.plugins")}
|
||||||
|
</Tabs.Trigger>
|
||||||
|
</Tabs.List>
|
||||||
|
|
||||||
|
<Tabs.Content value="servers">
|
||||||
|
<div class="flex flex-col px-2 pb-2">
|
||||||
|
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
||||||
|
<For each={sortedServers()}>
|
||||||
|
{(s) => {
|
||||||
|
const key = ServerConnection.key(s)
|
||||||
|
const isBlocked = () => health[key]?.healthy === false
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex items-center gap-2 w-full h-8 pl-3 pr-1.5 py-1.5 rounded-md transition-colors text-left"
|
||||||
|
classList={{
|
||||||
|
"hover:bg-surface-raised-base-hover": !isBlocked(),
|
||||||
|
"cursor-not-allowed": isBlocked(),
|
||||||
|
}}
|
||||||
|
aria-disabled={isBlocked()}
|
||||||
|
onClick={() => {
|
||||||
|
if (isBlocked()) return
|
||||||
|
navigate("/")
|
||||||
|
queueMicrotask(() => server.setActive(key))
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<ServerHealthIndicator health={health[key]} />
|
||||||
|
<ServerRow
|
||||||
|
conn={s}
|
||||||
|
dimmed={isBlocked()}
|
||||||
|
status={health[key]}
|
||||||
|
class="flex items-center gap-2 w-full min-w-0"
|
||||||
|
nameClass="text-14-regular text-text-base truncate"
|
||||||
|
versionClass="text-12-regular text-text-weak truncate"
|
||||||
|
badge={
|
||||||
|
<Show when={key === defaultServer.key()}>
|
||||||
|
<span class="text-11-regular text-text-base bg-surface-base px-1.5 py-0.5 rounded-md">
|
||||||
|
{language.t("common.default")}
|
||||||
|
</span>
|
||||||
|
</Show>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div class="flex-1" />
|
||||||
|
<Show when={server.current && key === ServerConnection.key(server.current)}>
|
||||||
|
<Icon name="check" size="small" class="text-icon-weak shrink-0" />
|
||||||
|
</Show>
|
||||||
|
</ServerRow>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
</For>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
class="mt-3 self-start h-8 px-3 py-1.5"
|
||||||
|
onClick={() => dialog.show(() => <DialogSelectServer />, defaultServer.refresh)}
|
||||||
|
>
|
||||||
|
{language.t("status.popover.action.manageServers")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Tabs.Content>
|
||||||
|
|
||||||
|
<Tabs.Content value="mcp">
|
||||||
|
<div class="flex flex-col px-2 pb-2">
|
||||||
|
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
||||||
|
<Show
|
||||||
|
when={mcpNames().length > 0}
|
||||||
|
fallback={
|
||||||
|
<div class="text-14-regular text-text-base text-center my-auto">
|
||||||
|
{language.t("dialog.mcp.empty")}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<For each={mcpNames()}>
|
||||||
|
{(name) => {
|
||||||
|
const status = () => mcpStatus(name)
|
||||||
|
const enabled = () => status() === "connected"
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex items-center gap-2 w-full h-8 pl-3 pr-2 py-1 rounded-md hover:bg-surface-raised-base-hover transition-colors text-left"
|
||||||
|
onClick={() => mcp.toggle(name)}
|
||||||
|
disabled={mcp.loading() === name}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
classList={{
|
||||||
|
"size-1.5 rounded-full shrink-0": true,
|
||||||
|
"bg-icon-success-base": status() === "connected",
|
||||||
|
"bg-icon-critical-base": status() === "failed",
|
||||||
|
"bg-border-weak-base": status() === "disabled",
|
||||||
|
"bg-icon-warning-base":
|
||||||
|
status() === "needs_auth" || status() === "needs_client_registration",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span class="text-14-regular text-text-base truncate flex-1">{name}</span>
|
||||||
|
<div onClick={(event) => event.stopPropagation()}>
|
||||||
|
<Switch
|
||||||
|
checked={enabled()}
|
||||||
|
disabled={mcp.loading() === name}
|
||||||
|
onChange={() => mcp.toggle(name)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
</For>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Tabs.Content>
|
||||||
|
|
||||||
|
<Tabs.Content value="lsp">
|
||||||
|
<div class="flex flex-col px-2 pb-2">
|
||||||
|
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
||||||
|
<Show
|
||||||
|
when={lspItems().length > 0}
|
||||||
|
fallback={
|
||||||
|
<div class="text-14-regular text-text-base text-center my-auto">
|
||||||
|
{language.t("dialog.lsp.empty")}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<For each={lspItems()}>
|
||||||
|
{(item) => (
|
||||||
|
<div class="flex items-center gap-2 w-full px-2 py-1">
|
||||||
|
<div
|
||||||
|
classList={{
|
||||||
|
"size-1.5 rounded-full shrink-0": true,
|
||||||
|
"bg-icon-success-base": item.status === "connected",
|
||||||
|
"bg-icon-critical-base": item.status === "error",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span class="text-14-regular text-text-base truncate">{item.name || item.id}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Tabs.Content>
|
||||||
|
|
||||||
|
<Tabs.Content value="plugins">
|
||||||
|
<div class="flex flex-col px-2 pb-2">
|
||||||
|
<div class="flex flex-col p-3 bg-background-base rounded-sm min-h-14">
|
||||||
|
<Show
|
||||||
|
when={plugins().length > 0}
|
||||||
|
fallback={<div class="text-14-regular text-text-base text-center my-auto">{pluginEmpty()}</div>}
|
||||||
|
>
|
||||||
|
<For each={plugins()}>
|
||||||
|
{(plugin) => (
|
||||||
|
<div class="flex items-center gap-2 w-full px-2 py-1">
|
||||||
|
<div class="size-1.5 rounded-full shrink-0 bg-icon-success-base" />
|
||||||
|
<span class="text-14-regular text-text-base truncate">{plugin}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Tabs.Content>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
</Popover>
|
</Popover>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import { withAlpha } from "@opencode-ai/ui/theme/color"
|
import { type HexColor, resolveThemeVariant, useTheme, withAlpha } from "@opencode-ai/ui/theme"
|
||||||
import { useTheme } from "@opencode-ai/ui/theme/context"
|
|
||||||
import { resolveThemeVariant } from "@opencode-ai/ui/theme/resolve"
|
|
||||||
import type { HexColor } from "@opencode-ai/ui/theme/types"
|
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
import type { FitAddon, Ghostty, Terminal as Term } from "ghostty-web"
|
import type { FitAddon, Ghostty, Terminal as Term } from "ghostty-web"
|
||||||
import { type ComponentProps, createEffect, createMemo, onCleanup, onMount, splitProps } from "solid-js"
|
import { type ComponentProps, createEffect, createMemo, onCleanup, onMount, splitProps } from "solid-js"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { IconButton } from "@opencode-ai/ui/icon-button"
|
|||||||
import { Icon } from "@opencode-ai/ui/icon"
|
import { Icon } from "@opencode-ai/ui/icon"
|
||||||
import { Button } from "@opencode-ai/ui/button"
|
import { Button } from "@opencode-ai/ui/button"
|
||||||
import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
|
import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
|
||||||
import { useTheme } from "@opencode-ai/ui/theme/context"
|
import { useTheme } from "@opencode-ai/ui/theme"
|
||||||
|
|
||||||
import { useLayout } from "@/context/layout"
|
import { useLayout } from "@/context/layout"
|
||||||
import { usePlatform } from "@/context/platform"
|
import { usePlatform } from "@/context/platform"
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
export const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"]
|
|
||||||
|
|
||||||
export const ACCEPTED_FILE_TYPES = [
|
|
||||||
...ACCEPTED_IMAGE_TYPES,
|
|
||||||
"application/pdf",
|
|
||||||
"text/*",
|
|
||||||
"application/json",
|
|
||||||
"application/ld+json",
|
|
||||||
"application/toml",
|
|
||||||
"application/x-toml",
|
|
||||||
"application/x-yaml",
|
|
||||||
"application/xml",
|
|
||||||
"application/yaml",
|
|
||||||
".c",
|
|
||||||
".cc",
|
|
||||||
".cjs",
|
|
||||||
".conf",
|
|
||||||
".cpp",
|
|
||||||
".css",
|
|
||||||
".csv",
|
|
||||||
".cts",
|
|
||||||
".env",
|
|
||||||
".go",
|
|
||||||
".gql",
|
|
||||||
".graphql",
|
|
||||||
".h",
|
|
||||||
".hh",
|
|
||||||
".hpp",
|
|
||||||
".htm",
|
|
||||||
".html",
|
|
||||||
".ini",
|
|
||||||
".java",
|
|
||||||
".js",
|
|
||||||
".json",
|
|
||||||
".jsx",
|
|
||||||
".log",
|
|
||||||
".md",
|
|
||||||
".mdx",
|
|
||||||
".mjs",
|
|
||||||
".mts",
|
|
||||||
".py",
|
|
||||||
".rb",
|
|
||||||
".rs",
|
|
||||||
".sass",
|
|
||||||
".scss",
|
|
||||||
".sh",
|
|
||||||
".sql",
|
|
||||||
".toml",
|
|
||||||
".ts",
|
|
||||||
".tsx",
|
|
||||||
".txt",
|
|
||||||
".xml",
|
|
||||||
".yaml",
|
|
||||||
".yml",
|
|
||||||
".zsh",
|
|
||||||
]
|
|
||||||
|
|
||||||
const MIME_EXT = new Map([
|
|
||||||
["image/png", "png"],
|
|
||||||
["image/jpeg", "jpg"],
|
|
||||||
["image/gif", "gif"],
|
|
||||||
["image/webp", "webp"],
|
|
||||||
["application/pdf", "pdf"],
|
|
||||||
["application/json", "json"],
|
|
||||||
["application/ld+json", "jsonld"],
|
|
||||||
["application/toml", "toml"],
|
|
||||||
["application/x-toml", "toml"],
|
|
||||||
["application/x-yaml", "yaml"],
|
|
||||||
["application/xml", "xml"],
|
|
||||||
["application/yaml", "yaml"],
|
|
||||||
])
|
|
||||||
|
|
||||||
const TEXT_EXT = ["txt", "text", "md", "markdown", "log", "csv"]
|
|
||||||
|
|
||||||
export const ACCEPTED_FILE_EXTENSIONS = Array.from(
|
|
||||||
new Set(
|
|
||||||
ACCEPTED_FILE_TYPES.flatMap((item) => {
|
|
||||||
if (item.startsWith(".")) return [item.slice(1)]
|
|
||||||
if (item === "text/*") return TEXT_EXT
|
|
||||||
const out = MIME_EXT.get(item)
|
|
||||||
return out ? [out] : []
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
).sort()
|
|
||||||
|
|
||||||
export function filePickerFilters(ext?: string[]) {
|
|
||||||
if (!ext || ext.length === 0) return undefined
|
|
||||||
return [{ name: "Files", extensions: ext }]
|
|
||||||
}
|
|
||||||
@@ -32,25 +32,6 @@ describe("command keybind helpers", () => {
|
|||||||
expect(matchKeybind(keybinds, new KeyboardEvent("keydown", { key: ",", ctrlKey: true, altKey: true }))).toBe(false)
|
expect(matchKeybind(keybinds, new KeyboardEvent("keydown", { key: ",", ctrlKey: true, altKey: true }))).toBe(false)
|
||||||
})
|
})
|
||||||
|
|
||||||
test("matchKeybind supports bracket keys", () => {
|
|
||||||
const keybinds = parseKeybind("mod+alt+[, mod+alt+]")
|
|
||||||
const prev = keybinds[0]
|
|
||||||
const next = keybinds[1]
|
|
||||||
|
|
||||||
expect(
|
|
||||||
matchKeybind(
|
|
||||||
keybinds,
|
|
||||||
new KeyboardEvent("keydown", { key: "[", ctrlKey: prev?.ctrl, metaKey: prev?.meta, altKey: true }),
|
|
||||||
),
|
|
||||||
).toBe(true)
|
|
||||||
expect(
|
|
||||||
matchKeybind(
|
|
||||||
keybinds,
|
|
||||||
new KeyboardEvent("keydown", { key: "]", ctrlKey: next?.ctrl, metaKey: next?.meta, altKey: true }),
|
|
||||||
),
|
|
||||||
).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("formatKeybind returns human readable output", () => {
|
test("formatKeybind returns human readable output", () => {
|
||||||
const display = formatKeybind("ctrl+alt+arrowup")
|
const display = formatKeybind("ctrl+alt+arrowup")
|
||||||
|
|
||||||
@@ -59,11 +40,4 @@ describe("command keybind helpers", () => {
|
|||||||
expect(display.includes("Alt") || display.includes("⌥")).toBe(true)
|
expect(display.includes("Alt") || display.includes("⌥")).toBe(true)
|
||||||
expect(formatKeybind("none")).toBe("")
|
expect(formatKeybind("none")).toBe("")
|
||||||
})
|
})
|
||||||
|
|
||||||
test("formatKeybind prefers the first combo", () => {
|
|
||||||
const display = formatKeybind("mod+k,mod+p")
|
|
||||||
|
|
||||||
expect(display.includes("K") || display.includes("k")).toBe(true)
|
|
||||||
expect(display.includes("P") || display.includes("p")).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -105,8 +105,6 @@ export const { use: useGlobalSDK, provider: GlobalSDKProvider } = createSimpleCo
|
|||||||
const aborted = (error: unknown) => abortError.safeParse(error).success
|
const aborted = (error: unknown) => abortError.safeParse(error).success
|
||||||
|
|
||||||
let attempt: AbortController | undefined
|
let attempt: AbortController | undefined
|
||||||
let run: Promise<void> | undefined
|
|
||||||
let started = false
|
|
||||||
const HEARTBEAT_TIMEOUT_MS = 15_000
|
const HEARTBEAT_TIMEOUT_MS = 15_000
|
||||||
let lastEventAt = Date.now()
|
let lastEventAt = Date.now()
|
||||||
let heartbeat: ReturnType<typeof setTimeout> | undefined
|
let heartbeat: ReturnType<typeof setTimeout> | undefined
|
||||||
@@ -123,93 +121,78 @@ export const { use: useGlobalSDK, provider: GlobalSDKProvider } = createSimpleCo
|
|||||||
heartbeat = undefined
|
heartbeat = undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
const start = () => {
|
void (async () => {
|
||||||
if (started) return run
|
while (!abort.signal.aborted) {
|
||||||
started = true
|
attempt = new AbortController()
|
||||||
run = (async () => {
|
lastEventAt = Date.now()
|
||||||
while (!abort.signal.aborted && started) {
|
const onAbort = () => {
|
||||||
attempt = new AbortController()
|
attempt?.abort()
|
||||||
lastEventAt = Date.now()
|
}
|
||||||
const onAbort = () => {
|
abort.signal.addEventListener("abort", onAbort)
|
||||||
attempt?.abort()
|
try {
|
||||||
}
|
const events = await eventSdk.global.event({
|
||||||
abort.signal.addEventListener("abort", onAbort)
|
signal: attempt.signal,
|
||||||
try {
|
onSseError: (error) => {
|
||||||
const events = await eventSdk.global.event({
|
if (aborted(error)) return
|
||||||
signal: attempt.signal,
|
if (streamErrorLogged) return
|
||||||
onSseError: (error) => {
|
|
||||||
if (aborted(error)) return
|
|
||||||
if (streamErrorLogged) return
|
|
||||||
streamErrorLogged = true
|
|
||||||
console.error("[global-sdk] event stream error", {
|
|
||||||
url: currentServer.http.url,
|
|
||||||
fetch: eventFetch ? "platform" : "webview",
|
|
||||||
error,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
let yielded = Date.now()
|
|
||||||
resetHeartbeat()
|
|
||||||
for await (const event of events.stream) {
|
|
||||||
resetHeartbeat()
|
|
||||||
streamErrorLogged = false
|
|
||||||
const directory = event.directory ?? "global"
|
|
||||||
const payload = event.payload
|
|
||||||
const k = key(directory, payload)
|
|
||||||
if (k) {
|
|
||||||
const i = coalesced.get(k)
|
|
||||||
if (i !== undefined) {
|
|
||||||
queue[i] = { directory, payload }
|
|
||||||
if (payload.type === "message.part.updated") {
|
|
||||||
const part = payload.properties.part
|
|
||||||
staleDeltas.add(deltaKey(directory, part.messageID, part.id))
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
coalesced.set(k, queue.length)
|
|
||||||
}
|
|
||||||
queue.push({ directory, payload })
|
|
||||||
schedule()
|
|
||||||
|
|
||||||
if (Date.now() - yielded < STREAM_YIELD_MS) continue
|
|
||||||
yielded = Date.now()
|
|
||||||
await wait(0)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
if (!aborted(error) && !streamErrorLogged) {
|
|
||||||
streamErrorLogged = true
|
streamErrorLogged = true
|
||||||
console.error("[global-sdk] event stream failed", {
|
console.error("[global-sdk] event stream error", {
|
||||||
url: currentServer.http.url,
|
url: currentServer.http.url,
|
||||||
fetch: eventFetch ? "platform" : "webview",
|
fetch: eventFetch ? "platform" : "webview",
|
||||||
error,
|
error,
|
||||||
})
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
let yielded = Date.now()
|
||||||
|
resetHeartbeat()
|
||||||
|
for await (const event of events.stream) {
|
||||||
|
resetHeartbeat()
|
||||||
|
streamErrorLogged = false
|
||||||
|
const directory = event.directory ?? "global"
|
||||||
|
const payload = event.payload
|
||||||
|
const k = key(directory, payload)
|
||||||
|
if (k) {
|
||||||
|
const i = coalesced.get(k)
|
||||||
|
if (i !== undefined) {
|
||||||
|
queue[i] = { directory, payload }
|
||||||
|
if (payload.type === "message.part.updated") {
|
||||||
|
const part = payload.properties.part
|
||||||
|
staleDeltas.add(deltaKey(directory, part.messageID, part.id))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
coalesced.set(k, queue.length)
|
||||||
}
|
}
|
||||||
} finally {
|
queue.push({ directory, payload })
|
||||||
abort.signal.removeEventListener("abort", onAbort)
|
schedule()
|
||||||
attempt = undefined
|
|
||||||
clearHeartbeat()
|
if (Date.now() - yielded < STREAM_YIELD_MS) continue
|
||||||
|
yielded = Date.now()
|
||||||
|
await wait(0)
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
if (abort.signal.aborted || !started) return
|
if (!aborted(error) && !streamErrorLogged) {
|
||||||
await wait(RECONNECT_DELAY_MS)
|
streamErrorLogged = true
|
||||||
|
console.error("[global-sdk] event stream failed", {
|
||||||
|
url: currentServer.http.url,
|
||||||
|
fetch: eventFetch ? "platform" : "webview",
|
||||||
|
error,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
abort.signal.removeEventListener("abort", onAbort)
|
||||||
|
attempt = undefined
|
||||||
|
clearHeartbeat()
|
||||||
}
|
}
|
||||||
})().finally(() => {
|
|
||||||
run = undefined
|
|
||||||
flush()
|
|
||||||
})
|
|
||||||
return run
|
|
||||||
}
|
|
||||||
|
|
||||||
const stop = () => {
|
if (abort.signal.aborted) return
|
||||||
started = false
|
await wait(RECONNECT_DELAY_MS)
|
||||||
attempt?.abort()
|
}
|
||||||
clearHeartbeat()
|
})().finally(flush)
|
||||||
}
|
|
||||||
|
|
||||||
const onVisibility = () => {
|
const onVisibility = () => {
|
||||||
if (typeof document === "undefined") return
|
if (typeof document === "undefined") return
|
||||||
if (document.visibilityState !== "visible") return
|
if (document.visibilityState !== "visible") return
|
||||||
if (!started) return
|
|
||||||
if (Date.now() - lastEventAt < HEARTBEAT_TIMEOUT_MS) return
|
if (Date.now() - lastEventAt < HEARTBEAT_TIMEOUT_MS) return
|
||||||
attempt?.abort()
|
attempt?.abort()
|
||||||
}
|
}
|
||||||
@@ -221,7 +204,6 @@ export const { use: useGlobalSDK, provider: GlobalSDKProvider } = createSimpleCo
|
|||||||
if (typeof document !== "undefined") {
|
if (typeof document !== "undefined") {
|
||||||
document.removeEventListener("visibilitychange", onVisibility)
|
document.removeEventListener("visibilitychange", onVisibility)
|
||||||
}
|
}
|
||||||
stop()
|
|
||||||
abort.abort()
|
abort.abort()
|
||||||
flush()
|
flush()
|
||||||
})
|
})
|
||||||
@@ -235,11 +217,7 @@ export const { use: useGlobalSDK, provider: GlobalSDKProvider } = createSimpleCo
|
|||||||
return {
|
return {
|
||||||
url: currentServer.http.url,
|
url: currentServer.http.url,
|
||||||
client: sdk,
|
client: sdk,
|
||||||
event: {
|
event: emitter,
|
||||||
on: emitter.on.bind(emitter),
|
|
||||||
listen: emitter.listen.bind(emitter),
|
|
||||||
start,
|
|
||||||
},
|
|
||||||
createClient(opts: Omit<Parameters<typeof createSdkForServer>[0], "server" | "fetch">) {
|
createClient(opts: Omit<Parameters<typeof createSdkForServer>[0], "server" | "fetch">) {
|
||||||
const s = server.current
|
const s = server.current
|
||||||
if (!s) throw new Error(language.t("error.globalSDK.serverNotAvailable"))
|
if (!s) throw new Error(language.t("error.globalSDK.serverNotAvailable"))
|
||||||
|
|||||||
@@ -9,13 +9,23 @@ import type {
|
|||||||
} from "@opencode-ai/sdk/v2/client"
|
} from "@opencode-ai/sdk/v2/client"
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
import { getFilename } from "@opencode-ai/util/path"
|
import { getFilename } from "@opencode-ai/util/path"
|
||||||
import { createContext, getOwner, onCleanup, onMount, type ParentProps, untrack, useContext } from "solid-js"
|
import {
|
||||||
|
createContext,
|
||||||
|
getOwner,
|
||||||
|
Match,
|
||||||
|
onCleanup,
|
||||||
|
onMount,
|
||||||
|
type ParentProps,
|
||||||
|
Switch,
|
||||||
|
untrack,
|
||||||
|
useContext,
|
||||||
|
} from "solid-js"
|
||||||
import { createStore, produce, reconcile } from "solid-js/store"
|
import { createStore, produce, reconcile } from "solid-js/store"
|
||||||
import { useLanguage } from "@/context/language"
|
import { useLanguage } from "@/context/language"
|
||||||
import { Persist, persisted } from "@/utils/persist"
|
import { Persist, persisted } from "@/utils/persist"
|
||||||
import type { InitError } from "../pages/error"
|
import type { InitError } from "../pages/error"
|
||||||
import { useGlobalSDK } from "./global-sdk"
|
import { useGlobalSDK } from "./global-sdk"
|
||||||
import { bootstrapDirectory, bootstrapGlobal, clearProviderRev } from "./global-sync/bootstrap"
|
import { bootstrapDirectory, bootstrapGlobal } from "./global-sync/bootstrap"
|
||||||
import { createChildStoreManager } from "./global-sync/child-store"
|
import { createChildStoreManager } from "./global-sync/child-store"
|
||||||
import { applyDirectoryEvent, applyGlobalEvent, cleanupDroppedSessionCaches } from "./global-sync/event-reducer"
|
import { applyDirectoryEvent, applyGlobalEvent, cleanupDroppedSessionCaches } from "./global-sync/event-reducer"
|
||||||
import { createRefreshQueue } from "./global-sync/queue"
|
import { createRefreshQueue } from "./global-sync/queue"
|
||||||
@@ -70,18 +80,10 @@ function createGlobalSync() {
|
|||||||
|
|
||||||
let active = true
|
let active = true
|
||||||
let projectWritten = false
|
let projectWritten = false
|
||||||
let bootedAt = 0
|
|
||||||
let bootingRoot = false
|
|
||||||
let eventFrame: number | undefined
|
|
||||||
let eventTimer: ReturnType<typeof setTimeout> | undefined
|
|
||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
active = false
|
active = false
|
||||||
})
|
})
|
||||||
onCleanup(() => {
|
|
||||||
if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
|
|
||||||
if (eventTimer !== undefined) clearTimeout(eventTimer)
|
|
||||||
})
|
|
||||||
|
|
||||||
const cacheProjects = () => {
|
const cacheProjects = () => {
|
||||||
setProjectCache(
|
setProjectCache(
|
||||||
@@ -160,7 +162,6 @@ function createGlobalSync() {
|
|||||||
queue.clear(directory)
|
queue.clear(directory)
|
||||||
sessionMeta.delete(directory)
|
sessionMeta.delete(directory)
|
||||||
sdkCache.delete(directory)
|
sdkCache.delete(directory)
|
||||||
clearProviderRev(directory)
|
|
||||||
clearSessionPrefetchDirectory(directory)
|
clearSessionPrefetchDirectory(directory)
|
||||||
},
|
},
|
||||||
translate: language.t,
|
translate: language.t,
|
||||||
@@ -257,12 +258,6 @@ function createGlobalSync() {
|
|||||||
const sdk = sdkFor(directory)
|
const sdk = sdkFor(directory)
|
||||||
await bootstrapDirectory({
|
await bootstrapDirectory({
|
||||||
directory,
|
directory,
|
||||||
global: {
|
|
||||||
config: globalStore.config,
|
|
||||||
path: globalStore.path,
|
|
||||||
project: globalStore.project,
|
|
||||||
provider: globalStore.provider,
|
|
||||||
},
|
|
||||||
sdk,
|
sdk,
|
||||||
store: child[0],
|
store: child[0],
|
||||||
setStore: child[1],
|
setStore: child[1],
|
||||||
@@ -283,20 +278,15 @@ function createGlobalSync() {
|
|||||||
const unsub = globalSDK.event.listen((e) => {
|
const unsub = globalSDK.event.listen((e) => {
|
||||||
const directory = e.name
|
const directory = e.name
|
||||||
const event = e.details
|
const event = e.details
|
||||||
const recent = bootingRoot || Date.now() - bootedAt < 1500
|
|
||||||
|
|
||||||
if (directory === "global") {
|
if (directory === "global") {
|
||||||
applyGlobalEvent({
|
applyGlobalEvent({
|
||||||
event,
|
event,
|
||||||
project: globalStore.project,
|
project: globalStore.project,
|
||||||
refresh: () => {
|
refresh: queue.refresh,
|
||||||
if (recent) return
|
|
||||||
queue.refresh()
|
|
||||||
},
|
|
||||||
setGlobalProject: setProjects,
|
setGlobalProject: setProjects,
|
||||||
})
|
})
|
||||||
if (event.type === "server.connected" || event.type === "global.disposed") {
|
if (event.type === "server.connected" || event.type === "global.disposed") {
|
||||||
if (recent) return
|
|
||||||
for (const directory of Object.keys(children.children)) {
|
for (const directory of Object.keys(children.children)) {
|
||||||
queue.push(directory)
|
queue.push(directory)
|
||||||
}
|
}
|
||||||
@@ -319,10 +309,7 @@ function createGlobalSync() {
|
|||||||
loadLsp: () => {
|
loadLsp: () => {
|
||||||
sdkFor(directory)
|
sdkFor(directory)
|
||||||
.lsp.status()
|
.lsp.status()
|
||||||
.then((x) => {
|
.then((x) => setStore("lsp", x.data ?? []))
|
||||||
setStore("lsp", x.data ?? [])
|
|
||||||
setStore("lsp_ready", true)
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -338,36 +325,20 @@ function createGlobalSync() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
bootingRoot = true
|
await bootstrapGlobal({
|
||||||
try {
|
globalSDK: globalSDK.client,
|
||||||
await bootstrapGlobal({
|
connectErrorTitle: language.t("dialog.server.add.error"),
|
||||||
globalSDK: globalSDK.client,
|
connectErrorDescription: language.t("error.globalSync.connectFailed", {
|
||||||
requestFailedTitle: language.t("common.requestFailed"),
|
url: globalSDK.url,
|
||||||
translate: language.t,
|
}),
|
||||||
formatMoreCount: (count) => language.t("common.moreCountSuffix", { count }),
|
requestFailedTitle: language.t("common.requestFailed"),
|
||||||
setGlobalStore: setBootStore,
|
translate: language.t,
|
||||||
})
|
formatMoreCount: (count) => language.t("common.moreCountSuffix", { count }),
|
||||||
bootedAt = Date.now()
|
setGlobalStore: setBootStore,
|
||||||
} finally {
|
})
|
||||||
bootingRoot = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
if (typeof requestAnimationFrame === "function") {
|
|
||||||
eventFrame = requestAnimationFrame(() => {
|
|
||||||
eventFrame = undefined
|
|
||||||
eventTimer = setTimeout(() => {
|
|
||||||
eventTimer = undefined
|
|
||||||
globalSDK.event.start()
|
|
||||||
}, 0)
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
eventTimer = setTimeout(() => {
|
|
||||||
eventTimer = undefined
|
|
||||||
globalSDK.event.start()
|
|
||||||
}, 0)
|
|
||||||
}
|
|
||||||
void bootstrap()
|
void bootstrap()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -407,7 +378,6 @@ function createGlobalSync() {
|
|||||||
return globalStore.error
|
return globalStore.error
|
||||||
},
|
},
|
||||||
child: children.child,
|
child: children.child,
|
||||||
peek: children.peek,
|
|
||||||
bootstrap,
|
bootstrap,
|
||||||
updateConfig,
|
updateConfig,
|
||||||
project: projectApi,
|
project: projectApi,
|
||||||
@@ -421,7 +391,13 @@ const GlobalSyncContext = createContext<ReturnType<typeof createGlobalSync>>()
|
|||||||
|
|
||||||
export function GlobalSyncProvider(props: ParentProps) {
|
export function GlobalSyncProvider(props: ParentProps) {
|
||||||
const value = createGlobalSync()
|
const value = createGlobalSync()
|
||||||
return <GlobalSyncContext.Provider value={value}>{props.children}</GlobalSyncContext.Provider>
|
return (
|
||||||
|
<Switch>
|
||||||
|
<Match when={value.ready}>
|
||||||
|
<GlobalSyncContext.Provider value={value}>{props.children}</GlobalSyncContext.Provider>
|
||||||
|
</Match>
|
||||||
|
</Switch>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useGlobalSync() {
|
export function useGlobalSync() {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import type {
|
|||||||
ProviderAuthResponse,
|
ProviderAuthResponse,
|
||||||
ProviderListResponse,
|
ProviderListResponse,
|
||||||
QuestionRequest,
|
QuestionRequest,
|
||||||
Session,
|
|
||||||
Todo,
|
Todo,
|
||||||
} from "@opencode-ai/sdk/v2/client"
|
} from "@opencode-ai/sdk/v2/client"
|
||||||
import { showToast } from "@opencode-ai/ui/toast"
|
import { showToast } from "@opencode-ai/ui/toast"
|
||||||
@@ -16,7 +15,7 @@ import { retry } from "@opencode-ai/util/retry"
|
|||||||
import { batch } from "solid-js"
|
import { batch } from "solid-js"
|
||||||
import { reconcile, type SetStoreFunction, type Store } from "solid-js/store"
|
import { reconcile, type SetStoreFunction, type Store } from "solid-js/store"
|
||||||
import type { State, VcsCache } from "./types"
|
import type { State, VcsCache } from "./types"
|
||||||
import { cmp, normalizeAgentList, normalizeProviderList } from "./utils"
|
import { cmp, normalizeProviderList } from "./utils"
|
||||||
import { formatServerError } from "@/utils/server-errors"
|
import { formatServerError } from "@/utils/server-errors"
|
||||||
|
|
||||||
type GlobalStore = {
|
type GlobalStore = {
|
||||||
@@ -32,110 +31,73 @@ type GlobalStore = {
|
|||||||
reload: undefined | "pending" | "complete"
|
reload: undefined | "pending" | "complete"
|
||||||
}
|
}
|
||||||
|
|
||||||
function waitForPaint() {
|
|
||||||
return new Promise<void>((resolve) => {
|
|
||||||
let done = false
|
|
||||||
const finish = () => {
|
|
||||||
if (done) return
|
|
||||||
done = true
|
|
||||||
resolve()
|
|
||||||
}
|
|
||||||
const timer = setTimeout(finish, 50)
|
|
||||||
if (typeof requestAnimationFrame !== "function") return
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
clearTimeout(timer)
|
|
||||||
finish()
|
|
||||||
}, 0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function errors(list: PromiseSettledResult<unknown>[]) {
|
|
||||||
return list.filter((item): item is PromiseRejectedResult => item.status === "rejected").map((item) => item.reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
const providerRev = new Map<string, number>()
|
|
||||||
|
|
||||||
export function clearProviderRev(directory: string) {
|
|
||||||
providerRev.delete(directory)
|
|
||||||
}
|
|
||||||
|
|
||||||
function runAll(list: Array<() => Promise<unknown>>) {
|
|
||||||
return Promise.allSettled(list.map((item) => item()))
|
|
||||||
}
|
|
||||||
|
|
||||||
function showErrors(input: {
|
|
||||||
errors: unknown[]
|
|
||||||
title: string
|
|
||||||
translate: (key: string, vars?: Record<string, string | number>) => string
|
|
||||||
formatMoreCount: (count: number) => string
|
|
||||||
}) {
|
|
||||||
if (input.errors.length === 0) return
|
|
||||||
const message = formatServerError(input.errors[0], input.translate)
|
|
||||||
const more = input.errors.length > 1 ? input.formatMoreCount(input.errors.length - 1) : ""
|
|
||||||
showToast({
|
|
||||||
variant: "error",
|
|
||||||
title: input.title,
|
|
||||||
description: message + more,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function bootstrapGlobal(input: {
|
export async function bootstrapGlobal(input: {
|
||||||
globalSDK: OpencodeClient
|
globalSDK: OpencodeClient
|
||||||
|
connectErrorTitle: string
|
||||||
|
connectErrorDescription: string
|
||||||
requestFailedTitle: string
|
requestFailedTitle: string
|
||||||
translate: (key: string, vars?: Record<string, string | number>) => string
|
translate: (key: string, vars?: Record<string, string | number>) => string
|
||||||
formatMoreCount: (count: number) => string
|
formatMoreCount: (count: number) => string
|
||||||
setGlobalStore: SetStoreFunction<GlobalStore>
|
setGlobalStore: SetStoreFunction<GlobalStore>
|
||||||
}) {
|
}) {
|
||||||
const fast = [
|
const health = await input.globalSDK.global
|
||||||
() =>
|
.health()
|
||||||
retry(() =>
|
.then((x) => x.data)
|
||||||
input.globalSDK.global.config.get().then((x) => {
|
.catch(() => undefined)
|
||||||
input.setGlobalStore("config", x.data!)
|
if (!health?.healthy) {
|
||||||
}),
|
showToast({
|
||||||
),
|
variant: "error",
|
||||||
() =>
|
title: input.connectErrorTitle,
|
||||||
retry(() =>
|
description: input.connectErrorDescription,
|
||||||
input.globalSDK.provider.list().then((x) => {
|
})
|
||||||
input.setGlobalStore("provider", normalizeProviderList(x.data!))
|
input.setGlobalStore("ready", true)
|
||||||
}),
|
return
|
||||||
),
|
}
|
||||||
|
|
||||||
|
const tasks = [
|
||||||
|
retry(() =>
|
||||||
|
input.globalSDK.path.get().then((x) => {
|
||||||
|
input.setGlobalStore("path", x.data!)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
retry(() =>
|
||||||
|
input.globalSDK.global.config.get().then((x) => {
|
||||||
|
input.setGlobalStore("config", x.data!)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
retry(() =>
|
||||||
|
input.globalSDK.project.list().then((x) => {
|
||||||
|
const projects = (x.data ?? [])
|
||||||
|
.filter((p) => !!p?.id)
|
||||||
|
.filter((p) => !!p.worktree && !p.worktree.includes("opencode-test"))
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => cmp(a.id, b.id))
|
||||||
|
input.setGlobalStore("project", projects)
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
retry(() =>
|
||||||
|
input.globalSDK.provider.list().then((x) => {
|
||||||
|
input.setGlobalStore("provider", normalizeProviderList(x.data!))
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
retry(() =>
|
||||||
|
input.globalSDK.provider.auth().then((x) => {
|
||||||
|
input.setGlobalStore("provider_auth", x.data ?? {})
|
||||||
|
}),
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
const slow = [
|
const results = await Promise.allSettled(tasks)
|
||||||
() =>
|
const errors = results.filter((r): r is PromiseRejectedResult => r.status === "rejected").map((r) => r.reason)
|
||||||
retry(() =>
|
if (errors.length) {
|
||||||
input.globalSDK.path.get().then((x) => {
|
const message = formatServerError(errors[0], input.translate)
|
||||||
input.setGlobalStore("path", x.data!)
|
const more = errors.length > 1 ? input.formatMoreCount(errors.length - 1) : ""
|
||||||
}),
|
showToast({
|
||||||
),
|
variant: "error",
|
||||||
() =>
|
title: input.requestFailedTitle,
|
||||||
retry(() =>
|
description: message + more,
|
||||||
input.globalSDK.project.list().then((x) => {
|
})
|
||||||
const projects = (x.data ?? [])
|
}
|
||||||
.filter((p) => !!p?.id)
|
|
||||||
.filter((p) => !!p.worktree && !p.worktree.includes("opencode-test"))
|
|
||||||
.slice()
|
|
||||||
.sort((a, b) => cmp(a.id, b.id))
|
|
||||||
input.setGlobalStore("project", projects)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
|
|
||||||
showErrors({
|
|
||||||
errors: errors(await runAll(fast)),
|
|
||||||
title: input.requestFailedTitle,
|
|
||||||
translate: input.translate,
|
|
||||||
formatMoreCount: input.formatMoreCount,
|
|
||||||
})
|
|
||||||
await waitForPaint()
|
|
||||||
showErrors({
|
|
||||||
errors: errors(await runAll(slow)),
|
|
||||||
title: input.requestFailedTitle,
|
|
||||||
translate: input.translate,
|
|
||||||
formatMoreCount: input.formatMoreCount,
|
|
||||||
})
|
|
||||||
input.setGlobalStore("ready", true)
|
input.setGlobalStore("ready", true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,44 +111,6 @@ function groupBySession<T extends { id: string; sessionID: string }>(input: T[])
|
|||||||
}, {})
|
}, {})
|
||||||
}
|
}
|
||||||
|
|
||||||
function projectID(directory: string, projects: Project[]) {
|
|
||||||
return projects.find((project) => project.worktree === directory || project.sandboxes?.includes(directory))?.id
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeSession(setStore: SetStoreFunction<State>, session: Session) {
|
|
||||||
setStore("session", (list) => {
|
|
||||||
const next = list.slice()
|
|
||||||
const idx = next.findIndex((item) => item.id >= session.id)
|
|
||||||
if (idx === -1) return [...next, session]
|
|
||||||
if (next[idx]?.id === session.id) {
|
|
||||||
next[idx] = session
|
|
||||||
return next
|
|
||||||
}
|
|
||||||
next.splice(idx, 0, session)
|
|
||||||
return next
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function warmSessions(input: {
|
|
||||||
ids: string[]
|
|
||||||
store: Store<State>
|
|
||||||
setStore: SetStoreFunction<State>
|
|
||||||
sdk: OpencodeClient
|
|
||||||
}) {
|
|
||||||
const known = new Set(input.store.session.map((item) => item.id))
|
|
||||||
const ids = [...new Set(input.ids)].filter((id) => !!id && !known.has(id))
|
|
||||||
if (ids.length === 0) return Promise.resolve()
|
|
||||||
return Promise.all(
|
|
||||||
ids.map((sessionID) =>
|
|
||||||
retry(() => input.sdk.session.get({ sessionID })).then((x) => {
|
|
||||||
const session = x.data
|
|
||||||
if (!session?.id) return
|
|
||||||
mergeSession(input.setStore, session)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
).then(() => undefined)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function bootstrapDirectory(input: {
|
export async function bootstrapDirectory(input: {
|
||||||
directory: string
|
directory: string
|
||||||
sdk: OpencodeClient
|
sdk: OpencodeClient
|
||||||
@@ -195,166 +119,88 @@ export async function bootstrapDirectory(input: {
|
|||||||
vcsCache: VcsCache
|
vcsCache: VcsCache
|
||||||
loadSessions: (directory: string) => Promise<void> | void
|
loadSessions: (directory: string) => Promise<void> | void
|
||||||
translate: (key: string, vars?: Record<string, string | number>) => string
|
translate: (key: string, vars?: Record<string, string | number>) => string
|
||||||
global: {
|
|
||||||
config: Config
|
|
||||||
path: Path
|
|
||||||
project: Project[]
|
|
||||||
provider: ProviderListResponse
|
|
||||||
}
|
|
||||||
}) {
|
}) {
|
||||||
const loading = input.store.status !== "complete"
|
if (input.store.status !== "complete") input.setStore("status", "loading")
|
||||||
const seededProject = projectID(input.directory, input.global.project)
|
|
||||||
const seededPath = input.global.path.directory === input.directory ? input.global.path : undefined
|
|
||||||
if (seededProject) input.setStore("project", seededProject)
|
|
||||||
if (seededPath) input.setStore("path", seededPath)
|
|
||||||
if (input.store.provider.all.length === 0 && input.global.provider.all.length > 0) {
|
|
||||||
input.setStore("provider", input.global.provider)
|
|
||||||
}
|
|
||||||
if (Object.keys(input.store.config).length === 0 && Object.keys(input.global.config).length > 0) {
|
|
||||||
input.setStore("config", input.global.config)
|
|
||||||
}
|
|
||||||
if (loading || input.store.provider.all.length === 0) {
|
|
||||||
input.setStore("provider_ready", false)
|
|
||||||
}
|
|
||||||
input.setStore("mcp_ready", false)
|
|
||||||
input.setStore("mcp", {})
|
|
||||||
input.setStore("lsp_ready", false)
|
|
||||||
input.setStore("lsp", [])
|
|
||||||
if (loading) input.setStore("status", "partial")
|
|
||||||
|
|
||||||
const fast = [
|
const blockingRequests = {
|
||||||
() => retry(() => input.sdk.app.agents().then((x) => input.setStore("agent", normalizeAgentList(x.data)))),
|
project: () => input.sdk.project.current().then((x) => input.setStore("project", x.data!.id)),
|
||||||
() => retry(() => input.sdk.config.get().then((x) => input.setStore("config", x.data!))),
|
provider: () =>
|
||||||
() => retry(() => input.sdk.session.status().then((x) => input.setStore("session_status", x.data!))),
|
input.sdk.provider.list().then((x) => {
|
||||||
]
|
input.setStore("provider", normalizeProviderList(x.data!))
|
||||||
|
}),
|
||||||
|
agent: () => input.sdk.app.agents().then((x) => input.setStore("agent", x.data ?? [])),
|
||||||
|
config: () => input.sdk.config.get().then((x) => input.setStore("config", x.data!)),
|
||||||
|
}
|
||||||
|
|
||||||
const slow = [
|
try {
|
||||||
() =>
|
await Promise.all(Object.values(blockingRequests).map((p) => retry(p)))
|
||||||
seededProject
|
} catch (err) {
|
||||||
? Promise.resolve()
|
console.error("Failed to bootstrap instance", err)
|
||||||
: retry(() => input.sdk.project.current()).then((x) => input.setStore("project", x.data!.id)),
|
|
||||||
() =>
|
|
||||||
seededPath
|
|
||||||
? Promise.resolve()
|
|
||||||
: retry(() =>
|
|
||||||
input.sdk.path.get().then((x) => {
|
|
||||||
input.setStore("path", x.data!)
|
|
||||||
const next = projectID(x.data?.directory ?? input.directory, input.global.project)
|
|
||||||
if (next) input.setStore("project", next)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
() =>
|
|
||||||
retry(() =>
|
|
||||||
input.sdk.vcs.get().then((x) => {
|
|
||||||
const next = x.data ?? input.store.vcs
|
|
||||||
input.setStore("vcs", next)
|
|
||||||
if (next?.branch) input.vcsCache.setStore("value", next)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
() => retry(() => input.sdk.command.list().then((x) => input.setStore("command", x.data ?? []))),
|
|
||||||
() =>
|
|
||||||
retry(() =>
|
|
||||||
input.sdk.permission.list().then((x) => {
|
|
||||||
const ids = (x.data ?? []).map((perm) => perm?.sessionID).filter((id): id is string => !!id)
|
|
||||||
const grouped = groupBySession(
|
|
||||||
(x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID),
|
|
||||||
)
|
|
||||||
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then(() =>
|
|
||||||
batch(() => {
|
|
||||||
for (const sessionID of Object.keys(input.store.permission)) {
|
|
||||||
if (grouped[sessionID]) continue
|
|
||||||
input.setStore("permission", sessionID, [])
|
|
||||||
}
|
|
||||||
for (const [sessionID, permissions] of Object.entries(grouped)) {
|
|
||||||
input.setStore(
|
|
||||||
"permission",
|
|
||||||
sessionID,
|
|
||||||
reconcile(
|
|
||||||
permissions.filter((p) => !!p?.id).sort((a, b) => cmp(a.id, b.id)),
|
|
||||||
{ key: "id" },
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
() =>
|
|
||||||
retry(() =>
|
|
||||||
input.sdk.question.list().then((x) => {
|
|
||||||
const ids = (x.data ?? []).map((question) => question?.sessionID).filter((id): id is string => !!id)
|
|
||||||
const grouped = groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID))
|
|
||||||
return warmSessions({ ids, store: input.store, setStore: input.setStore, sdk: input.sdk }).then(() =>
|
|
||||||
batch(() => {
|
|
||||||
for (const sessionID of Object.keys(input.store.question)) {
|
|
||||||
if (grouped[sessionID]) continue
|
|
||||||
input.setStore("question", sessionID, [])
|
|
||||||
}
|
|
||||||
for (const [sessionID, questions] of Object.entries(grouped)) {
|
|
||||||
input.setStore(
|
|
||||||
"question",
|
|
||||||
sessionID,
|
|
||||||
reconcile(
|
|
||||||
questions.filter((q) => !!q?.id).sort((a, b) => cmp(a.id, b.id)),
|
|
||||||
{ key: "id" },
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
() => Promise.resolve(input.loadSessions(input.directory)),
|
|
||||||
() =>
|
|
||||||
retry(() =>
|
|
||||||
input.sdk.mcp.status().then((x) => {
|
|
||||||
input.setStore("mcp", x.data!)
|
|
||||||
input.setStore("mcp_ready", true)
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
|
|
||||||
const errs = errors(await runAll(fast))
|
|
||||||
if (errs.length > 0) {
|
|
||||||
console.error("Failed to bootstrap instance", errs[0])
|
|
||||||
const project = getFilename(input.directory)
|
const project = getFilename(input.directory)
|
||||||
showToast({
|
showToast({
|
||||||
variant: "error",
|
variant: "error",
|
||||||
title: input.translate("toast.project.reloadFailed.title", { project }),
|
title: input.translate("toast.project.reloadFailed.title", { project }),
|
||||||
description: formatServerError(errs[0], input.translate),
|
description: formatServerError(err, input.translate),
|
||||||
})
|
})
|
||||||
|
input.setStore("status", "partial")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
await waitForPaint()
|
if (input.store.status !== "complete") input.setStore("status", "partial")
|
||||||
const slowErrs = errors(await runAll(slow))
|
|
||||||
if (slowErrs.length > 0) {
|
|
||||||
console.error("Failed to finish bootstrap instance", slowErrs[0])
|
|
||||||
const project = getFilename(input.directory)
|
|
||||||
showToast({
|
|
||||||
variant: "error",
|
|
||||||
title: input.translate("toast.project.reloadFailed.title", { project }),
|
|
||||||
description: formatServerError(slowErrs[0], input.translate),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loading && errs.length === 0 && slowErrs.length === 0) input.setStore("status", "complete")
|
Promise.all([
|
||||||
|
input.sdk.path.get().then((x) => input.setStore("path", x.data!)),
|
||||||
const rev = (providerRev.get(input.directory) ?? 0) + 1
|
input.sdk.command.list().then((x) => input.setStore("command", x.data ?? [])),
|
||||||
providerRev.set(input.directory, rev)
|
input.sdk.session.status().then((x) => input.setStore("session_status", x.data!)),
|
||||||
void retry(() => input.sdk.provider.list())
|
input.loadSessions(input.directory),
|
||||||
.then((x) => {
|
input.sdk.mcp.status().then((x) => input.setStore("mcp", x.data!)),
|
||||||
if (providerRev.get(input.directory) !== rev) return
|
input.sdk.lsp.status().then((x) => input.setStore("lsp", x.data!)),
|
||||||
input.setStore("provider", normalizeProviderList(x.data!))
|
input.sdk.vcs.get().then((x) => {
|
||||||
input.setStore("provider_ready", true)
|
const next = x.data ?? input.store.vcs
|
||||||
})
|
input.setStore("vcs", next)
|
||||||
.catch((err) => {
|
if (next?.branch) input.vcsCache.setStore("value", next)
|
||||||
if (providerRev.get(input.directory) !== rev) return
|
}),
|
||||||
console.error("Failed to refresh provider list", err)
|
input.sdk.permission.list().then((x) => {
|
||||||
const project = getFilename(input.directory)
|
const grouped = groupBySession(
|
||||||
showToast({
|
(x.data ?? []).filter((perm): perm is PermissionRequest => !!perm?.id && !!perm.sessionID),
|
||||||
variant: "error",
|
)
|
||||||
title: input.translate("toast.project.reloadFailed.title", { project }),
|
batch(() => {
|
||||||
description: formatServerError(err, input.translate),
|
for (const sessionID of Object.keys(input.store.permission)) {
|
||||||
|
if (grouped[sessionID]) continue
|
||||||
|
input.setStore("permission", sessionID, [])
|
||||||
|
}
|
||||||
|
for (const [sessionID, permissions] of Object.entries(grouped)) {
|
||||||
|
input.setStore(
|
||||||
|
"permission",
|
||||||
|
sessionID,
|
||||||
|
reconcile(
|
||||||
|
permissions.filter((p) => !!p?.id).sort((a, b) => cmp(a.id, b.id)),
|
||||||
|
{ key: "id" },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
})
|
}),
|
||||||
|
input.sdk.question.list().then((x) => {
|
||||||
|
const grouped = groupBySession((x.data ?? []).filter((q): q is QuestionRequest => !!q?.id && !!q.sessionID))
|
||||||
|
batch(() => {
|
||||||
|
for (const sessionID of Object.keys(input.store.question)) {
|
||||||
|
if (grouped[sessionID]) continue
|
||||||
|
input.setStore("question", sessionID, [])
|
||||||
|
}
|
||||||
|
for (const [sessionID, questions] of Object.entries(grouped)) {
|
||||||
|
input.setStore(
|
||||||
|
"question",
|
||||||
|
sessionID,
|
||||||
|
reconcile(
|
||||||
|
questions.filter((q) => !!q?.id).sort((a, b) => cmp(a.id, b.id)),
|
||||||
|
{ key: "id" },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
]).then(() => {
|
||||||
|
input.setStore("status", "complete")
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -160,7 +160,6 @@ export function createChildStoreManager(input: {
|
|||||||
project: "",
|
project: "",
|
||||||
projectMeta: initialMeta,
|
projectMeta: initialMeta,
|
||||||
icon: initialIcon,
|
icon: initialIcon,
|
||||||
provider_ready: false,
|
|
||||||
provider: { all: [], connected: [], default: {} },
|
provider: { all: [], connected: [], default: {} },
|
||||||
config: {},
|
config: {},
|
||||||
path: { state: "", config: "", worktree: "", directory: "", home: "" },
|
path: { state: "", config: "", worktree: "", directory: "", home: "" },
|
||||||
@@ -174,9 +173,7 @@ export function createChildStoreManager(input: {
|
|||||||
todo: {},
|
todo: {},
|
||||||
permission: {},
|
permission: {},
|
||||||
question: {},
|
question: {},
|
||||||
mcp_ready: false,
|
|
||||||
mcp: {},
|
mcp: {},
|
||||||
lsp_ready: false,
|
|
||||||
lsp: [],
|
lsp: [],
|
||||||
vcs: vcsStore.value,
|
vcs: vcsStore.value,
|
||||||
limit: 5,
|
limit: 5,
|
||||||
@@ -229,15 +226,6 @@ export function createChildStoreManager(input: {
|
|||||||
return childStore
|
return childStore
|
||||||
}
|
}
|
||||||
|
|
||||||
function peek(directory: string, options: ChildOptions = {}) {
|
|
||||||
const childStore = ensureChild(directory)
|
|
||||||
const shouldBootstrap = options.bootstrap ?? true
|
|
||||||
if (shouldBootstrap && childStore[0].status === "loading") {
|
|
||||||
input.onBootstrap(directory)
|
|
||||||
}
|
|
||||||
return childStore
|
|
||||||
}
|
|
||||||
|
|
||||||
function projectMeta(directory: string, patch: ProjectMeta) {
|
function projectMeta(directory: string, patch: ProjectMeta) {
|
||||||
const [store, setStore] = ensureChild(directory)
|
const [store, setStore] = ensureChild(directory)
|
||||||
const cached = metaCache.get(directory)
|
const cached = metaCache.get(directory)
|
||||||
@@ -268,7 +256,6 @@ export function createChildStoreManager(input: {
|
|||||||
children,
|
children,
|
||||||
ensureChild,
|
ensureChild,
|
||||||
child,
|
child,
|
||||||
peek,
|
|
||||||
projectMeta,
|
projectMeta,
|
||||||
projectIcon,
|
projectIcon,
|
||||||
mark,
|
mark,
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ import type { State, VcsCache } from "./types"
|
|||||||
import { trimSessions } from "./session-trim"
|
import { trimSessions } from "./session-trim"
|
||||||
import { dropSessionCaches } from "./session-cache"
|
import { dropSessionCaches } from "./session-cache"
|
||||||
|
|
||||||
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
|
||||||
|
|
||||||
export function applyGlobalEvent(input: {
|
export function applyGlobalEvent(input: {
|
||||||
event: { type: string; properties?: unknown }
|
event: { type: string; properties?: unknown }
|
||||||
project: Project[]
|
project: Project[]
|
||||||
@@ -213,7 +211,6 @@ export function applyDirectoryEvent(input: {
|
|||||||
}
|
}
|
||||||
case "message.part.updated": {
|
case "message.part.updated": {
|
||||||
const part = (event.properties as { part: Part }).part
|
const part = (event.properties as { part: Part }).part
|
||||||
if (SKIP_PARTS.has(part.type)) break
|
|
||||||
const parts = input.store.part[part.messageID]
|
const parts = input.store.part[part.messageID]
|
||||||
if (!parts) {
|
if (!parts) {
|
||||||
input.setStore("part", part.messageID, [part])
|
input.setStore("part", part.messageID, [part])
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ export type State = {
|
|||||||
project: string
|
project: string
|
||||||
projectMeta: ProjectMeta | undefined
|
projectMeta: ProjectMeta | undefined
|
||||||
icon: string | undefined
|
icon: string | undefined
|
||||||
provider_ready: boolean
|
|
||||||
provider: ProviderListResponse
|
provider: ProviderListResponse
|
||||||
config: Config
|
config: Config
|
||||||
path: Path
|
path: Path
|
||||||
@@ -59,11 +58,9 @@ export type State = {
|
|||||||
question: {
|
question: {
|
||||||
[sessionID: string]: QuestionRequest[]
|
[sessionID: string]: QuestionRequest[]
|
||||||
}
|
}
|
||||||
mcp_ready: boolean
|
|
||||||
mcp: {
|
mcp: {
|
||||||
[name: string]: McpStatus
|
[name: string]: McpStatus
|
||||||
}
|
}
|
||||||
lsp_ready: boolean
|
|
||||||
lsp: LspStatus[]
|
lsp: LspStatus[]
|
||||||
vcs: VcsInfo | undefined
|
vcs: VcsInfo | undefined
|
||||||
limit: number
|
limit: number
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
import { describe, expect, test } from "bun:test"
|
|
||||||
import type { Agent } from "@opencode-ai/sdk/v2/client"
|
|
||||||
import { normalizeAgentList } from "./utils"
|
|
||||||
|
|
||||||
const agent = (name = "build") =>
|
|
||||||
({
|
|
||||||
name,
|
|
||||||
mode: "primary",
|
|
||||||
permission: {},
|
|
||||||
options: {},
|
|
||||||
}) as Agent
|
|
||||||
|
|
||||||
describe("normalizeAgentList", () => {
|
|
||||||
test("keeps array payloads", () => {
|
|
||||||
expect(normalizeAgentList([agent("build"), agent("docs")])).toEqual([agent("build"), agent("docs")])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("wraps a single agent payload", () => {
|
|
||||||
expect(normalizeAgentList(agent("docs"))).toEqual([agent("docs")])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("extracts agents from keyed objects", () => {
|
|
||||||
expect(
|
|
||||||
normalizeAgentList({
|
|
||||||
build: agent("build"),
|
|
||||||
docs: agent("docs"),
|
|
||||||
}),
|
|
||||||
).toEqual([agent("build"), agent("docs")])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("drops invalid payloads", () => {
|
|
||||||
expect(normalizeAgentList({ name: "AbortError" })).toEqual([])
|
|
||||||
expect(normalizeAgentList([{ name: "build" }, agent("docs")])).toEqual([agent("docs")])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,21 +1,7 @@
|
|||||||
import type { Agent, Project, ProviderListResponse } from "@opencode-ai/sdk/v2/client"
|
import type { Project, ProviderListResponse } from "@opencode-ai/sdk/v2/client"
|
||||||
|
|
||||||
export const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
|
export const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
|
||||||
|
|
||||||
function isAgent(input: unknown): input is Agent {
|
|
||||||
if (!input || typeof input !== "object") return false
|
|
||||||
const item = input as { name?: unknown; mode?: unknown }
|
|
||||||
if (typeof item.name !== "string") return false
|
|
||||||
return item.mode === "subagent" || item.mode === "primary" || item.mode === "all"
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeAgentList(input: unknown): Agent[] {
|
|
||||||
if (Array.isArray(input)) return input.filter(isAgent)
|
|
||||||
if (isAgent(input)) return [input]
|
|
||||||
if (!input || typeof input !== "object") return []
|
|
||||||
return Object.values(input).filter(isAgent)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeProviderList(input: ProviderListResponse): ProviderListResponse {
|
export function normalizeProviderList(input: ProviderListResponse): ProviderListResponse {
|
||||||
return {
|
return {
|
||||||
...input,
|
...input,
|
||||||
|
|||||||
@@ -1,10 +1,42 @@
|
|||||||
import * as i18n from "@solid-primitives/i18n"
|
import * as i18n from "@solid-primitives/i18n"
|
||||||
import { createEffect, createMemo, createResource } from "solid-js"
|
import { createEffect, createMemo } from "solid-js"
|
||||||
import { createStore } from "solid-js/store"
|
import { createStore } from "solid-js/store"
|
||||||
import { createSimpleContext } from "@opencode-ai/ui/context"
|
import { createSimpleContext } from "@opencode-ai/ui/context"
|
||||||
import { Persist, persisted } from "@/utils/persist"
|
import { Persist, persisted } from "@/utils/persist"
|
||||||
import { dict as en } from "@/i18n/en"
|
import { dict as en } from "@/i18n/en"
|
||||||
|
import { dict as zh } from "@/i18n/zh"
|
||||||
|
import { dict as zht } from "@/i18n/zht"
|
||||||
|
import { dict as ko } from "@/i18n/ko"
|
||||||
|
import { dict as de } from "@/i18n/de"
|
||||||
|
import { dict as es } from "@/i18n/es"
|
||||||
|
import { dict as fr } from "@/i18n/fr"
|
||||||
|
import { dict as da } from "@/i18n/da"
|
||||||
|
import { dict as ja } from "@/i18n/ja"
|
||||||
|
import { dict as pl } from "@/i18n/pl"
|
||||||
|
import { dict as ru } from "@/i18n/ru"
|
||||||
|
import { dict as ar } from "@/i18n/ar"
|
||||||
|
import { dict as no } from "@/i18n/no"
|
||||||
|
import { dict as br } from "@/i18n/br"
|
||||||
|
import { dict as th } from "@/i18n/th"
|
||||||
|
import { dict as bs } from "@/i18n/bs"
|
||||||
|
import { dict as tr } from "@/i18n/tr"
|
||||||
import { dict as uiEn } from "@opencode-ai/ui/i18n/en"
|
import { dict as uiEn } from "@opencode-ai/ui/i18n/en"
|
||||||
|
import { dict as uiZh } from "@opencode-ai/ui/i18n/zh"
|
||||||
|
import { dict as uiZht } from "@opencode-ai/ui/i18n/zht"
|
||||||
|
import { dict as uiKo } from "@opencode-ai/ui/i18n/ko"
|
||||||
|
import { dict as uiDe } from "@opencode-ai/ui/i18n/de"
|
||||||
|
import { dict as uiEs } from "@opencode-ai/ui/i18n/es"
|
||||||
|
import { dict as uiFr } from "@opencode-ai/ui/i18n/fr"
|
||||||
|
import { dict as uiDa } from "@opencode-ai/ui/i18n/da"
|
||||||
|
import { dict as uiJa } from "@opencode-ai/ui/i18n/ja"
|
||||||
|
import { dict as uiPl } from "@opencode-ai/ui/i18n/pl"
|
||||||
|
import { dict as uiRu } from "@opencode-ai/ui/i18n/ru"
|
||||||
|
import { dict as uiAr } from "@opencode-ai/ui/i18n/ar"
|
||||||
|
import { dict as uiNo } from "@opencode-ai/ui/i18n/no"
|
||||||
|
import { dict as uiBr } from "@opencode-ai/ui/i18n/br"
|
||||||
|
import { dict as uiTh } from "@opencode-ai/ui/i18n/th"
|
||||||
|
import { dict as uiBs } from "@opencode-ai/ui/i18n/bs"
|
||||||
|
import { dict as uiTr } from "@opencode-ai/ui/i18n/tr"
|
||||||
|
|
||||||
export type Locale =
|
export type Locale =
|
||||||
| "en"
|
| "en"
|
||||||
@@ -27,7 +59,6 @@ export type Locale =
|
|||||||
|
|
||||||
type RawDictionary = typeof en & typeof uiEn
|
type RawDictionary = typeof en & typeof uiEn
|
||||||
type Dictionary = i18n.Flatten<RawDictionary>
|
type Dictionary = i18n.Flatten<RawDictionary>
|
||||||
type Source = { dict: Record<string, string> }
|
|
||||||
|
|
||||||
function cookie(locale: Locale) {
|
function cookie(locale: Locale) {
|
||||||
return `oc_locale=${encodeURIComponent(locale)}; Path=/; Max-Age=31536000; SameSite=Lax`
|
return `oc_locale=${encodeURIComponent(locale)}; Path=/; Max-Age=31536000; SameSite=Lax`
|
||||||
@@ -94,43 +125,24 @@ const LABEL_KEY: Record<Locale, keyof Dictionary> = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const base = i18n.flatten({ ...en, ...uiEn })
|
const base = i18n.flatten({ ...en, ...uiEn })
|
||||||
const dicts = new Map<Locale, Dictionary>([["en", base]])
|
const DICT: Record<Locale, Dictionary> = {
|
||||||
|
en: base,
|
||||||
const merge = (app: Promise<Source>, ui: Promise<Source>) =>
|
zh: { ...base, ...i18n.flatten({ ...zh, ...uiZh }) },
|
||||||
Promise.all([app, ui]).then(([a, b]) => ({ ...base, ...i18n.flatten({ ...a.dict, ...b.dict }) }) as Dictionary)
|
zht: { ...base, ...i18n.flatten({ ...zht, ...uiZht }) },
|
||||||
|
ko: { ...base, ...i18n.flatten({ ...ko, ...uiKo }) },
|
||||||
const loaders: Record<Exclude<Locale, "en">, () => Promise<Dictionary>> = {
|
de: { ...base, ...i18n.flatten({ ...de, ...uiDe }) },
|
||||||
zh: () => merge(import("@/i18n/zh"), import("@opencode-ai/ui/i18n/zh")),
|
es: { ...base, ...i18n.flatten({ ...es, ...uiEs }) },
|
||||||
zht: () => merge(import("@/i18n/zht"), import("@opencode-ai/ui/i18n/zht")),
|
fr: { ...base, ...i18n.flatten({ ...fr, ...uiFr }) },
|
||||||
ko: () => merge(import("@/i18n/ko"), import("@opencode-ai/ui/i18n/ko")),
|
da: { ...base, ...i18n.flatten({ ...da, ...uiDa }) },
|
||||||
de: () => merge(import("@/i18n/de"), import("@opencode-ai/ui/i18n/de")),
|
ja: { ...base, ...i18n.flatten({ ...ja, ...uiJa }) },
|
||||||
es: () => merge(import("@/i18n/es"), import("@opencode-ai/ui/i18n/es")),
|
pl: { ...base, ...i18n.flatten({ ...pl, ...uiPl }) },
|
||||||
fr: () => merge(import("@/i18n/fr"), import("@opencode-ai/ui/i18n/fr")),
|
ru: { ...base, ...i18n.flatten({ ...ru, ...uiRu }) },
|
||||||
da: () => merge(import("@/i18n/da"), import("@opencode-ai/ui/i18n/da")),
|
ar: { ...base, ...i18n.flatten({ ...ar, ...uiAr }) },
|
||||||
ja: () => merge(import("@/i18n/ja"), import("@opencode-ai/ui/i18n/ja")),
|
no: { ...base, ...i18n.flatten({ ...no, ...uiNo }) },
|
||||||
pl: () => merge(import("@/i18n/pl"), import("@opencode-ai/ui/i18n/pl")),
|
br: { ...base, ...i18n.flatten({ ...br, ...uiBr }) },
|
||||||
ru: () => merge(import("@/i18n/ru"), import("@opencode-ai/ui/i18n/ru")),
|
th: { ...base, ...i18n.flatten({ ...th, ...uiTh }) },
|
||||||
ar: () => merge(import("@/i18n/ar"), import("@opencode-ai/ui/i18n/ar")),
|
bs: { ...base, ...i18n.flatten({ ...bs, ...uiBs }) },
|
||||||
no: () => merge(import("@/i18n/no"), import("@opencode-ai/ui/i18n/no")),
|
tr: { ...base, ...i18n.flatten({ ...tr, ...uiTr }) },
|
||||||
br: () => merge(import("@/i18n/br"), import("@opencode-ai/ui/i18n/br")),
|
|
||||||
th: () => merge(import("@/i18n/th"), import("@opencode-ai/ui/i18n/th")),
|
|
||||||
bs: () => merge(import("@/i18n/bs"), import("@opencode-ai/ui/i18n/bs")),
|
|
||||||
tr: () => merge(import("@/i18n/tr"), import("@opencode-ai/ui/i18n/tr")),
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadDict(locale: Locale) {
|
|
||||||
const hit = dicts.get(locale)
|
|
||||||
if (hit) return Promise.resolve(hit)
|
|
||||||
if (locale === "en") return Promise.resolve(base)
|
|
||||||
const load = loaders[locale]
|
|
||||||
return load().then((next: Dictionary) => {
|
|
||||||
dicts.set(locale, next)
|
|
||||||
return next
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export function loadLocaleDict(locale: Locale) {
|
|
||||||
return loadDict(locale).then(() => undefined)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const localeMatchers: Array<{ locale: Locale; match: (language: string) => boolean }> = [
|
const localeMatchers: Array<{ locale: Locale; match: (language: string) => boolean }> = [
|
||||||
@@ -156,6 +168,27 @@ const localeMatchers: Array<{ locale: Locale; match: (language: string) => boole
|
|||||||
{ locale: "tr", match: (language) => language.startsWith("tr") },
|
{ locale: "tr", match: (language) => language.startsWith("tr") },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
type ParityKey = "command.session.previous.unseen" | "command.session.next.unseen"
|
||||||
|
const PARITY_CHECK: Record<Exclude<Locale, "en">, Record<ParityKey, string>> = {
|
||||||
|
zh,
|
||||||
|
zht,
|
||||||
|
ko,
|
||||||
|
de,
|
||||||
|
es,
|
||||||
|
fr,
|
||||||
|
da,
|
||||||
|
ja,
|
||||||
|
pl,
|
||||||
|
ru,
|
||||||
|
ar,
|
||||||
|
no,
|
||||||
|
br,
|
||||||
|
th,
|
||||||
|
bs,
|
||||||
|
tr,
|
||||||
|
}
|
||||||
|
void PARITY_CHECK
|
||||||
|
|
||||||
function detectLocale(): Locale {
|
function detectLocale(): Locale {
|
||||||
if (typeof navigator !== "object") return "en"
|
if (typeof navigator !== "object") return "en"
|
||||||
|
|
||||||
@@ -170,48 +203,27 @@ function detectLocale(): Locale {
|
|||||||
return "en"
|
return "en"
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeLocale(value: string): Locale {
|
function normalizeLocale(value: string): Locale {
|
||||||
return LOCALES.includes(value as Locale) ? (value as Locale) : "en"
|
return LOCALES.includes(value as Locale) ? (value as Locale) : "en"
|
||||||
}
|
}
|
||||||
|
|
||||||
function readStoredLocale() {
|
|
||||||
if (typeof localStorage !== "object") return
|
|
||||||
try {
|
|
||||||
const raw = localStorage.getItem("opencode.global.dat:language")
|
|
||||||
if (!raw) return
|
|
||||||
const next = JSON.parse(raw) as { locale?: string }
|
|
||||||
if (typeof next?.locale !== "string") return
|
|
||||||
return normalizeLocale(next.locale)
|
|
||||||
} catch {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const warm = readStoredLocale() ?? detectLocale()
|
|
||||||
if (warm !== "en") void loadDict(warm)
|
|
||||||
|
|
||||||
export const { use: useLanguage, provider: LanguageProvider } = createSimpleContext({
|
export const { use: useLanguage, provider: LanguageProvider } = createSimpleContext({
|
||||||
name: "Language",
|
name: "Language",
|
||||||
init: (props: { locale?: Locale }) => {
|
init: () => {
|
||||||
const initial = props.locale ?? readStoredLocale() ?? detectLocale()
|
|
||||||
const [store, setStore, _, ready] = persisted(
|
const [store, setStore, _, ready] = persisted(
|
||||||
Persist.global("language", ["language.v1"]),
|
Persist.global("language", ["language.v1"]),
|
||||||
createStore({
|
createStore({
|
||||||
locale: initial,
|
locale: detectLocale() as Locale,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
const locale = createMemo<Locale>(() => normalizeLocale(store.locale))
|
const locale = createMemo<Locale>(() => normalizeLocale(store.locale))
|
||||||
|
console.log("locale", locale())
|
||||||
const intl = createMemo(() => INTL[locale()])
|
const intl = createMemo(() => INTL[locale()])
|
||||||
|
|
||||||
const [dict] = createResource(locale, loadDict, {
|
const dict = createMemo<Dictionary>(() => DICT[locale()])
|
||||||
initialValue: dicts.get(initial) ?? base,
|
|
||||||
})
|
|
||||||
|
|
||||||
const t = i18n.translator(() => dict() ?? base, i18n.resolveTemplate) as (
|
const t = i18n.translator(dict, i18n.resolveTemplate)
|
||||||
key: keyof Dictionary,
|
|
||||||
params?: Record<string, string | number | boolean>,
|
|
||||||
) => string
|
|
||||||
|
|
||||||
const label = (value: Locale) => t(LABEL_KEY[value])
|
const label = (value: Locale) => t(LABEL_KEY[value])
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,7 @@ import { createScrollPersistence, type SessionScroll } from "./layout-scroll"
|
|||||||
import { createPathHelpers } from "./file/path"
|
import { createPathHelpers } from "./file/path"
|
||||||
|
|
||||||
const AVATAR_COLOR_KEYS = ["pink", "mint", "orange", "purple", "cyan", "lime"] as const
|
const AVATAR_COLOR_KEYS = ["pink", "mint", "orange", "purple", "cyan", "lime"] as const
|
||||||
const DEFAULT_SIDEBAR_WIDTH = 344
|
const DEFAULT_PANEL_WIDTH = 344
|
||||||
const DEFAULT_FILE_TREE_WIDTH = 200
|
|
||||||
const DEFAULT_SESSION_WIDTH = 600
|
const DEFAULT_SESSION_WIDTH = 600
|
||||||
const DEFAULT_TERMINAL_HEIGHT = 280
|
const DEFAULT_TERMINAL_HEIGHT = 280
|
||||||
export type AvatarColorKey = (typeof AVATAR_COLOR_KEYS)[number]
|
export type AvatarColorKey = (typeof AVATAR_COLOR_KEYS)[number]
|
||||||
@@ -162,11 +161,11 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
if (!isRecord(fileTree)) return fileTree
|
if (!isRecord(fileTree)) return fileTree
|
||||||
if (fileTree.tab === "changes" || fileTree.tab === "all") return fileTree
|
if (fileTree.tab === "changes" || fileTree.tab === "all") return fileTree
|
||||||
|
|
||||||
const width = typeof fileTree.width === "number" ? fileTree.width : DEFAULT_FILE_TREE_WIDTH
|
const width = typeof fileTree.width === "number" ? fileTree.width : DEFAULT_PANEL_WIDTH
|
||||||
return {
|
return {
|
||||||
...fileTree,
|
...fileTree,
|
||||||
opened: true,
|
opened: true,
|
||||||
width: width === 260 ? DEFAULT_FILE_TREE_WIDTH : width,
|
width: width === 260 ? DEFAULT_PANEL_WIDTH : width,
|
||||||
tab: "changes",
|
tab: "changes",
|
||||||
}
|
}
|
||||||
})()
|
})()
|
||||||
@@ -231,7 +230,7 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
createStore({
|
createStore({
|
||||||
sidebar: {
|
sidebar: {
|
||||||
opened: false,
|
opened: false,
|
||||||
width: DEFAULT_SIDEBAR_WIDTH,
|
width: DEFAULT_PANEL_WIDTH,
|
||||||
workspaces: {} as Record<string, boolean>,
|
workspaces: {} as Record<string, boolean>,
|
||||||
workspacesDefault: false,
|
workspacesDefault: false,
|
||||||
},
|
},
|
||||||
@@ -244,8 +243,8 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
panelOpened: true,
|
panelOpened: true,
|
||||||
},
|
},
|
||||||
fileTree: {
|
fileTree: {
|
||||||
opened: false,
|
opened: true,
|
||||||
width: DEFAULT_FILE_TREE_WIDTH,
|
width: DEFAULT_PANEL_WIDTH,
|
||||||
tab: "changes" as "changes" | "all",
|
tab: "changes" as "changes" | "all",
|
||||||
},
|
},
|
||||||
session: {
|
session: {
|
||||||
@@ -544,26 +543,12 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
let sessionFrame: number | undefined
|
|
||||||
let sessionTimer: number | undefined
|
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
sessionFrame = requestAnimationFrame(() => {
|
Promise.all(
|
||||||
sessionFrame = undefined
|
server.projects.list().map((project) => {
|
||||||
sessionTimer = window.setTimeout(() => {
|
return globalSync.project.loadSessions(project.worktree)
|
||||||
sessionTimer = undefined
|
}),
|
||||||
void Promise.all(
|
)
|
||||||
server.projects.list().map((project) => {
|
|
||||||
return globalSync.project.loadSessions(project.worktree)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}, 0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
onCleanup(() => {
|
|
||||||
if (sessionFrame !== undefined) cancelAnimationFrame(sessionFrame)
|
|
||||||
if (sessionTimer !== undefined) window.clearTimeout(sessionTimer)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -643,32 +628,32 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
|
|||||||
},
|
},
|
||||||
fileTree: {
|
fileTree: {
|
||||||
opened: createMemo(() => store.fileTree?.opened ?? true),
|
opened: createMemo(() => store.fileTree?.opened ?? true),
|
||||||
width: createMemo(() => store.fileTree?.width ?? DEFAULT_FILE_TREE_WIDTH),
|
width: createMemo(() => store.fileTree?.width ?? DEFAULT_PANEL_WIDTH),
|
||||||
tab: createMemo(() => store.fileTree?.tab ?? "changes"),
|
tab: createMemo(() => store.fileTree?.tab ?? "changes"),
|
||||||
setTab(tab: "changes" | "all") {
|
setTab(tab: "changes" | "all") {
|
||||||
if (!store.fileTree) {
|
if (!store.fileTree) {
|
||||||
setStore("fileTree", { opened: true, width: DEFAULT_FILE_TREE_WIDTH, tab })
|
setStore("fileTree", { opened: true, width: DEFAULT_PANEL_WIDTH, tab })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setStore("fileTree", "tab", tab)
|
setStore("fileTree", "tab", tab)
|
||||||
},
|
},
|
||||||
open() {
|
open() {
|
||||||
if (!store.fileTree) {
|
if (!store.fileTree) {
|
||||||
setStore("fileTree", { opened: true, width: DEFAULT_FILE_TREE_WIDTH, tab: "changes" })
|
setStore("fileTree", { opened: true, width: DEFAULT_PANEL_WIDTH, tab: "changes" })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setStore("fileTree", "opened", true)
|
setStore("fileTree", "opened", true)
|
||||||
},
|
},
|
||||||
close() {
|
close() {
|
||||||
if (!store.fileTree) {
|
if (!store.fileTree) {
|
||||||
setStore("fileTree", { opened: false, width: DEFAULT_FILE_TREE_WIDTH, tab: "changes" })
|
setStore("fileTree", { opened: false, width: DEFAULT_PANEL_WIDTH, tab: "changes" })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setStore("fileTree", "opened", false)
|
setStore("fileTree", "opened", false)
|
||||||
},
|
},
|
||||||
toggle() {
|
toggle() {
|
||||||
if (!store.fileTree) {
|
if (!store.fileTree) {
|
||||||
setStore("fileTree", { opened: true, width: DEFAULT_FILE_TREE_WIDTH, tab: "changes" })
|
setStore("fileTree", { opened: true, width: DEFAULT_PANEL_WIDTH, tab: "changes" })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setStore("fileTree", "opened", (x) => !x)
|
setStore("fileTree", "opened", (x) => !x)
|
||||||
|
|||||||
@@ -390,18 +390,10 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (modelEnabled()) {
|
if (modelEnabled()) {
|
||||||
const probe = Symbol("model-probe")
|
|
||||||
|
|
||||||
modelProbe.bind(probe, {
|
|
||||||
setAgent: agent.set,
|
|
||||||
setModel: model.set,
|
|
||||||
setVariant: model.variant.set,
|
|
||||||
})
|
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
const agent = result.agent.current()
|
const agent = result.agent.current()
|
||||||
const model = result.model.current()
|
const model = result.model.current()
|
||||||
modelProbe.set(probe, {
|
modelProbe.set({
|
||||||
dir: sdk.directory,
|
dir: sdk.directory,
|
||||||
sessionID: id(),
|
sessionID: id(),
|
||||||
last: store.last,
|
last: store.last,
|
||||||
@@ -419,20 +411,10 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
|
|||||||
pick: scope(),
|
pick: scope(),
|
||||||
base: undefined,
|
base: undefined,
|
||||||
current: store.current,
|
current: store.current,
|
||||||
variants: result.model.variant.list(),
|
|
||||||
models: result.model
|
|
||||||
.list()
|
|
||||||
.filter((item) => result.model.visible({ providerID: item.provider.id, modelID: item.id }))
|
|
||||||
.map((item) => ({
|
|
||||||
providerID: item.provider.id,
|
|
||||||
modelID: item.id,
|
|
||||||
name: item.name,
|
|
||||||
})),
|
|
||||||
agents: result.agent.list().map((item) => ({ name: item.name })),
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
onCleanup(() => modelProbe.clear(probe))
|
onCleanup(() => modelProbe.clear())
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import { base64Encode } from "@opencode-ai/util/encode"
|
|||||||
import { decode64 } from "@/utils/base64"
|
import { decode64 } from "@/utils/base64"
|
||||||
import { EventSessionError } from "@opencode-ai/sdk/v2"
|
import { EventSessionError } from "@opencode-ai/sdk/v2"
|
||||||
import { Persist, persisted } from "@/utils/persist"
|
import { Persist, persisted } from "@/utils/persist"
|
||||||
import { playSoundById } from "@/utils/sound"
|
import { playSound, soundSrc } from "@/utils/sound"
|
||||||
|
|
||||||
type NotificationBase = {
|
type NotificationBase = {
|
||||||
directory?: string
|
directory?: string
|
||||||
@@ -234,7 +234,7 @@ export const { use: useNotification, provider: NotificationProvider } = createSi
|
|||||||
if (session.parentID) return
|
if (session.parentID) return
|
||||||
|
|
||||||
if (settings.sounds.agentEnabled()) {
|
if (settings.sounds.agentEnabled()) {
|
||||||
void playSoundById(settings.sounds.agent())
|
playSound(soundSrc(settings.sounds.agent()))
|
||||||
}
|
}
|
||||||
|
|
||||||
append({
|
append({
|
||||||
@@ -263,7 +263,7 @@ export const { use: useNotification, provider: NotificationProvider } = createSi
|
|||||||
if (session?.parentID) return
|
if (session?.parentID) return
|
||||||
|
|
||||||
if (settings.sounds.errorsEnabled()) {
|
if (settings.sounds.errorsEnabled()) {
|
||||||
void playSoundById(settings.sounds.errors())
|
playSound(soundSrc(settings.sounds.errors()))
|
||||||
}
|
}
|
||||||
|
|
||||||
const error = "error" in event.properties ? event.properties.error : undefined
|
const error = "error" in event.properties ? event.properties.error : undefined
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { ServerConnection } from "./server"
|
|||||||
|
|
||||||
type PickerPaths = string | string[] | null
|
type PickerPaths = string | string[] | null
|
||||||
type OpenDirectoryPickerOptions = { title?: string; multiple?: boolean }
|
type OpenDirectoryPickerOptions = { title?: string; multiple?: boolean }
|
||||||
type OpenFilePickerOptions = { title?: string; multiple?: boolean; accept?: string[]; extensions?: string[] }
|
type OpenFilePickerOptions = { title?: string; multiple?: boolean }
|
||||||
type SaveFilePickerOptions = { title?: string; defaultPath?: string }
|
type SaveFilePickerOptions = { title?: string; defaultPath?: string }
|
||||||
type UpdateInfo = { updateAvailable: boolean; version?: string }
|
type UpdateInfo = { updateAvailable: boolean; version?: string }
|
||||||
|
|
||||||
|
|||||||
@@ -94,11 +94,7 @@ export namespace ServerConnection {
|
|||||||
|
|
||||||
export const { use: useServer, provider: ServerProvider } = createSimpleContext({
|
export const { use: useServer, provider: ServerProvider } = createSimpleContext({
|
||||||
name: "Server",
|
name: "Server",
|
||||||
init: (props: {
|
init: (props: { defaultServer: ServerConnection.Key; servers?: Array<ServerConnection.Any> }) => {
|
||||||
defaultServer: ServerConnection.Key
|
|
||||||
disableHealthCheck?: boolean
|
|
||||||
servers?: Array<ServerConnection.Any>
|
|
||||||
}) => {
|
|
||||||
const checkServerHealth = useCheckServerHealth()
|
const checkServerHealth = useCheckServerHealth()
|
||||||
|
|
||||||
const [store, setStore, _, ready] = persisted(
|
const [store, setStore, _, ready] = persisted(
|
||||||
@@ -206,10 +202,6 @@ export const { use: useServer, provider: ServerProvider } = createSimpleContext(
|
|||||||
const current_ = current()
|
const current_ = current()
|
||||||
if (!current_) return
|
if (!current_) return
|
||||||
|
|
||||||
if (props.disableHealthCheck) {
|
|
||||||
setState("healthy", true)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setState("healthy", undefined)
|
setState("healthy", undefined)
|
||||||
onCleanup(startHealthPolling(current_))
|
onCleanup(startHealthPolling(current_))
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -32,8 +32,7 @@ export interface Settings {
|
|||||||
}
|
}
|
||||||
appearance: {
|
appearance: {
|
||||||
fontSize: number
|
fontSize: number
|
||||||
mono: string
|
font: string
|
||||||
sans: string
|
|
||||||
}
|
}
|
||||||
keybinds: Record<string, string>
|
keybinds: Record<string, string>
|
||||||
permissions: {
|
permissions: {
|
||||||
@@ -43,54 +42,13 @@ export interface Settings {
|
|||||||
sounds: SoundSettings
|
sounds: SoundSettings
|
||||||
}
|
}
|
||||||
|
|
||||||
export const monoDefault = "System Mono"
|
|
||||||
export const sansDefault = "System Sans"
|
|
||||||
|
|
||||||
const monoFallback =
|
|
||||||
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'
|
|
||||||
const sansFallback = 'ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'
|
|
||||||
|
|
||||||
const monoBase = monoFallback
|
|
||||||
const sansBase = sansFallback
|
|
||||||
|
|
||||||
function input(font: string | undefined) {
|
|
||||||
return font ?? ""
|
|
||||||
}
|
|
||||||
|
|
||||||
function family(font: string) {
|
|
||||||
if (/^[\w-]+$/.test(font)) return font
|
|
||||||
return `"${font.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
|
|
||||||
}
|
|
||||||
|
|
||||||
function stack(font: string | undefined, base: string) {
|
|
||||||
const value = font?.trim() ?? ""
|
|
||||||
if (!value) return base
|
|
||||||
return `${family(value)}, ${base}`
|
|
||||||
}
|
|
||||||
|
|
||||||
export function monoInput(font: string | undefined) {
|
|
||||||
return input(font)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function sansInput(font: string | undefined) {
|
|
||||||
return input(font)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function monoFontFamily(font: string | undefined) {
|
|
||||||
return stack(font, monoBase)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function sansFontFamily(font: string | undefined) {
|
|
||||||
return stack(font, sansBase)
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaultSettings: Settings = {
|
const defaultSettings: Settings = {
|
||||||
general: {
|
general: {
|
||||||
autoSave: true,
|
autoSave: true,
|
||||||
releaseNotes: true,
|
releaseNotes: true,
|
||||||
followup: "steer",
|
followup: "steer",
|
||||||
showReasoningSummaries: false,
|
showReasoningSummaries: false,
|
||||||
shellToolPartsExpanded: false,
|
shellToolPartsExpanded: true,
|
||||||
editToolPartsExpanded: false,
|
editToolPartsExpanded: false,
|
||||||
},
|
},
|
||||||
updates: {
|
updates: {
|
||||||
@@ -98,8 +56,7 @@ const defaultSettings: Settings = {
|
|||||||
},
|
},
|
||||||
appearance: {
|
appearance: {
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
mono: "",
|
font: "ibm-plex-mono",
|
||||||
sans: "",
|
|
||||||
},
|
},
|
||||||
keybinds: {},
|
keybinds: {},
|
||||||
permissions: {
|
permissions: {
|
||||||
@@ -120,6 +77,29 @@ const defaultSettings: Settings = {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const monoFallback =
|
||||||
|
'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'
|
||||||
|
|
||||||
|
const monoFonts: Record<string, string> = {
|
||||||
|
"ibm-plex-mono": `"IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"cascadia-code": `"Cascadia Code Nerd Font", "Cascadia Code NF", "Cascadia Mono NF", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"fira-code": `"Fira Code Nerd Font", "FiraMono Nerd Font", "FiraMono Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
hack: `"Hack Nerd Font", "Hack Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
inconsolata: `"Inconsolata Nerd Font", "Inconsolata Nerd Font Mono","IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"intel-one-mono": `"Intel One Mono Nerd Font", "IntoneMono Nerd Font", "IntoneMono Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
iosevka: `"Iosevka Nerd Font", "Iosevka Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"jetbrains-mono": `"JetBrains Mono Nerd Font", "JetBrainsMono Nerd Font Mono", "JetBrainsMonoNL Nerd Font", "JetBrainsMonoNL Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"meslo-lgs": `"Meslo LGS Nerd Font", "MesloLGS Nerd Font", "MesloLGM Nerd Font", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"roboto-mono": `"Roboto Mono Nerd Font", "RobotoMono Nerd Font", "RobotoMono Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"source-code-pro": `"Source Code Pro Nerd Font", "SauceCodePro Nerd Font", "SauceCodePro Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"ubuntu-mono": `"Ubuntu Mono Nerd Font", "UbuntuMono Nerd Font", "UbuntuMono Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
"geist-mono": `"GeistMono Nerd Font", "GeistMono Nerd Font Mono", "IBM Plex Mono", "IBM Plex Mono Fallback", ${monoFallback}`,
|
||||||
|
}
|
||||||
|
|
||||||
|
export function monoFontFamily(font: string | undefined) {
|
||||||
|
return monoFonts[font ?? defaultSettings.appearance.font] ?? monoFonts[defaultSettings.appearance.font]
|
||||||
|
}
|
||||||
|
|
||||||
function withFallback<T>(read: () => T | undefined, fallback: T) {
|
function withFallback<T>(read: () => T | undefined, fallback: T) {
|
||||||
return createMemo(() => read() ?? fallback)
|
return createMemo(() => read() ?? fallback)
|
||||||
}
|
}
|
||||||
@@ -131,9 +111,7 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
|||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
if (typeof document === "undefined") return
|
if (typeof document === "undefined") return
|
||||||
const root = document.documentElement
|
document.documentElement.style.setProperty("--font-family-mono", monoFontFamily(store.appearance?.font))
|
||||||
root.style.setProperty("--font-family-mono", monoFontFamily(store.appearance?.mono))
|
|
||||||
root.style.setProperty("--font-family-sans", sansFontFamily(store.appearance?.sans))
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -187,13 +165,9 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
|||||||
setFontSize(value: number) {
|
setFontSize(value: number) {
|
||||||
setStore("appearance", "fontSize", value)
|
setStore("appearance", "fontSize", value)
|
||||||
},
|
},
|
||||||
font: withFallback(() => store.appearance?.mono, defaultSettings.appearance.mono),
|
font: withFallback(() => store.appearance?.font, defaultSettings.appearance.font),
|
||||||
setFont(value: string) {
|
setFont(value: string) {
|
||||||
setStore("appearance", "mono", value.trim() ? value : "")
|
setStore("appearance", "font", value)
|
||||||
},
|
|
||||||
uiFont: withFallback(() => store.appearance?.sans, defaultSettings.appearance.sans),
|
|
||||||
setUIFont(value: string) {
|
|
||||||
setStore("appearance", "sans", value.trim() ? value : "")
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
keybinds: {
|
keybinds: {
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ import { useSDK } from "./sdk"
|
|||||||
import type { Message, Part } from "@opencode-ai/sdk/v2/client"
|
import type { Message, Part } from "@opencode-ai/sdk/v2/client"
|
||||||
import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
|
import { SESSION_CACHE_LIMIT, dropSessionCaches, pickSessionCacheEvictions } from "./global-sync/session-cache"
|
||||||
|
|
||||||
const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"])
|
|
||||||
|
|
||||||
function sortParts(parts: Part[]) {
|
function sortParts(parts: Part[]) {
|
||||||
return parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id))
|
return parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id))
|
||||||
}
|
}
|
||||||
@@ -180,8 +178,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||||||
return globalSync.child(directory)
|
return globalSync.child(directory)
|
||||||
}
|
}
|
||||||
const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
|
const absolute = (path: string) => (current()[0].path.directory + "/" + path).replace("//", "/")
|
||||||
const initialMessagePageSize = 80
|
const messagePageSize = 200
|
||||||
const historyMessagePageSize = 200
|
|
||||||
const inflight = new Map<string, Promise<void>>()
|
const inflight = new Map<string, Promise<void>>()
|
||||||
const inflightDiff = new Map<string, Promise<void>>()
|
const inflightDiff = new Map<string, Promise<void>>()
|
||||||
const inflightTodo = new Map<string, Promise<void>>()
|
const inflightTodo = new Map<string, Promise<void>>()
|
||||||
@@ -339,8 +336,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||||||
batch(() => {
|
batch(() => {
|
||||||
input.setStore("message", input.sessionID, reconcile(message, { key: "id" }))
|
input.setStore("message", input.sessionID, reconcile(message, { key: "id" }))
|
||||||
for (const p of next.part) {
|
for (const p of next.part) {
|
||||||
const filtered = p.part.filter((x) => !SKIP_PARTS.has(x.type))
|
input.setStore("part", p.id, p.part)
|
||||||
if (filtered.length) input.setStore("part", p.id, filtered)
|
|
||||||
}
|
}
|
||||||
setMeta("limit", key, message.length)
|
setMeta("limit", key, message.length)
|
||||||
setMeta("cursor", key, next.cursor)
|
setMeta("cursor", key, next.cursor)
|
||||||
@@ -464,7 +460,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||||||
const cached = store.message[sessionID] !== undefined && meta.limit[key] !== undefined
|
const cached = store.message[sessionID] !== undefined && meta.limit[key] !== undefined
|
||||||
if (cached && hasSession && !opts?.force) return
|
if (cached && hasSession && !opts?.force) return
|
||||||
|
|
||||||
const limit = meta.limit[key] ?? initialMessagePageSize
|
const limit = meta.limit[key] ?? messagePageSize
|
||||||
const sessionReq =
|
const sessionReq =
|
||||||
hasSession && !opts?.force
|
hasSession && !opts?.force
|
||||||
? Promise.resolve()
|
? Promise.resolve()
|
||||||
@@ -561,7 +557,7 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||||||
const [, setStore] = globalSync.child(directory)
|
const [, setStore] = globalSync.child(directory)
|
||||||
touch(directory, setStore, sessionID)
|
touch(directory, setStore, sessionID)
|
||||||
const key = keyFor(directory, sessionID)
|
const key = keyFor(directory, sessionID)
|
||||||
const step = count ?? historyMessagePageSize
|
const step = count ?? messagePageSize
|
||||||
if (meta.loading[key]) return
|
if (meta.loading[key]) return
|
||||||
if (meta.complete[key]) return
|
if (meta.complete[key]) return
|
||||||
const before = meta.cursor[key]
|
const before = meta.cursor[key]
|
||||||
|
|||||||
@@ -1,18 +1,45 @@
|
|||||||
const template = "Terminal {{number}}"
|
import { dict as ar } from "@/i18n/ar"
|
||||||
|
import { dict as br } from "@/i18n/br"
|
||||||
|
import { dict as bs } from "@/i18n/bs"
|
||||||
|
import { dict as da } from "@/i18n/da"
|
||||||
|
import { dict as de } from "@/i18n/de"
|
||||||
|
import { dict as en } from "@/i18n/en"
|
||||||
|
import { dict as es } from "@/i18n/es"
|
||||||
|
import { dict as fr } from "@/i18n/fr"
|
||||||
|
import { dict as ja } from "@/i18n/ja"
|
||||||
|
import { dict as ko } from "@/i18n/ko"
|
||||||
|
import { dict as no } from "@/i18n/no"
|
||||||
|
import { dict as pl } from "@/i18n/pl"
|
||||||
|
import { dict as ru } from "@/i18n/ru"
|
||||||
|
import { dict as th } from "@/i18n/th"
|
||||||
|
import { dict as tr } from "@/i18n/tr"
|
||||||
|
import { dict as zh } from "@/i18n/zh"
|
||||||
|
import { dict as zht } from "@/i18n/zht"
|
||||||
|
|
||||||
const numbered = [
|
const numbered = Array.from(
|
||||||
template,
|
new Set([
|
||||||
"محطة طرفية {{number}}",
|
en["terminal.title.numbered"],
|
||||||
"Терминал {{number}}",
|
ar["terminal.title.numbered"],
|
||||||
"ターミナル {{number}}",
|
br["terminal.title.numbered"],
|
||||||
"터미널 {{number}}",
|
bs["terminal.title.numbered"],
|
||||||
"เทอร์มินัล {{number}}",
|
da["terminal.title.numbered"],
|
||||||
"终端 {{number}}",
|
de["terminal.title.numbered"],
|
||||||
"終端機 {{number}}",
|
es["terminal.title.numbered"],
|
||||||
]
|
fr["terminal.title.numbered"],
|
||||||
|
ja["terminal.title.numbered"],
|
||||||
|
ko["terminal.title.numbered"],
|
||||||
|
no["terminal.title.numbered"],
|
||||||
|
pl["terminal.title.numbered"],
|
||||||
|
ru["terminal.title.numbered"],
|
||||||
|
th["terminal.title.numbered"],
|
||||||
|
tr["terminal.title.numbered"],
|
||||||
|
zh["terminal.title.numbered"],
|
||||||
|
zht["terminal.title.numbered"],
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
|
||||||
export function defaultTitle(number: number) {
|
export function defaultTitle(number: number) {
|
||||||
return template.replace("{{number}}", String(number))
|
return en["terminal.title.numbered"].replace("{{number}}", String(number))
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isDefaultTitle(title: string, number: number) {
|
export function isDefaultTitle(title: string, number: number) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user