Compare commits

..

82 Commits

Author SHA1 Message Date
Adam 3b2a33f5ed fix(app): persist quota 2026-01-19 14:41:24 -06:00
GitHub Action 2bdc385b7c chore: format code 2026-01-19 14:25:33 -06:00
David Hill 40c48b48ae wip: tabs in focus and accept left and right 2026-01-19 14:18:50 -06:00
David Hill b383026d38 fix: indicator widths 2026-01-19 14:18:50 -06:00
David Hill aeb89297ac wip: dropdown position fix 2026-01-19 14:18:50 -06:00
David Hill 8cab430199 wip: responsiveness to keyboard shortcuts panel 2026-01-19 14:17:04 -06:00
David Hill 7050bdd43a wip: keyboard shortcuts 2026-01-19 14:17:04 -06:00
David Hill 3ff6ce5967 wip: polish to shortcuts 2026-01-19 14:16:26 -06:00
David Hill 0f398e612f wip: shortcuts panel 2026-01-19 14:10:26 -06:00
David Hill dad5dbc1cc wip: new release modal
- highlight key updates or new features
- needs some transition love
- all copy including text and video placeholder
2026-01-19 14:01:18 -06:00
David Hill 13446cf8cc wip: start screen opencode tips
show a tip on the start screen from a list of 101 opencode tips
2026-01-19 13:55:24 -06:00
David Hill ed3ac35581 fix: search clear icon 2026-01-19 13:53:28 -06:00
Adam c2f9fd5fef fix(app): reload instance after workspace reset 2026-01-19 12:44:41 -06:00
Aiden Cline 3fd0043d19 chore: handle fields other than reasoning_content in interleaved block 2026-01-19 12:18:17 -06:00
Adam 092428633f fix(app): layout jumping 2026-01-19 11:44:20 -06:00
Adam fc50b2962c fix(app): make terminal sessions scoped to workspace 2026-01-19 11:28:24 -06:00
Aiden Cline dd0906be8c tweak: apply patch description 2026-01-19 11:22:00 -06:00
David Hill b72a00eaa3 fix text field border showing through focus ring 2026-01-19 17:10:27 +00:00
David Hill 2dbdd18483 add hover overlay with upload/trash icons to project icon in edit dialog 2026-01-19 17:10:27 +00:00
David Hill b0794172bf update: tighten edit project color spacing 2026-01-19 17:10:27 +00:00
David Hill 9fbf2e72b4 update: constrain edit project dialog width 2026-01-19 17:10:27 +00:00
David Hill 494e8d5be9 update: tweak edit project icon container 2026-01-19 17:10:27 +00:00
David Hill e12b94d91a update: adjust edit project icon helper text 2026-01-19 17:10:27 +00:00
David Hill 89be504abc update: align edit project dialog padding and avatar styles 2026-01-19 17:10:27 +00:00
David Hill c7f0cb3d2d fix: remove focus outline from dropdown menu 2026-01-19 17:10:26 +00:00
Adam eb779a7cc5 chore: cleanup 2026-01-19 10:55:57 -06:00
Adam c720a2163c chore: cleanup 2026-01-19 10:55:57 -06:00
Adam 7811e01c8e fix(app): new layout improvements 2026-01-19 10:55:57 -06:00
Adam befd0f1636 feat(app): new session layout 2026-01-19 10:55:57 -06:00
Adam 1f11a8a6ea feat(app): improved session layout 2026-01-19 10:55:57 -06:00
Goni Zahavy d5ae8e0bef fix(opencode): cargo fmt is formatting whole workspace instead of edited file (#9436) 2026-01-19 10:48:59 -06:00
GitHub Action 453417ed47 chore: generate 2026-01-19 16:46:09 +00:00
Joseph Campuzano 72cb7ccc00 fix(app): list component jumping when mouse happens to be under the list and keyboard navigating. (#9435) 2026-01-19 10:43:27 -06:00
Adam 4ee540309f fix(app): hide settings button 2026-01-19 10:26:21 -06:00
Aiden Cline 5b86724632 fix: cargo fmt actually does not support formatting single files 2026-01-19 10:15:32 -06:00
paulclou b1684f3d12 fix(config): rename uv formatter from 'uv format' to 'uv' for config consistency (#9409)
Co-authored-by: Paul C. Lou <paul@exig.ai>
2026-01-19 09:59:51 -06:00
Vladimir Glafirov 29e206b6c6 docs: Improve Gitlab self-hosted instances documentation (#9391) 2026-01-19 09:51:27 -06:00
Evgenii Kosenko 31864cadb4 docs: update codecompanion.nvim acp doc (#9411) 2026-01-19 09:50:41 -06:00
Frank 843d76191e zen: fix black reset date 2026-01-19 10:12:50 -05:00
Github Action 3186e7ec7c Update node_modules hashes 2026-01-19 09:03:52 -06:00
Adam 1ba7c606e6 chore: cleanup 2026-01-19 09:03:52 -06:00
Adam f00f18b926 chore: cleanup 2026-01-19 09:03:52 -06:00
Adam e9ede70793 chore: cleanup 2026-01-19 09:03:52 -06:00
Adam 2b086f0584 test(app): more e2e tests 2026-01-19 09:03:52 -06:00
Adam b90315bc7e chore: cleanup 2026-01-19 09:03:52 -06:00
Adam 182c43a78f chore: cleanup 2026-01-19 09:03:52 -06:00
Adam f1daf3b430 fix(app): tests in ci 2026-01-19 09:03:52 -06:00
Adam dd19c3d8f2 test(app): e2e utilities 2026-01-19 09:03:52 -06:00
Github Action f5eb90514a Update node_modules hash (aarch64-darwin) 2026-01-19 09:03:52 -06:00
Github Action 6bc823bd40 Update node_modules hash (x86_64-linux) 2026-01-19 09:03:52 -06:00
Github Action 7621c5cafb Update flake.lock 2026-01-19 09:03:52 -06:00
Adam 91a708b12e test(app): more e2e tests 2026-01-19 09:03:52 -06:00
Adam 19d15ca4df test(app): more e2e tests 2026-01-19 09:03:52 -06:00
Adam 03d7467ea2 test(app): initial e2e test setup 2026-01-19 09:03:52 -06:00
GitHub Action 23e9c02a7f chore: generate 2026-01-19 13:37:19 +00:00
Adam 51804a47e9 chore: cleanup 2026-01-19 07:35:52 -06:00
Adam 55739b7aa1 chore: cleanup 2026-01-19 07:35:52 -06:00
Adam 295f290efd chore: cleanup 2026-01-19 07:35:52 -06:00
Adam 1a262c4ca8 chore: cleanup 2026-01-19 07:35:52 -06:00
Adam dca2540ca7 chore: cleanup 2026-01-19 07:35:52 -06:00
Adam fcfe6d3d26 chore: cleanup 2026-01-19 07:35:52 -06:00
Adam 093a3e7876 feat(app): reset worktree 2026-01-19 07:35:52 -06:00
Adam f26de6c52f feat(app): delete workspace 2026-01-19 07:35:52 -06:00
GitHub Action 06d03dec3b ignore: update download stats 2026-01-19 2026-01-19 12:05:55 +00:00
Mani Sundararajan 08005d755b refactor(desktop): tweak share button to prevent layout shift (#9322) 2026-01-19 04:34:40 -06:00
Slone 13276aee82 fix(desktop): apply getComputedStyle polyfill on all platforms (#9369) 2026-01-19 04:32:41 -06:00
Aiden Cline 4299450d7d tweak apply_patch tool description 2026-01-19 01:31:30 -06:00
Aiden Cline 3515b4ff7d omit todo tools for openai models 2026-01-19 01:06:26 -06:00
Aiden Cline 4a7809f600 add proper variant support to copilot 2026-01-19 00:18:42 -06:00
GitHub Action 9d1803d000 chore: generate 2026-01-19 06:14:40 +00:00
Caleb Norton 91787ceb3e fix: nix ci - swapped dash/underscore (#9352) 2026-01-19 00:14:14 -06:00
Aiden Cline 86df915df0 chore: cleanup provider code to assign copilot sdk earlier in flow 2026-01-19 00:13:58 -06:00
GitHub Action 6f847a794b chore: generate 2026-01-19 06:12:36 +00:00
NateSmyth 260ab60c0b fix: track reasoning by output_index for copilot compatibility (#9124)
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
2026-01-19 00:11:54 -06:00
Aiden Cline e2f1f4d81e add scheduler, cleanup module (#9346) 2026-01-18 23:33:23 -06:00
Christopher Tso fc6c9cbbd2 fix(github-copilot): auto-route GPT-5+ models to Responses API (#5877)
Co-authored-by: Claude <noreply@anthropic.com>
2026-01-18 23:30:28 -06:00
Thiago Malek 6b481b5fb0 fix(opencode): use streamObject when using openai oauth in agent generation (#9231) 2026-01-18 23:22:31 -06:00
Caleb Norton 2fc4ab9687 ci: simplify nix hash updates (#9309) 2026-01-18 21:46:00 -06:00
Luke Parker d939a3ad54 feat(tui): use mouse for permission buttons (#9305) 2026-01-18 21:42:10 -06:00
Frank bee2f65409 zen: fix checkout link for black users 2026-01-18 19:19:00 -05:00
Luke Parker e81bb86795 fix: Windows evaluating text on copy (#9293) 2026-01-18 17:27:30 -06:00
Alan Pogrebinschi b4d4a1ea7d docs: clarify agent tool access and explore vs general distinction (#9300) 2026-01-18 16:46:04 -06:00
96 changed files with 3813 additions and 1081 deletions
+65
View File
@@ -18,6 +18,54 @@ jobs:
- name: Setup Bun
uses: ./.github/actions/setup-bun
- name: Install Playwright browsers
working-directory: packages/app
run: bunx playwright install --with-deps
- name: Seed opencode data
working-directory: packages/opencode
run: bun script/seed-e2e.ts
env:
MODELS_DEV_API_JSON: ${{ github.workspace }}/packages/opencode/test/tool/fixtures/models-api.json
OPENCODE_DISABLE_MODELS_FETCH: "true"
OPENCODE_DISABLE_SHARE: "true"
OPENCODE_DISABLE_LSP_DOWNLOAD: "true"
OPENCODE_DISABLE_DEFAULT_PLUGINS: "true"
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: "true"
OPENCODE_TEST_HOME: ${{ runner.temp }}/opencode-e2e/home
XDG_DATA_HOME: ${{ runner.temp }}/opencode-e2e/share
XDG_CACHE_HOME: ${{ runner.temp }}/opencode-e2e/cache
XDG_CONFIG_HOME: ${{ runner.temp }}/opencode-e2e/config
XDG_STATE_HOME: ${{ runner.temp }}/opencode-e2e/state
OPENCODE_E2E_PROJECT_DIR: ${{ github.workspace }}
OPENCODE_E2E_SESSION_TITLE: "E2E Session"
OPENCODE_E2E_MESSAGE: "Seeded for UI e2e"
OPENCODE_E2E_MODEL: "opencode/gpt-5-nano"
- name: Run opencode server
run: bun run dev -- --print-logs --log-level WARN serve --port 4096 --hostname 0.0.0.0 &
env:
MODELS_DEV_API_JSON: ${{ github.workspace }}/packages/opencode/test/tool/fixtures/models-api.json
OPENCODE_DISABLE_MODELS_FETCH: "true"
OPENCODE_DISABLE_SHARE: "true"
OPENCODE_DISABLE_LSP_DOWNLOAD: "true"
OPENCODE_DISABLE_DEFAULT_PLUGINS: "true"
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: "true"
OPENCODE_TEST_HOME: ${{ runner.temp }}/opencode-e2e/home
XDG_DATA_HOME: ${{ runner.temp }}/opencode-e2e/share
XDG_CACHE_HOME: ${{ runner.temp }}/opencode-e2e/cache
XDG_CONFIG_HOME: ${{ runner.temp }}/opencode-e2e/config
XDG_STATE_HOME: ${{ runner.temp }}/opencode-e2e/state
OPENCODE_CLIENT: "app"
- name: Wait for opencode server
run: |
for i in {1..60}; do
curl -fsS "http://localhost:4096/global/health" > /dev/null && exit 0
sleep 1
done
exit 1
- name: run
run: |
git config --global user.email "bot@opencode.ai"
@@ -26,3 +74,20 @@ jobs:
bun turbo test
env:
CI: true
MODELS_DEV_API_JSON: ${{ github.workspace }}/packages/opencode/test/tool/fixtures/models-api.json
OPENCODE_DISABLE_MODELS_FETCH: "true"
OPENCODE_DISABLE_SHARE: "true"
OPENCODE_DISABLE_LSP_DOWNLOAD: "true"
OPENCODE_DISABLE_DEFAULT_PLUGINS: "true"
OPENCODE_EXPERIMENTAL_DISABLE_FILEWATCHER: "true"
OPENCODE_TEST_HOME: ${{ runner.temp }}/opencode-e2e/home
XDG_DATA_HOME: ${{ runner.temp }}/opencode-e2e/share
XDG_CACHE_HOME: ${{ runner.temp }}/opencode-e2e/cache
XDG_CONFIG_HOME: ${{ runner.temp }}/opencode-e2e/config
XDG_STATE_HOME: ${{ runner.temp }}/opencode-e2e/state
PLAYWRIGHT_SERVER_HOST: "localhost"
PLAYWRIGHT_SERVER_PORT: "4096"
VITE_OPENCODE_SERVER_HOST: "localhost"
VITE_OPENCODE_SERVER_PORT: "4096"
OPENCODE_CLIENT: "app"
timeout-minutes: 30
+29 -144
View File
@@ -10,129 +10,18 @@ on:
- "bun.lock"
- "package.json"
- "packages/*/package.json"
- "flake.lock"
- ".github/workflows/update-nix-hashes.yml"
pull_request:
paths:
- "bun.lock"
- "package.json"
- "packages/*/package.json"
- "flake.lock"
- ".github/workflows/update-nix-hashes.yml"
jobs:
compute-node-modules-hash:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
strategy:
fail-fast: false
matrix:
include:
- system: x86_64-linux
host: blacksmith-4vcpu-ubuntu-2404
- system: aarch64-linux
host: blacksmith-4vcpu-ubuntu-2404-arm
- system: x86_64-darwin
host: macos-15-intel
- system: aarch64-darwin
host: macos-latest
runs-on: ${{ matrix.host }}
env:
SYSTEM: ${{ matrix.system }}
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ github.head_ref || github.ref_name }}
repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
- name: Setup Nix
uses: nixbuild/nix-quick-install-action@v34
- name: Compute node_modules hash
run: |
set -euo pipefail
DUMMY="sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
HASH_FILE="nix/hashes.json"
OUTPUT_FILE="hash-${SYSTEM}.txt"
export NIX_KEEP_OUTPUTS=1
export NIX_KEEP_DERIVATIONS=1
BUILD_LOG=$(mktemp)
TMP_JSON=$(mktemp)
trap 'rm -f "$BUILD_LOG" "$TMP_JSON"' EXIT
if [ ! -f "$HASH_FILE" ]; then
mkdir -p "$(dirname "$HASH_FILE")"
echo '{"nodeModules":{}}' > "$HASH_FILE"
fi
# Set dummy hash to force nix to rebuild and reveal correct hash
jq --arg system "$SYSTEM" --arg value "$DUMMY" \
'.nodeModules = (.nodeModules // {}) | .nodeModules[$system] = $value' "$HASH_FILE" > "$TMP_JSON"
mv "$TMP_JSON" "$HASH_FILE"
MODULES_ATTR=".#packages.${SYSTEM}.default.node_modules"
DRV_PATH="$(nix eval --raw "${MODULES_ATTR}.drvPath")"
echo "Building node_modules for ${SYSTEM} to discover correct hash..."
echo "Attempting to realize derivation: ${DRV_PATH}"
REALISE_OUT=$(nix-store --realise "$DRV_PATH" --keep-failed 2>&1 | tee "$BUILD_LOG" || true)
BUILD_PATH=$(echo "$REALISE_OUT" | grep "^/nix/store/" | head -n1 || true)
CORRECT_HASH=""
if [ -n "$BUILD_PATH" ] && [ -d "$BUILD_PATH" ]; then
echo "Realized node_modules output: $BUILD_PATH"
CORRECT_HASH=$(nix hash path --sri "$BUILD_PATH" 2>/dev/null || true)
fi
# Try to extract hash from build log
if [ -z "$CORRECT_HASH" ]; then
CORRECT_HASH="$(grep -E 'got:\s+sha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | awk '{print $2}' | head -n1 || true)"
fi
if [ -z "$CORRECT_HASH" ]; then
CORRECT_HASH="$(grep -A2 'hash mismatch' "$BUILD_LOG" | grep 'got:' | awk '{print $2}' | sed 's/sha256:/sha256-/' || true)"
fi
# Try to hash from kept failed build directory
if [ -z "$CORRECT_HASH" ]; then
KEPT_DIR=$(grep -oE "build directory.*'[^']+'" "$BUILD_LOG" | grep -oE "'/[^']+'" | tr -d "'" | head -n1 || true)
if [ -z "$KEPT_DIR" ]; then
KEPT_DIR=$(grep -oE '/nix/var/nix/builds/[^ ]+' "$BUILD_LOG" | head -n1 || true)
fi
if [ -n "$KEPT_DIR" ] && [ -d "$KEPT_DIR" ]; then
HASH_PATH="$KEPT_DIR"
[ -d "$KEPT_DIR/build" ] && HASH_PATH="$KEPT_DIR/build"
if [ -d "$HASH_PATH/node_modules" ]; then
CORRECT_HASH=$(nix hash path --sri "$HASH_PATH" 2>/dev/null || true)
fi
fi
fi
if [ -z "$CORRECT_HASH" ]; then
echo "Failed to determine correct node_modules hash for ${SYSTEM}."
cat "$BUILD_LOG"
exit 1
fi
echo "$CORRECT_HASH" > "$OUTPUT_FILE"
echo "Hash for ${SYSTEM}: $CORRECT_HASH"
- name: Upload hash artifact
uses: actions/upload-artifact@v6
with:
name: hash-${{ matrix.system }}
path: hash-${{ matrix.system }}.txt
retention-days: 1
commit-node-modules-hashes:
needs: compute-node-modules-hash
update-node-modules-hashes:
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: blacksmith-4vcpu-ubuntu-2404
env:
@@ -147,6 +36,9 @@ jobs:
ref: ${{ github.head_ref || github.ref_name }}
repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
- name: Setup Nix
uses: nixbuild/nix-quick-install-action@v34
- name: Configure git
run: |
git config --global user.email "action@github.com"
@@ -159,54 +51,47 @@ jobs:
BRANCH="${TARGET_BRANCH:-${GITHUB_REF_NAME}}"
git pull --rebase --autostash origin "$BRANCH"
- name: Download all hash artifacts
uses: actions/download-artifact@v7
with:
pattern: hash-*
merge-multiple: true
- name: Merge hashes into hashes.json
- name: Compute all node_modules hashes
run: |
set -euo pipefail
HASH_FILE="nix/hashes.json"
SYSTEMS="x86_64-linux aarch64-linux x86_64-darwin aarch64-darwin"
if [ ! -f "$HASH_FILE" ]; then
mkdir -p "$(dirname "$HASH_FILE")"
echo '{"nodeModules":{}}' > "$HASH_FILE"
fi
echo "Merging hashes into ${HASH_FILE}..."
for SYSTEM in $SYSTEMS; do
echo "Computing hash for ${SYSTEM}..."
BUILD_LOG=$(mktemp)
trap 'rm -f "$BUILD_LOG"' EXIT
shopt -s nullglob
files=(hash-*.txt)
if [ ${#files[@]} -eq 0 ]; then
echo "No hash files found, nothing to update"
exit 0
fi
# The updater derivations use fakeHash, so they will fail and reveal the correct hash
UPDATER_ATTR=".#packages.x86_64-linux.${SYSTEM}_node_modules"
EXPECTED_SYSTEMS="x86_64-linux aarch64-linux x86_64-darwin aarch64-darwin"
for sys in $EXPECTED_SYSTEMS; do
if [ ! -f "hash-${sys}.txt" ]; then
echo "WARNING: Missing hash file for $sys"
nix build "$UPDATER_ATTR" --no-link 2>&1 | tee "$BUILD_LOG" || true
CORRECT_HASH="$(grep -E 'got:\s+sha256-[A-Za-z0-9+/=]+' "$BUILD_LOG" | awk '{print $2}' | head -n1 || true)"
if [ -z "$CORRECT_HASH" ]; then
CORRECT_HASH="$(grep -A2 'hash mismatch' "$BUILD_LOG" | grep 'got:' | awk '{print $2}' | sed 's/sha256:/sha256-/' || true)"
fi
done
for f in "${files[@]}"; do
system="${f#hash-}"
system="${system%.txt}"
hash=$(cat "$f")
if [ -z "$hash" ]; then
echo "WARNING: Empty hash for $system, skipping"
continue
if [ -z "$CORRECT_HASH" ]; then
echo "Failed to determine correct node_modules hash for ${SYSTEM}."
cat "$BUILD_LOG"
exit 1
fi
echo " $system: $hash"
jq --arg sys "$system" --arg h "$hash" \
'.nodeModules = (.nodeModules // {}) | .nodeModules[$sys] = $h' "$HASH_FILE" > "${HASH_FILE}.tmp"
echo " ${SYSTEM}: ${CORRECT_HASH}"
jq --arg sys "$SYSTEM" --arg h "$CORRECT_HASH" \
'.nodeModules[$sys] = $h' "$HASH_FILE" > "${HASH_FILE}.tmp"
mv "${HASH_FILE}.tmp" "$HASH_FILE"
done
echo "All hashes merged:"
echo "All hashes computed:"
cat "$HASH_FILE"
- name: Commit ${{ env.TITLE }} changes
-5
View File
@@ -9,11 +9,6 @@
"opencode": {
"options": {},
},
"azure": {
"options": {
"resourceName": "alice-mi7mfgew-eastus2",
},
},
},
"mcp": {
"context7": {
+1
View File
@@ -204,3 +204,4 @@
| 2026-01-16 | 4,121,550 (+552,622) | 1,754,418 (+109,056) | 5,875,968 (+661,678) |
| 2026-01-17 | 4,389,558 (+268,008) | 1,805,315 (+50,897) | 6,194,873 (+318,905) |
| 2026-01-18 | 4,627,623 (+238,065) | 1,839,171 (+33,856) | 6,466,794 (+271,921) |
| 2026-01-19 | 4,861,108 (+233,485) | 1,863,112 (+23,941) | 6,724,220 (+257,426) |
+10
View File
@@ -56,6 +56,7 @@
},
"devDependencies": {
"@happy-dom/global-registrator": "20.0.11",
"@playwright/test": "1.57.0",
"@tailwindcss/vite": "catalog:",
"@tsconfig/bun": "1.0.9",
"@types/bun": "catalog:",
@@ -502,6 +503,7 @@
"@octokit/rest": "22.0.0",
"@openauthjs/openauth": "0.0.0-20250322224806",
"@pierre/diffs": "1.0.2",
"@playwright/test": "1.51.0",
"@solid-primitives/storage": "4.3.3",
"@solidjs/meta": "0.29.4",
"@solidjs/router": "0.15.4",
@@ -1355,6 +1357,8 @@
"@planetscale/database": ["@planetscale/database@1.19.0", "", {}, "sha512-Tv4jcFUFAFjOWrGSio49H6R2ijALv0ZzVBfJKIdm+kl9X046Fh4LLawrF9OMsglVbK6ukqMJsUCeucGAFTBcMA=="],
"@playwright/test": ["@playwright/test@1.57.0", "", { "dependencies": { "playwright": "1.57.0" }, "bin": { "playwright": "cli.js" } }, "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA=="],
"@poppinss/colors": ["@poppinss/colors@4.1.5", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-FvdDqtcRCtz6hThExcFOgW0cWX+xwSMWcRuQe5ZEb2m7cVQOAVZOIMt+/v9RxGiD9/OY16qJBXK4CVKWAPalBw=="],
"@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="],
@@ -3291,6 +3295,10 @@
"planck": ["planck@1.4.2", "", { "peerDependencies": { "stage-js": "^1.0.0-alpha.12" } }, "sha512-mNbhnV3g8X2rwGxzcesjmN8BDA6qfXgQxXVMkWau9MCRlQY0RLNEkyHlVp6yFy/X6qrzAXyNONCnZ1cGDLrNew=="],
"playwright": ["playwright@1.57.0", "", { "dependencies": { "playwright-core": "1.57.0" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw=="],
"playwright-core": ["playwright-core@1.57.0", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ=="],
"pngjs": ["pngjs@7.0.0", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],
"possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],
@@ -4427,6 +4435,8 @@
"pkg-up/find-up": ["find-up@3.0.0", "", { "dependencies": { "locate-path": "^3.0.0" } }, "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg=="],
"playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
"postcss-load-config/lilconfig": ["lilconfig@3.1.3", "", {}, "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw=="],
"prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="],
Generated
+3 -3
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1768302833,
"narHash": "sha256-h5bRFy9bco+8QcK7rGoOiqMxMbmn21moTACofNLRMP4=",
"lastModified": 1768569498,
"narHash": "sha256-bB6Nt99Cj8Nu5nIUq0GLmpiErIT5KFshMQJGMZwgqUo=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "61db79b0c6b838d9894923920b612048e1201926",
"rev": "be5afa0fcb31f0a96bf9ecba05a516c66fcd8114",
"type": "github"
},
"original": {
+22 -2
View File
@@ -33,17 +33,37 @@
packages = forEachSystem (
pkgs:
let
opencode = pkgs.callPackage ./nix/opencode.nix {
node_modules = pkgs.callPackage ./nix/node_modules.nix {
inherit rev;
};
opencode = pkgs.callPackage ./nix/opencode.nix {
inherit node_modules;
};
desktop = pkgs.callPackage ./nix/desktop.nix {
inherit opencode;
};
# nixpkgs cpu naming to bun cpu naming
cpuMap = { x86_64 = "x64"; aarch64 = "arm64"; };
# matrix of node_modules builds - these will always fail due to fakeHash usage
# but allow computation of the correct hash from any build machine for any cpu/os
# see the update-nix-hashes workflow for usage
moduleUpdaters = pkgs.lib.listToAttrs (
pkgs.lib.concatMap (cpu:
map (os: {
name = "${cpu}-${os}_node_modules";
value = node_modules.override {
bunCpu = cpuMap.${cpu};
bunOs = os;
hash = pkgs.lib.fakeHash;
};
}) [ "linux" "darwin" ]
) [ "x86_64" "aarch64" ]
);
in
{
default = opencode;
inherit opencode desktop;
}
} // moduleUpdaters
);
};
}
+4 -4
View File
@@ -1,8 +1,8 @@
{
"nodeModules": {
"x86_64-linux": "sha256-D1VXuKJagfq3mxh8Xs8naHoYNJUJzAM9JLJqpHcItDk=",
"aarch64-linux": "sha256-9wXcg50Sv56Wb2x5NWe15olNGE/uMiDkmGRmqPoeW1U=",
"aarch64-darwin": "sha256-i5eTTjsNAARwcw69sd6wuse2BKTUi/Vfgo4M28l+RoY=",
"x86_64-darwin": "sha256-oFtQnIzgTS2zcjkhBTnXxYqr20KXdA2I+b908piLs+c="
"x86_64-linux": "sha256-80+b7FwUy4mRWTzEjPrBWuR5Um67I1Rn4U/n/s/lBjs=",
"aarch64-linux": "sha256-xH/Grwh3b+HWsUkKN8LMcyMaMcmnIJYlgp38WJCat5E=",
"aarch64-darwin": "sha256-Izv6PE9gNaeYYfcqDwjTU/WYtD1y+j65annwvLzkMD8=",
"x86_64-darwin": "sha256-EG1Z0uAeyFiOeVsv0Sz1sa8/mdXuw/uvbYYrkFR3EAg="
}
}
+85
View File
@@ -0,0 +1,85 @@
{
lib,
stdenvNoCC,
bun,
bunCpu ? if stdenvNoCC.hostPlatform.isAarch64 then "arm64" else "x64",
bunOs ? if stdenvNoCC.hostPlatform.isLinux then "linux" else "darwin",
rev ? "dirty",
hash ?
(lib.pipe ./hashes.json [
builtins.readFile
builtins.fromJSON
]).nodeModules.${stdenvNoCC.hostPlatform.system},
}:
let
packageJson = lib.pipe ../packages/opencode/package.json [
builtins.readFile
builtins.fromJSON
];
in
stdenvNoCC.mkDerivation {
pname = "opencode-node_modules";
version = "${packageJson.version}-${rev}";
src = lib.fileset.toSource {
root = ../.;
fileset = lib.fileset.intersection (lib.fileset.fromSource (lib.sources.cleanSource ../.)) (
lib.fileset.unions [
../packages
../bun.lock
../package.json
../patches
../install
]
);
};
impureEnvVars = lib.fetchers.proxyImpureEnvVars ++ [
"GIT_PROXY_COMMAND"
"SOCKS_SERVER"
];
nativeBuildInputs = [
bun
];
dontConfigure = true;
buildPhase = ''
runHook preBuild
export HOME=$(mktemp -d)
export BUN_INSTALL_CACHE_DIR=$(mktemp -d)
bun install \
--cpu="${bunCpu}" \
--os="${bunOs}" \
--frozen-lockfile \
--ignore-scripts \
--no-progress \
--linker=isolated
bun --bun ${./scripts/canonicalize-node-modules.ts}
bun --bun ${./scripts/normalize-bun-binaries.ts}
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out
find . -type d -name node_modules -exec cp -R --parents {} $out \;
runHook postInstall
'';
dontFixup = true;
outputHashAlgo = "sha256";
outputHashMode = "recursive";
outputHash = hash;
meta.platforms = [
"aarch64-linux"
"x86_64-linux"
"aarch64-darwin"
"x86_64-darwin"
];
}
+5 -78
View File
@@ -1,6 +1,7 @@
{
lib,
stdenvNoCC,
callPackage,
bun,
sysctl,
makeBinaryWrapper,
@@ -9,81 +10,12 @@
installShellFiles,
versionCheckHook,
writableTmpDirAsHomeHook,
rev ? "dirty",
node_modules ? callPackage ./node-modules.nix { },
}:
let
packageJson = lib.pipe ../packages/opencode/package.json [
builtins.readFile
builtins.fromJSON
];
in
stdenvNoCC.mkDerivation (finalAttrs: {
pname = "opencode";
version = "${packageJson.version}-${rev}";
src = lib.fileset.toSource {
root = ../.;
fileset = lib.fileset.intersection (lib.fileset.fromSource (lib.sources.cleanSource ../.)) (
lib.fileset.unions [
../packages
../bun.lock
../package.json
../patches
../install
]
);
};
node_modules = stdenvNoCC.mkDerivation {
pname = "${finalAttrs.pname}-node_modules";
inherit (finalAttrs) version src;
impureEnvVars = lib.fetchers.proxyImpureEnvVars ++ [
"GIT_PROXY_COMMAND"
"SOCKS_SERVER"
];
nativeBuildInputs = [
bun
];
dontConfigure = true;
buildPhase = ''
runHook preBuild
export HOME=$(mktemp -d)
export BUN_INSTALL_CACHE_DIR=$(mktemp -d)
bun install \
--cpu="${if stdenvNoCC.hostPlatform.isAarch64 then "arm64" else "x64"}" \
--os="${if stdenvNoCC.hostPlatform.isLinux then "linux" else "darwin"}" \
--frozen-lockfile \
--ignore-scripts \
--no-progress \
--linker=isolated
bun --bun ${./scripts/canonicalize-node-modules.ts}
bun --bun ${./scripts/normalize-bun-binaries.ts}
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out
find . -type d -name node_modules -exec cp -R --parents {} $out \;
runHook postInstall
'';
dontFixup = true;
outputHashAlgo = "sha256";
outputHashMode = "recursive";
outputHash =
(lib.pipe ./hashes.json [
builtins.readFile
builtins.fromJSON
]).nodeModules.${stdenvNoCC.hostPlatform.system};
};
inherit (node_modules) version src;
inherit node_modules;
nativeBuildInputs = [
bun
@@ -159,11 +91,6 @@ stdenvNoCC.mkDerivation (finalAttrs: {
homepage = "https://opencode.ai/";
license = lib.licenses.mit;
mainProgram = "opencode";
platforms = [
"aarch64-linux"
"x86_64-linux"
"aarch64-darwin"
"x86_64-darwin"
];
inherit (node_modules.meta) platforms;
};
})
+1
View File
@@ -44,6 +44,7 @@
"luxon": "3.6.1",
"marked": "17.0.1",
"marked-shiki": "1.2.1",
"@playwright/test": "1.51.0",
"typescript": "5.8.2",
"@typescript/native-preview": "7.0.0-dev.20251207.1",
"zod": "4.1.8",
+2
View File
@@ -1 +1,3 @@
src/assets/theme.css
e2e/test-results
e2e/playwright-report
+15
View File
@@ -29,6 +29,21 @@ It correctly bundles Solid in production mode and optimizes the build for the be
The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!
## E2E Testing
The Playwright runner expects the app already running at `http://localhost:3000`.
```bash
bun add -D @playwright/test
bunx playwright install
bun run test:e2e
```
Environment options:
- `PLAYWRIGHT_BASE_URL` (default: `http://localhost:3000`)
- `PLAYWRIGHT_PORT` (default: `3000`)
## Deployment
You can deploy the `dist` folder to any static host provider (netlify, surge, now, etc.)
+45
View File
@@ -0,0 +1,45 @@
import { test, expect } from "./fixtures"
import { promptSelector } from "./utils"
test("context panel can be opened from the prompt", async ({ page, sdk, gotoSession }) => {
const title = `e2e smoke context ${Date.now()}`
const created = await sdk.session.create({ title }).then((r) => r.data)
if (!created?.id) throw new Error("Session create did not return an id")
const sessionID = created.id
try {
await sdk.session.promptAsync({
sessionID,
noReply: true,
parts: [
{
type: "text",
text: "seed context",
},
],
})
await expect
.poll(async () => {
const messages = await sdk.session.messages({ sessionID, limit: 1 }).then((r) => r.data ?? [])
return messages.length
})
.toBeGreaterThan(0)
await gotoSession(sessionID)
const contextButton = page
.locator('[data-component="button"]')
.filter({ has: page.locator('[data-component="progress-circle"]').first() })
.first()
await expect(contextButton).toBeVisible()
await contextButton.click()
const tabs = page.locator('[data-component="tabs"][data-variant="normal"]')
await expect(tabs.getByRole("tab", { name: "Context" })).toBeVisible()
} finally {
await sdk.session.delete({ sessionID }).catch(() => undefined)
}
})
+23
View File
@@ -0,0 +1,23 @@
import { test, expect } from "./fixtures"
import { modKey } from "./utils"
test("can open a file tab from the search palette", async ({ page, gotoSession }) => {
await gotoSession()
await page.keyboard.press(`${modKey}+P`)
const dialog = page.getByRole("dialog")
await expect(dialog).toBeVisible()
const input = dialog.getByRole("textbox").first()
await input.fill("package.json")
const fileItem = dialog.locator('[data-slot="list-item"][data-key^="file:"]').first()
await expect(fileItem).toBeVisible()
await fileItem.click()
await expect(dialog).toHaveCount(0)
const tabs = page.locator('[data-component="tabs"][data-variant="normal"]')
await expect(tabs.locator('[data-slot="tabs-trigger"]').first()).toBeVisible()
})
+40
View File
@@ -0,0 +1,40 @@
import { test as base, expect } from "@playwright/test"
import { createSdk, dirSlug, getWorktree, promptSelector, sessionPath } from "./utils"
type TestFixtures = {
sdk: ReturnType<typeof createSdk>
gotoSession: (sessionID?: string) => Promise<void>
}
type WorkerFixtures = {
directory: string
slug: string
}
export const test = base.extend<TestFixtures, WorkerFixtures>({
directory: [
async ({}, use) => {
const directory = await getWorktree()
await use(directory)
},
{ scope: "worker" },
],
slug: [
async ({ directory }, use) => {
await use(dirSlug(directory))
},
{ scope: "worker" },
],
sdk: async ({ directory }, use) => {
await use(createSdk(directory))
},
gotoSession: async ({ page, directory }, use) => {
const gotoSession = async (sessionID?: string) => {
await page.goto(sessionPath(directory, sessionID))
await expect(page.locator(promptSelector)).toBeVisible()
}
await use(gotoSession)
},
})
export { expect }
+21
View File
@@ -0,0 +1,21 @@
import { test, expect } from "./fixtures"
import { serverName } from "./utils"
test("home renders and shows core entrypoints", async ({ page }) => {
await page.goto("/")
await expect(page.getByRole("button", { name: "Open project" }).first()).toBeVisible()
await expect(page.getByRole("button", { name: serverName })).toBeVisible()
})
test("server picker dialog opens from home", async ({ page }) => {
await page.goto("/")
const trigger = page.getByRole("button", { name: serverName })
await expect(trigger).toBeVisible()
await trigger.click()
const dialog = page.getByRole("dialog")
await expect(dialog).toBeVisible()
await expect(dialog.getByRole("textbox").first()).toBeVisible()
})
+9
View File
@@ -0,0 +1,9 @@
import { test, expect } from "./fixtures"
import { dirPath, promptSelector } from "./utils"
test("project route redirects to /session", async ({ page, directory, slug }) => {
await page.goto(dirPath(directory))
await expect(page).toHaveURL(new RegExp(`/${slug}/session`))
await expect(page.locator(promptSelector)).toBeVisible()
})
+15
View File
@@ -0,0 +1,15 @@
import { test, expect } from "./fixtures"
import { modKey } from "./utils"
test("search palette opens and closes", async ({ page, gotoSession }) => {
await gotoSession()
await page.keyboard.press(`${modKey}+P`)
const dialog = page.getByRole("dialog")
await expect(dialog).toBeVisible()
await expect(dialog.getByRole("textbox").first()).toBeVisible()
await page.keyboard.press("Escape")
await expect(dialog).toHaveCount(0)
})
+21
View File
@@ -0,0 +1,21 @@
import { test, expect } from "./fixtures"
import { promptSelector } from "./utils"
test("can open an existing session and type into the prompt", async ({ page, sdk, gotoSession }) => {
const title = `e2e smoke ${Date.now()}`
const created = await sdk.session.create({ title }).then((r) => r.data)
if (!created?.id) throw new Error("Session create did not return an id")
const sessionID = created.id
try {
await gotoSession(sessionID)
const prompt = page.locator(promptSelector)
await prompt.click()
await page.keyboard.type("hello from e2e")
await expect(prompt).toContainText("hello from e2e")
} finally {
await sdk.session.delete({ sessionID }).catch(() => undefined)
}
})
+21
View File
@@ -0,0 +1,21 @@
import { test, expect } from "./fixtures"
import { modKey } from "./utils"
test("sidebar can be collapsed and expanded", async ({ page, gotoSession }) => {
await gotoSession()
const main = page.locator("main")
const closedClass = /xl:border-l/
const isClosed = await main.evaluate((node) => node.className.includes("xl:border-l"))
if (isClosed) {
await page.keyboard.press(`${modKey}+B`)
await expect(main).not.toHaveClass(closedClass)
}
await page.keyboard.press(`${modKey}+B`)
await expect(main).toHaveClass(closedClass)
await page.keyboard.press(`${modKey}+B`)
await expect(main).not.toHaveClass(closedClass)
})
+16
View File
@@ -0,0 +1,16 @@
import { test, expect } from "./fixtures"
import { terminalSelector, terminalToggleKey } from "./utils"
test("terminal panel can be toggled", async ({ page, gotoSession }) => {
await gotoSession()
const terminal = page.locator(terminalSelector)
const initiallyOpen = await terminal.isVisible()
if (initiallyOpen) {
await page.keyboard.press(terminalToggleKey)
await expect(terminal).toHaveCount(0)
}
await page.keyboard.press(terminalToggleKey)
await expect(terminal).toBeVisible()
})
+38
View File
@@ -0,0 +1,38 @@
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
import { base64Encode } from "@opencode-ai/util/encode"
export const serverHost = process.env.PLAYWRIGHT_SERVER_HOST ?? "localhost"
export const serverPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
export const serverUrl = `http://${serverHost}:${serverPort}`
export const serverName = `${serverHost}:${serverPort}`
export const modKey = process.platform === "darwin" ? "Meta" : "Control"
export const terminalToggleKey = "Control+Backquote"
export const promptSelector = '[data-component="prompt-input"]'
export const terminalSelector = '[data-component="terminal"]'
export function createSdk(directory?: string) {
return createOpencodeClient({ baseUrl: serverUrl, directory, throwOnError: true })
}
export async function getWorktree() {
const sdk = createSdk()
const result = await sdk.path.get()
const data = result.data
if (!data?.worktree) throw new Error(`Failed to resolve a worktree from ${serverUrl}/path`)
return data.worktree
}
export function dirSlug(directory: string) {
return base64Encode(directory)
}
export function dirPath(directory: string) {
return `/${dirSlug(directory)}`
}
export function sessionPath(directory: string, sessionID?: string) {
return `${dirPath(directory)}/session${sessionID ? `/${sessionID}` : ""}`
}
+6 -1
View File
@@ -12,11 +12,16 @@
"start": "vite",
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
"serve": "vite preview",
"test": "playwright test",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:report": "playwright show-report e2e/playwright-report"
},
"license": "MIT",
"devDependencies": {
"@happy-dom/global-registrator": "20.0.11",
"@playwright/test": "1.57.0",
"@tailwindcss/vite": "catalog:",
"@tsconfig/bun": "1.0.9",
"@types/bun": "catalog:",
+43
View File
@@ -0,0 +1,43 @@
import { defineConfig, devices } from "@playwright/test"
const port = Number(process.env.PLAYWRIGHT_PORT ?? 3000)
const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${port}`
const serverHost = process.env.PLAYWRIGHT_SERVER_HOST ?? "localhost"
const serverPort = process.env.PLAYWRIGHT_SERVER_PORT ?? "4096"
const command = `bun run dev -- --host 0.0.0.0 --port ${port}`
const reuse = !process.env.CI
export default defineConfig({
testDir: "./e2e",
outputDir: "./e2e/test-results",
timeout: 60_000,
expect: {
timeout: 10_000,
},
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: [["html", { outputFolder: "e2e/playwright-report", open: "never" }], ["line"]],
webServer: {
command,
url: baseURL,
reuseExistingServer: reuse,
timeout: 120_000,
env: {
VITE_OPENCODE_SERVER_HOST: serverHost,
VITE_OPENCODE_SERVER_PORT: serverPort,
},
},
use: {
baseURL,
trace: "on-first-retry",
screenshot: "only-on-failure",
video: "retain-on-failure",
},
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
],
})
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

@@ -27,11 +27,15 @@ export function DialogEditProject(props: { project: LocalProject }) {
})
const [dragOver, setDragOver] = createSignal(false)
const [iconHover, setIconHover] = createSignal(false)
function handleFileSelect(file: File) {
if (!file.type.startsWith("image/")) return
const reader = new FileReader()
reader.onload = (e) => setStore("iconUrl", e.target?.result as string)
reader.onload = (e) => {
setStore("iconUrl", e.target?.result as string)
setIconHover(false)
}
reader.readAsDataURL(file)
}
@@ -77,8 +81,8 @@ export function DialogEditProject(props: { project: LocalProject }) {
}
return (
<Dialog title="Edit project">
<form onSubmit={handleSubmit} class="flex flex-col gap-6 px-2.5 pb-3">
<Dialog title="Edit project" class="w-full max-w-[480px] mx-auto">
<form onSubmit={handleSubmit} class="flex flex-col gap-6 p-6">
<div class="flex flex-col gap-4">
<TextField
autofocus
@@ -92,17 +96,24 @@ export function DialogEditProject(props: { project: LocalProject }) {
<div class="flex flex-col gap-2">
<label class="text-12-medium text-text-weak">Icon</label>
<div class="flex gap-3 items-start">
<div class="relative">
<div class="relative" onMouseEnter={() => setIconHover(true)} onMouseLeave={() => setIconHover(false)}>
<div
class="size-16 rounded-lg overflow-hidden border border-dashed transition-colors cursor-pointer"
class="relative size-16 rounded-md transition-colors cursor-pointer"
classList={{
"border-text-interactive-base bg-surface-info-base/20": dragOver(),
"border-border-base hover:border-border-strong": !dragOver(),
"overflow-hidden": !!store.iconUrl,
}}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onClick={() => document.getElementById("icon-upload")?.click()}
onClick={() => {
if (store.iconUrl && iconHover()) {
clearIcon()
} else {
document.getElementById("icon-upload")?.click()
}
}}
>
<Show
when={store.iconUrl}
@@ -119,20 +130,48 @@ export function DialogEditProject(props: { project: LocalProject }) {
<img src={store.iconUrl} alt="Project icon" class="size-full object-cover" />
</Show>
</div>
<Show when={store.iconUrl}>
<button
type="button"
class="absolute -top-1.5 -right-1.5 size-5 rounded-full bg-surface-raised-base border border-border-base flex items-center justify-center hover:bg-surface-raised-base-hover"
onClick={clearIcon}
>
<Icon name="close" class="size-3 text-icon-base" />
</button>
</Show>
<div
style={{
position: "absolute",
top: 0,
left: 0,
width: "64px",
height: "64px",
background: "rgba(0,0,0,0.6)",
"border-radius": "6px",
"z-index": 10,
"pointer-events": "none",
opacity: iconHover() && !store.iconUrl ? 1 : 0,
display: "flex",
"align-items": "center",
"justify-content": "center",
}}
>
<Icon name="cloud-upload" size="large" class="text-icon-invert-base" />
</div>
<div
style={{
position: "absolute",
top: 0,
left: 0,
width: "64px",
height: "64px",
background: "rgba(0,0,0,0.6)",
"border-radius": "6px",
"z-index": 10,
"pointer-events": "none",
opacity: iconHover() && store.iconUrl ? 1 : 0,
display: "flex",
"align-items": "center",
"justify-content": "center",
}}
>
<Icon name="trash" size="large" class="text-icon-invert-base" />
</div>
</div>
<input id="icon-upload" type="file" accept="image/*" class="hidden" onChange={handleInputChange} />
<div class="flex flex-col gap-1.5 text-12-regular text-text-weak">
<span>Click or drag an image</span>
<span>Recommended: 128x128px</span>
<div class="flex flex-col gap-1.5 text-12-regular text-text-weak self-center">
<span>Recommended size 128x128px</span>
</div>
</div>
</div>
@@ -140,20 +179,25 @@ export function DialogEditProject(props: { project: LocalProject }) {
<Show when={!store.iconUrl}>
<div class="flex flex-col gap-2">
<label class="text-12-medium text-text-weak">Color</label>
<div class="flex gap-2">
<div class="flex gap-1.5">
<For each={AVATAR_COLOR_KEYS}>
{(color) => (
<button
type="button"
class="relative size-8 rounded-md transition-all"
classList={{
"ring-2 ring-offset-2 ring-offset-surface-base ring-text-interactive-base":
"flex items-center justify-center size-10 p-0.5 rounded-lg overflow-hidden transition-colors cursor-default": true,
"bg-transparent border-2 border-icon-strong-base hover:bg-surface-base-hover":
store.color === color,
"bg-transparent border border-transparent hover:bg-surface-base-hover hover:border-border-weak-base":
store.color !== color,
}}
style={{ background: getAvatarColors(color).background }}
onClick={() => setStore("color", color)}
>
<Avatar fallback={store.name || defaultName()} {...getAvatarColors(color)} class="size-full" />
<Avatar
fallback={store.name || defaultName()}
{...getAvatarColors(color)}
class="size-full rounded"
/>
</button>
)}
</For>
@@ -0,0 +1,189 @@
import { createSignal, createEffect, onMount, onCleanup } from "solid-js"
import { Dialog } from "@opencode-ai/ui/dialog"
import { Button } from "@opencode-ai/ui/button"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { markReleaseNotesSeen } from "@/lib/release-notes"
export interface ReleaseFeature {
title: string
description: string
tag?: string
media?: {
type: "image" | "video"
src: string
alt?: string
}
}
export interface ReleaseNote {
version: string
features: ReleaseFeature[]
}
// Current release notes - update this with each release
export const CURRENT_RELEASE: ReleaseNote = {
version: "1.0.0",
features: [
{
title: "Cleaner tab experience",
description: "Chat is now fixed to the side of your tabs, and review is now available as a dedicated tab. ",
tag: "New",
media: {
type: "video",
src: "/release/release-example.mp4",
alt: "Cleaner tab experience",
},
},
{
title: "Share with control",
description: "Keep your sessions private by default, or publish them to the web with a shareable URL.",
tag: "New",
media: {
type: "image",
src: "/release/release-share.png",
alt: "Share with control",
},
},
{
title: "Improved attachment management",
description: "Upload and manage attachments more easily, to help build and maintain context.",
tag: "New",
media: {
type: "video",
src: "/release/release-example.mp4",
alt: "Improved attachment management",
},
},
],
}
export function DialogReleaseNotes(props: { release?: ReleaseNote }) {
const dialog = useDialog()
const release = props.release ?? CURRENT_RELEASE
const [index, setIndex] = createSignal(0)
const feature = () => release.features[index()]
const total = release.features.length
const isFirst = () => index() === 0
const isLast = () => index() === total - 1
function handleNext() {
if (!isLast()) setIndex(index() + 1)
}
function handleBack() {
if (!isFirst()) setIndex(index() - 1)
}
function handleClose() {
markReleaseNotesSeen()
dialog.close()
}
let focusTrap: HTMLDivElement | undefined
function handleKeyDown(e: KeyboardEvent) {
if (e.key === "ArrowLeft" && !isFirst()) {
e.preventDefault()
setIndex(index() - 1)
}
if (e.key === "ArrowRight" && !isLast()) {
e.preventDefault()
setIndex(index() + 1)
}
}
onMount(() => {
focusTrap?.focus()
document.addEventListener("keydown", handleKeyDown)
onCleanup(() => document.removeEventListener("keydown", handleKeyDown))
})
// Refocus the trap when index changes to ensure escape always works
createEffect(() => {
index() // track index
focusTrap?.focus()
})
return (
<Dialog class="dialog-release-notes">
{/* Hidden element to capture initial focus and handle escape */}
<div ref={focusTrap} tabindex="0" class="absolute opacity-0 pointer-events-none" />
{/* Left side - Text content */}
<div class="flex flex-col flex-1 min-w-0 p-8">
{/* Top section - feature content (fixed position from top) */}
<div class="flex flex-col gap-2 pt-22">
<div class="flex items-center gap-2">
<h1 class="text-16-medium text-text-strong">{feature().title}</h1>
{feature().tag && (
<span
class="text-12-medium text-text-weak px-1.5 py-0.5 bg-surface-base rounded-sm border border-border-weak-base"
style={{ "border-width": "0.5px" }}
>
{feature().tag}
</span>
)}
</div>
<p class="text-14-regular text-text-base">{feature().description}</p>
</div>
{/* Spacer to push buttons to bottom */}
<div class="flex-1" />
{/* Bottom section - buttons and indicators (fixed position) */}
<div class="flex flex-col gap-12">
<div class="flex items-center gap-3">
{isLast() ? (
<Button variant="primary" size="large" onClick={handleClose}>
Get started
</Button>
) : (
<Button variant="secondary" size="large" onClick={handleNext}>
Next
</Button>
)}
</div>
{total > 1 && (
<div class="flex items-center gap-1.5 -my-2.5">
{release.features.map((_, i) => (
<button
type="button"
class="h-6 flex items-center cursor-pointer bg-transparent border-none p-0 transition-all duration-200"
classList={{
"w-8": i === index(),
"w-3": i !== index(),
}}
onClick={() => setIndex(i)}
>
<div
class="w-full h-0.5 rounded-[1px] transition-colors duration-200"
classList={{
"bg-icon-strong-base": i === index(),
"bg-icon-weak-base": i !== index(),
}}
/>
</button>
))}
</div>
)}
</div>
</div>
{/* Right side - Media content (edge to edge) */}
{feature().media && (
<div class="flex-1 min-w-0 bg-surface-base overflow-hidden rounded-r-xl">
{feature().media!.type === "image" ? (
<img
src={feature().media!.src}
alt={feature().media!.alt ?? "Release preview"}
class="w-full h-full object-cover"
/>
) : (
<video src={feature().media!.src} autoplay loop muted playsinline class="w-full h-full object-cover" />
)}
</div>
)}
</Dialog>
)
}
+13 -4
View File
@@ -44,7 +44,7 @@ import { ImagePreview } from "@opencode-ai/ui/image-preview"
import { ModelSelectorPopover } from "@/components/dialog-select-model"
import { DialogSelectModelUnpaid } from "@/components/dialog-select-model-unpaid"
import { useProviders } from "@/hooks/use-providers"
import { useCommand } from "@/context/command"
import { formatKeybind, useCommand } from "@/context/command"
import { Persist, persisted } from "@/utils/persist"
import { Identifier } from "@/utils/id"
import { SessionContextUsage } from "@/components/session-context-usage"
@@ -1056,7 +1056,16 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
let session = info()
if (!session && isNewSession) {
session = await client.session.create().then((x) => x.data ?? undefined)
session = await client.session
.create()
.then((x) => x.data ?? undefined)
.catch((err) => {
showToast({
title: "Failed to create session",
description: errorMessage(err),
})
return undefined
})
if (session) navigate(`/${base64Encode(sessionDirectory)}/session/${session.id}`)
}
if (!session) return
@@ -1391,8 +1400,8 @@ export const PromptInput: Component<PromptInputProps> = (props) => {
custom
</span>
</Show>
<Show when={command.keybind(cmd.id)}>
<span class="text-12-regular text-text-subtle">{command.keybind(cmd.id)}</span>
<Show when={cmd.keybind}>
<span class="text-12-regular text-text-subtle">{formatKeybind(cmd.keybind!)}</span>
</Show>
</div>
</button>
@@ -0,0 +1,31 @@
import { onMount } from "solid-js"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { DialogReleaseNotes } from "./dialog-release-notes"
import { shouldShowReleaseNotes, markReleaseNotesSeen } from "@/lib/release-notes"
/**
* Component that handles showing release notes modal on app startup.
* Shows the modal if:
* - DEV_ALWAYS_SHOW_RELEASE_NOTES is true in lib/release-notes.ts
* - OR the user hasn't seen the current version's release notes yet
*
* To disable the dev mode behavior, set DEV_ALWAYS_SHOW_RELEASE_NOTES to false
* in packages/app/src/lib/release-notes.ts
*/
export function ReleaseNotesHandler() {
const dialog = useDialog()
onMount(() => {
// Small delay to ensure app is fully loaded before showing modal
setTimeout(() => {
if (shouldShowReleaseNotes()) {
dialog.show(
() => <DialogReleaseNotes />,
() => markReleaseNotesSeen(),
)
}
}, 500)
})
return null
}
@@ -244,7 +244,11 @@ export function SessionHeader() {
}
trigger={
<Tooltip class="shrink-0" value="Share session">
<Button variant="secondary" classList={{ "rounded-r-none": shareUrl() !== undefined }}>
<Button
variant="secondary"
classList={{ "rounded-r-none": shareUrl() !== undefined }}
style={{ scale: 1 }}
>
Share
</Button>
</Tooltip>
@@ -293,12 +297,12 @@ export function SessionHeader() {
</Show>
</div>
</Popover>
<Show when={shareUrl()}>
<Show when={shareUrl()} fallback={<div class="size-6" aria-hidden="true" />}>
<Tooltip value={state.copied ? "Copied" : "Copy link"} placement="top" gutter={8}>
<IconButton
icon={state.copied ? "check" : "copy"}
variant="secondary"
class="rounded-l-none border-l border-border-weak-base"
class="rounded-l-none"
onClick={copyLink}
disabled={state.unshare}
/>
@@ -0,0 +1,232 @@
import { For, createSignal, Show, onMount, onCleanup } from "solid-js"
import { Tabs } from "@opencode-ai/ui/tabs"
import { Icon } from "@opencode-ai/ui/icon"
import { IconButton } from "@opencode-ai/ui/icon-button"
import { Tooltip } from "@opencode-ai/ui/tooltip"
import { parseKeybind, formatKeybind } from "@/context/command"
const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
const SPECIAL_CHAR_NAMES: Record<string, string> = {
"^": "Control",
"⌥": "Option",
"⇧": "Shift",
"⌘": "Command",
"↑": "Arrow Up",
"↓": "Arrow Down",
"`": "Backtick",
"'": "Quote",
".": "Period",
",": "Comma",
"/": "Slash",
"\\": "Backslash",
"[": "Left Bracket",
"]": "Right Bracket",
"-": "Minus",
"=": "Equals",
";": "Semicolon",
}
const KEY_DISPLAY_MAP: Record<string, string> = {
arrowup: "↑",
arrowdown: "↓",
arrowleft: "←",
arrowright: "→",
backspace: "⌫",
}
interface Shortcut {
title: string
keybind: string
}
interface ShortcutCategory {
name: string
shortcuts: Shortcut[]
}
function isLetter(char: string): boolean {
return /^[A-Za-z]$/.test(char)
}
function getKeyChars(config: string): string[] {
const keybinds = parseKeybind(config)
if (keybinds.length === 0) return []
const kb = keybinds[0]
const chars: string[] = []
if (kb.ctrl) chars.push(IS_MAC ? "^" : "Ctrl")
if (kb.alt) chars.push(IS_MAC ? "⌥" : "Alt")
if (kb.shift) chars.push(IS_MAC ? "⇧" : "Shift")
if (kb.meta) chars.push(IS_MAC ? "⌘" : "Meta")
if (kb.key) {
const mapped = KEY_DISPLAY_MAP[kb.key.toLowerCase()]
if (mapped) {
chars.push(mapped)
} else {
const displayKey = kb.key.length === 1 ? kb.key.toUpperCase() : kb.key.charAt(0).toUpperCase() + kb.key.slice(1)
for (const char of displayKey) {
chars.push(char)
}
}
}
return chars
}
const SHORTCUT_CATEGORIES: ShortcutCategory[] = [
{
name: "General",
shortcuts: [
{ title: "Command palette", keybind: "mod+shift+p" },
{ title: "Toggle sidebar", keybind: "mod+b" },
{ title: "Toggle shortcuts", keybind: "ctrl+/" },
{ title: "Open file", keybind: "mod+p" },
{ title: "Open project", keybind: "mod+o" },
],
},
{
name: "Session",
shortcuts: [
{ title: "New session", keybind: "mod+shift+s" },
{ title: "Previous session", keybind: "alt+arrowup" },
{ title: "Next session", keybind: "alt+arrowdown" },
{ title: "Archive session", keybind: "mod+shift+backspace" },
{ title: "Undo", keybind: "mod+z" },
{ title: "Redo", keybind: "mod+shift+z" },
],
},
{
name: "Navigation",
shortcuts: [
{ title: "Previous message", keybind: "mod+arrowup" },
{ title: "Next message", keybind: "mod+arrowdown" },
{ title: "Toggle steps", keybind: "mod+e" },
],
},
{
name: "Model and Agent",
shortcuts: [
{ title: "Choose model", keybind: "mod+'" },
{ title: "Cycle agent", keybind: "mod+." },
],
},
{
name: "Terminal",
shortcuts: [
{ title: "Toggle terminal", keybind: "ctrl+`" },
{ title: "New terminal", keybind: "ctrl+shift+`" },
],
},
]
const USED_SHORTCUTS_KEY = "opencode:used-shortcuts"
function getUsedShortcuts(): Set<string> {
const stored = localStorage.getItem(USED_SHORTCUTS_KEY)
return stored ? new Set(JSON.parse(stored)) : new Set()
}
const [usedShortcuts, setUsedShortcuts] = createSignal(getUsedShortcuts())
function formatKeybindForCopy(config: string): string {
const chars = getKeyChars(config)
return chars.join("")
}
function ShortcutItem(props: { shortcut: Shortcut }) {
const [copied, setCopied] = createSignal(false)
const used = () => usedShortcuts().has(props.shortcut.keybind)
function copyToClipboard() {
const text = formatKeybindForCopy(props.shortcut.keybind)
navigator.clipboard.writeText(text)
setCopied(true)
setTimeout(() => setCopied(false), 1500)
}
return (
<Tooltip value="Copy to clipboard" placement="top">
<button type="button" class="shortcut-item" classList={{ "shortcut-used": used() }} onClick={copyToClipboard}>
<span class="text-14-regular text-text-base">{props.shortcut.title}</span>
<Show
when={!copied()}
fallback={
<div class="shortcut-copied">
<Icon name="check" size="small" />
</div>
}
>
<div class="shortcut-keys">
<For each={getKeyChars(props.shortcut.keybind)}>
{(char) => {
const tooltip = SPECIAL_CHAR_NAMES[char]
const isSpecial = tooltip && !isLetter(char)
const isShift = char === "⇧"
return (
<Show when={isSpecial} fallback={<kbd class="shortcut-key">{char}</kbd>}>
<Tooltip value={tooltip} placement="top">
<kbd class="shortcut-key shortcut-key-special">
<span classList={{ "shortcut-key-shift": isShift }}>{char}</span>
</kbd>
</Tooltip>
</Show>
)
}}
</For>
</div>
</Show>
</button>
</Tooltip>
)
}
export function ShortcutsPanel(props: { onClose: () => void }) {
const [activeTab, setActiveTab] = createSignal(SHORTCUT_CATEGORIES[0].name)
let listRef: HTMLDivElement | undefined
onMount(() => {
const handler = () => setUsedShortcuts(getUsedShortcuts())
window.addEventListener("shortcut-used", handler)
onCleanup(() => window.removeEventListener("shortcut-used", handler))
// Focus the active tab trigger so arrow keys work immediately
const trigger = listRef?.querySelector<HTMLButtonElement>('[data-slot="tabs-trigger"][data-selected]')
trigger?.focus()
})
return (
<div class="shortcuts-panel" data-component="shortcuts-panel">
<Tabs value={activeTab()} onChange={setActiveTab}>
<div class="shortcuts-tabs-row">
<Tabs.List ref={listRef} class="shortcuts-tabs-list">
<For each={SHORTCUT_CATEGORIES}>
{(category) => <Tabs.Trigger value={category.name}>{category.name}</Tabs.Trigger>}
</For>
</Tabs.List>
<Tooltip
placement="top"
value={
<span>
Close <span class="text-text-weak">{formatKeybind("ctrl+/")}</span>
</span>
}
>
<IconButton icon="close" variant="ghost" onClick={props.onClose} />
</Tooltip>
</div>
<For each={SHORTCUT_CATEGORIES}>
{(category) => (
<Tabs.Content value={category.name} class="shortcuts-content">
<div class="shortcuts-grid">
<For each={category.shortcuts}>{(shortcut) => <ShortcutItem shortcut={shortcut} />}</For>
</div>
</Tabs.Content>
)}
</For>
</Tabs>
</div>
)
}
+74 -2
View File
@@ -1,6 +1,8 @@
import { createMemo, createSignal, onCleanup, onMount, type Accessor } from "solid-js"
import { createMemo, createSignal, onCleanup, onMount, Show, type Accessor } from "solid-js"
import { createSimpleContext } from "@opencode-ai/ui/context"
import { useDialog } from "@opencode-ai/ui/context/dialog"
import { Dialog } from "@opencode-ai/ui/dialog"
import { List } from "@opencode-ai/ui/list"
const IS_MAC = typeof navigator === "object" && /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
@@ -120,6 +122,73 @@ export function formatKeybind(config: string): string {
return IS_MAC ? parts.join("") : parts.join("+")
}
function DialogCommand(props: { options: CommandOption[] }) {
const dialog = useDialog()
const state = { cleanup: undefined as (() => void) | void, committed: false }
const handleMove = (option: CommandOption | undefined) => {
state.cleanup?.()
if (!option) return
state.cleanup = option.onHighlight?.()
}
const handleSelect = (option: CommandOption | undefined) => {
if (!option) return
state.committed = true
state.cleanup = undefined
dialog.close()
option.onSelect?.("palette")
}
onCleanup(() => {
if (state.committed) return
state.cleanup?.()
})
return (
<Dialog title="Commands">
<List
class="px-2.5"
search={{ placeholder: "Search commands", autofocus: true }}
emptyMessage="No commands found"
items={() => props.options.filter((x) => !x.id.startsWith("suggested.") || !x.disabled)}
key={(x) => x?.id}
filterKeys={["title", "description", "category"]}
groupBy={(x) => x.category ?? ""}
onMove={handleMove}
onSelect={handleSelect}
>
{(option) => (
<div class="w-full flex items-center justify-between gap-4">
<div class="flex items-center gap-2 min-w-0">
<span class="text-14-regular text-text-strong whitespace-nowrap">{option.title}</span>
<Show when={option.description}>
<span class="text-14-regular text-text-weak truncate">{option.description}</span>
</Show>
</div>
<Show when={option.keybind}>
<span class="text-12-regular text-text-subtle shrink-0">{formatKeybind(option.keybind!)}</span>
</Show>
</div>
)}
</List>
</Dialog>
)
}
const USED_SHORTCUTS_KEY = "opencode:used-shortcuts"
function getUsedShortcuts(): Set<string> {
const stored = localStorage.getItem(USED_SHORTCUTS_KEY)
return stored ? new Set(JSON.parse(stored)) : new Set()
}
function markShortcutUsed(keybind: string) {
const used = getUsedShortcuts()
used.add(keybind)
localStorage.setItem(USED_SHORTCUTS_KEY, JSON.stringify([...used]))
window.dispatchEvent(new CustomEvent("shortcut-used", { detail: keybind }))
}
export const { use: useCommand, provider: CommandProvider } = createSimpleContext({
name: "Command",
init: () => {
@@ -163,7 +232,8 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
}
const showPalette = () => {
run("file.open", "palette")
if (dialog.active) return
dialog.show(() => <DialogCommand options={options().filter((x) => !x.disabled)} />)
}
const handleKeyDown = (event: KeyboardEvent) => {
@@ -172,6 +242,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const paletteKeybinds = parseKeybind("mod+shift+p")
if (matchKeybind(paletteKeybinds, event)) {
event.preventDefault()
markShortcutUsed("mod+shift+p")
showPalette()
return
}
@@ -183,6 +254,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex
const keybinds = parseKeybind(option.keybind)
if (matchKeybind(keybinds, event)) {
event.preventDefault()
markShortcutUsed(option.keybind)
option.onSelect?.("keybind")
return
}
+15 -1
View File
@@ -1,5 +1,5 @@
import { createStore, produce } from "solid-js/store"
import { batch, createEffect, createMemo, onCleanup, onMount } from "solid-js"
import { batch, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"
import { createSimpleContext } from "@opencode-ai/ui/context"
import { useGlobalSync } from "./global-sync"
import { useGlobalSDK } from "./global-sdk"
@@ -93,6 +93,8 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
}),
)
const [shortcutsOpened, setShortcutsOpened] = createSignal(false)
const MAX_SESSION_KEYS = 50
const meta = { active: undefined as string | undefined, pruned: false }
const used = new Map<string, number>()
@@ -353,6 +355,18 @@ export const { use: useLayout, provider: LayoutProvider } = createSimpleContext(
setStore("review", "diffStyle", diffStyle)
},
},
shortcuts: {
opened: shortcutsOpened,
open() {
setShortcutsOpened(true)
},
close() {
setShortcutsOpened(false)
},
toggle() {
setShortcutsOpened((x) => !x)
},
},
session: {
width: createMemo(() => store.session?.width ?? 600),
resize(width: number) {
+34 -23
View File
@@ -25,11 +25,11 @@ type TerminalCacheEntry = {
dispose: VoidFunction
}
function createTerminalSession(sdk: ReturnType<typeof useSDK>, dir: string, id: string | undefined) {
const legacy = `${dir}/terminal${id ? "/" + id : ""}.v1`
function createTerminalSession(sdk: ReturnType<typeof useSDK>, dir: string, session?: string) {
const legacy = session ? [`${dir}/terminal/${session}.v1`, `${dir}/terminal.v1`] : [`${dir}/terminal.v1`]
const [store, setStore, _, ready] = persisted(
Persist.scoped(dir, id, "terminal", [legacy]),
Persist.workspace(dir, "terminal", legacy),
createStore<{
active?: string
all: LocalPTY[]
@@ -43,17 +43,28 @@ function createTerminalSession(sdk: ReturnType<typeof useSDK>, dir: string, id:
all: createMemo(() => Object.values(store.all)),
active: createMemo(() => store.active),
new() {
const parse = (title: string) => {
const match = title.match(/^Terminal (\d+)$/)
if (!match) return
const value = Number(match[1])
if (!Number.isFinite(value) || value <= 0) return
return value
}
const existingTitleNumbers = new Set(
store.all.map((pty) => {
const match = pty.titleNumber
return match
store.all.flatMap((pty) => {
const direct = Number.isFinite(pty.titleNumber) && pty.titleNumber > 0 ? pty.titleNumber : undefined
if (direct !== undefined) return [direct]
const parsed = parse(pty.title)
if (parsed === undefined) return []
return [parsed]
}),
)
let nextNumber = 1
while (existingTitleNumbers.has(nextNumber)) {
nextNumber++
}
const nextNumber =
Array.from({ length: existingTitleNumbers.size + 1 }, (_, index) => index + 1).find(
(number) => !existingTitleNumbers.has(number),
) ?? 1
sdk.client.pty
.create({ title: `Terminal ${nextNumber}` })
@@ -166,8 +177,8 @@ export const { use: useTerminal, provider: TerminalProvider } = createSimpleCont
}
}
const load = (dir: string, id: string | undefined) => {
const key = `${dir}:${id ?? WORKSPACE_KEY}`
const load = (dir: string, session?: string) => {
const key = `${dir}:${WORKSPACE_KEY}`
const existing = cache.get(key)
if (existing) {
cache.delete(key)
@@ -176,7 +187,7 @@ export const { use: useTerminal, provider: TerminalProvider } = createSimpleCont
}
const entry = createRoot((dispose) => ({
value: createTerminalSession(sdk, dir, id),
value: createTerminalSession(sdk, dir, session),
dispose,
}))
@@ -185,18 +196,18 @@ export const { use: useTerminal, provider: TerminalProvider } = createSimpleCont
return entry.value
}
const session = createMemo(() => load(params.dir!, params.id))
const workspace = createMemo(() => load(params.dir!, params.id))
return {
ready: () => session().ready(),
all: () => session().all(),
active: () => session().active(),
new: () => session().new(),
update: (pty: Partial<LocalPTY> & { id: string }) => session().update(pty),
clone: (id: string) => session().clone(id),
open: (id: string) => session().open(id),
close: (id: string) => session().close(id),
move: (id: string, to: number) => session().move(id, to),
ready: () => workspace().ready(),
all: () => workspace().all(),
active: () => workspace().active(),
new: () => workspace().new(),
update: (pty: Partial<LocalPTY> & { id: string }) => workspace().update(pty),
clone: (id: string) => workspace().clone(id),
open: (id: string) => workspace().open(id),
close: (id: string) => workspace().close(id),
move: (id: string, to: number) => workspace().move(id, to),
}
},
})
+259
View File
@@ -9,3 +9,262 @@
*[data-tauri-drag-region] {
app-region: drag;
}
/* Wider dialog variant for release notes modal */
[data-component="dialog"]:has(.dialog-release-notes) {
padding: 20px;
box-sizing: border-box;
[data-slot="dialog-container"] {
width: min(100%, 720px);
height: min(100%, 400px);
margin-top: -80px;
[data-slot="dialog-content"] {
min-height: auto;
overflow: hidden;
height: 100%;
border: none;
box-shadow: var(--shadow-lg-border-base);
}
[data-slot="dialog-body"] {
overflow: hidden;
height: 100%;
display: flex;
flex-direction: row;
}
}
}
/* Shortcuts panel */
[data-component="shortcuts-panel"] {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: var(--color-background-base);
border-top: 1px solid var(--color-border-weak-base);
z-index: 100;
display: flex;
flex-direction: column;
height: 280px;
}
.shortcuts-panel [data-component="tabs"] {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
.shortcuts-tabs-row {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
position: relative;
padding: 12px 16px;
flex-shrink: 0;
}
.shortcuts-tabs-row > [data-component="icon-button"] {
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
}
.shortcuts-panel [data-slot="tabs-list"] {
height: auto;
justify-content: center;
gap: 24px;
padding: 4px;
}
.shortcuts-panel [data-slot="tabs-list"]::after {
display: none;
}
.shortcuts-panel [data-slot="tabs-trigger-wrapper"] {
background: transparent;
border: none;
font-weight: var(--font-weight-regular);
border-radius: 6px;
color: var(--color-text-weak);
}
.shortcuts-panel [data-slot="tabs-trigger-wrapper"]:hover {
background: var(--color-surface-base);
}
.shortcuts-panel [data-slot="tabs-trigger-wrapper"]:has([data-selected]) {
background: var(--color-surface-raised-base-active);
color: var(--color-text-strong);
}
.shortcuts-panel [data-slot="tabs-trigger"] {
padding: 4px 12px;
border-radius: 6px;
}
.shortcuts-panel [data-slot="tabs-trigger"]:focus-visible {
outline: none;
box-shadow: var(--shadow-xs-border-focus);
}
.shortcuts-panel [data-slot="tabs-content"] {
flex: 1;
overflow-y: auto;
padding: 20px;
display: flex;
justify-content: center;
}
.shortcuts-grid {
display: grid;
grid-template-columns: repeat(4, 240px);
gap: 4px 48px;
align-content: start;
}
@media (max-width: 1200px) {
.shortcuts-grid {
grid-template-columns: repeat(3, 240px);
gap: 4px 32px;
}
.shortcuts-panel [data-slot="tabs-list"] {
gap: 16px;
}
}
@media (max-width: 900px) {
.shortcuts-grid {
grid-template-columns: repeat(2, 240px);
gap: 4px 24px;
}
.shortcuts-panel [data-slot="tabs-list"] {
gap: 8px;
}
}
@media (max-width: 600px) {
.shortcuts-grid {
grid-template-columns: repeat(2, minmax(160px, 1fr));
gap: 4px 24px;
}
.shortcuts-panel [data-slot="tabs-list"] {
gap: 4px;
}
.shortcuts-panel [data-slot="tabs-trigger"] {
padding: 4px 8px;
}
}
@media (max-width: 420px) {
.shortcuts-grid {
grid-template-columns: 1fr;
}
}
.shortcut-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 6px 6px 12px;
margin: 0 -12px;
gap: 16px;
height: 36px;
background: transparent;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.1s ease;
text-align: left;
width: calc(100% + 24px);
box-sizing: border-box;
}
.shortcut-item:hover {
background: var(--color-surface-base);
}
.shortcut-item:hover .shortcut-key {
background: var(--color-background-stronger);
}
.shortcut-item:active {
background: var(--color-surface-raised-base);
}
.shortcut-item.shortcut-used span {
color: var(--color-text-interactive-base);
}
.shortcut-item.shortcut-used .shortcut-key {
color: var(--color-text-interactive-base);
border-color: var(--color-border-interactive-base);
background: var(--color-surface-interactive-base);
box-shadow: var(--shadow-xs-border-interactive);
}
.shortcut-keys {
display: flex;
gap: 4px;
flex-shrink: 0;
}
.shortcut-copied {
display: flex;
align-items: center;
justify-content: center;
color: var(--color-text-success-base);
margin-right: 4px;
}
.shortcut-key {
display: flex;
align-items: center;
justify-content: center;
min-width: 24px;
height: 24px;
padding: 0 6px;
font-family: var(--font-mono);
font-size: 12px;
color: var(--color-text-subtle);
box-shadow: var(--shadow-xs-border-base);
border-radius: 4px;
white-space: nowrap;
}
.shortcut-key-special {
font-size: 18px;
}
.shortcut-key-shift {
position: relative;
top: -2px;
}
/* Adjust main content and sidebar when shortcuts panel is open */
main.shortcuts-open {
padding-bottom: 280px;
}
.sidebar-shortcuts-open {
padding-bottom: 280px;
}
/* Adjust dialogs when shortcuts panel is open */
body:has([data-component="shortcuts-panel"]) [data-component="dialog"] {
bottom: 280px;
}
body:has([data-component="shortcuts-panel"]) [data-component="dialog-overlay"] {
bottom: 280px;
}
+53
View File
@@ -0,0 +1,53 @@
import { CURRENT_RELEASE } from "@/components/dialog-release-notes"
const STORAGE_KEY = "opencode:last-seen-version"
// ============================================================================
// DEV MODE: Set this to true to always show the release notes modal on startup
// Set to false for production behavior (only shows after updates)
// ============================================================================
const DEV_ALWAYS_SHOW_RELEASE_NOTES = true
/**
* Check if release notes should be shown
* Returns true if:
* - DEV_ALWAYS_SHOW_RELEASE_NOTES is true (for development)
* - OR the current version is newer than the last seen version
*/
export function shouldShowReleaseNotes(): boolean {
if (DEV_ALWAYS_SHOW_RELEASE_NOTES) {
console.log("[ReleaseNotes] DEV mode: always showing release notes")
return true
}
const lastSeen = localStorage.getItem(STORAGE_KEY)
if (!lastSeen) {
// First time user - show release notes
return true
}
// Compare versions - show if current is newer
return CURRENT_RELEASE.version !== lastSeen
}
/**
* Mark the current release notes as seen
* Call this when the user closes the release notes modal
*/
export function markReleaseNotesSeen(): void {
localStorage.setItem(STORAGE_KEY, CURRENT_RELEASE.version)
}
/**
* Get the current version
*/
export function getCurrentVersion(): string {
return CURRENT_RELEASE.version
}
/**
* Reset the seen status (useful for testing)
*/
export function resetReleaseNotesSeen(): void {
localStorage.removeItem(STORAGE_KEY)
}
+498 -128
View File
@@ -28,12 +28,14 @@ import { IconButton } from "@opencode-ai/ui/icon-button"
import { InlineInput } from "@opencode-ai/ui/inline-input"
import { Tooltip, TooltipKeybind } from "@opencode-ai/ui/tooltip"
import { HoverCard } from "@opencode-ai/ui/hover-card"
import { MessageNav } from "@opencode-ai/ui/message-nav"
import { DropdownMenu } from "@opencode-ai/ui/dropdown-menu"
import { Collapsible } from "@opencode-ai/ui/collapsible"
import { DiffChanges } from "@opencode-ai/ui/diff-changes"
import { Spinner } from "@opencode-ai/ui/spinner"
import { Dialog } from "@opencode-ai/ui/dialog"
import { getFilename } from "@opencode-ai/util/path"
import { Session } from "@opencode-ai/sdk/v2/client"
import { Session, type Message, type TextPart } from "@opencode-ai/sdk/v2/client"
import { usePlatform } from "@/context/platform"
import { createStore, produce, reconcile } from "solid-js/store"
import {
@@ -57,11 +59,13 @@ import { useDialog } from "@opencode-ai/ui/context/dialog"
import { useTheme, type ColorScheme } from "@opencode-ai/ui/theme"
import { DialogSelectProvider } from "@/components/dialog-select-provider"
import { DialogSelectServer } from "@/components/dialog-select-server"
import { useCommand, type CommandOption } from "@/context/command"
import { formatKeybind, useCommand, type CommandOption } from "@/context/command"
import { ConstrainDragXAxis } from "@/utils/solid-dnd"
import { navStart } from "@/utils/perf"
import { DialogSelectDirectory } from "@/components/dialog-select-directory"
import { DialogEditProject } from "@/components/dialog-edit-project"
import { ReleaseNotesHandler } from "@/components/release-notes-handler"
import { ShortcutsPanel } from "@/components/shortcuts-panel"
import { Titlebar } from "@/components/titlebar"
import { useServer } from "@/context/server"
@@ -83,6 +87,7 @@ export default function Layout(props: ParentProps) {
let scrollContainerRef: HTMLDivElement | undefined
const xlQuery = window.matchMedia("(min-width: 1280px)")
const [isLargeViewport, setIsLargeViewport] = createSignal(xlQuery.matches)
const [helpDropdownWidth, setHelpDropdownWidth] = createSignal<number | undefined>(undefined)
const handleViewportChange = (e: MediaQueryListEvent) => setIsLargeViewport(e.matches)
xlQuery.addEventListener("change", handleViewportChange)
onCleanup(() => xlQuery.removeEventListener("change", handleViewportChange))
@@ -399,7 +404,24 @@ export default function Layout(props: ParentProps) {
const currentProject = createMemo(() => {
const directory = params.dir ? base64Decode(params.dir) : undefined
if (!directory) return
return layout.projects.list().find((p) => p.worktree === directory || p.sandboxes?.includes(directory))
const projects = layout.projects.list()
const sandbox = projects.find((p) => p.sandboxes?.includes(directory))
if (sandbox) return sandbox
const direct = projects.find((p) => p.worktree === directory)
if (direct) return direct
const [child] = globalSync.child(directory)
const id = child.project
if (!id) return
const meta = globalSync.data.project.find((p) => p.id === id)
const root = meta?.worktree
if (!root) return
return projects.find((p) => p.worktree === root)
})
createEffect(
@@ -730,6 +752,13 @@ export default function Layout(props: ParentProps) {
keybind: "mod+b",
onSelect: () => layout.sidebar.toggle(),
},
{
id: "shortcuts.toggle",
title: "Toggle shortcuts panel",
category: "View",
keybind: "ctrl+/",
onSelect: () => layout.shortcuts.toggle(),
},
{
id: "project.open",
title: "Open project",
@@ -906,6 +935,241 @@ export default function Layout(props: ParentProps) {
}
}
const errorMessage = (err: unknown) => {
if (err && typeof err === "object" && "data" in err) {
const data = (err as { data?: { message?: string } }).data
if (data?.message) return data.message
}
if (err instanceof Error) return err.message
return "Request failed"
}
const deleteWorkspace = async (directory: string) => {
const current = currentProject()
if (!current) return
if (directory === current.worktree) return
const result = await globalSDK.client.worktree
.remove({ directory: current.worktree, worktreeRemoveInput: { directory } })
.then((x) => x.data)
.catch((err) => {
showToast({
title: "Failed to delete workspace",
description: errorMessage(err),
})
return false
})
if (!result) return
layout.projects.close(directory)
layout.projects.open(current.worktree)
if (params.dir && base64Decode(params.dir) === directory) {
navigateToProject(current.worktree)
}
}
const resetWorkspace = async (directory: string) => {
const current = currentProject()
if (!current) return
if (directory === current.worktree) return
const progress = showToast({
persistent: true,
title: "Resetting workspace",
description: "This may take a minute.",
})
const dismiss = () => toaster.dismiss(progress)
const sessions = await globalSDK.client.session
.list({ directory })
.then((x) => x.data ?? [])
.catch(() => [])
const result = await globalSDK.client.worktree
.reset({ directory: current.worktree, worktreeResetInput: { directory } })
.then((x) => x.data)
.catch((err) => {
dismiss()
showToast({
title: "Failed to reset workspace",
description: errorMessage(err),
})
return false
})
if (!result) {
dismiss()
return
}
const archivedAt = Date.now()
await Promise.all(
sessions
.filter((session) => session.time.archived === undefined)
.map((session) =>
globalSDK.client.session
.update({
sessionID: session.id,
directory: session.directory,
time: { archived: archivedAt },
})
.catch(() => undefined),
),
)
await globalSDK.client.instance.dispose({ directory }).catch(() => undefined)
dismiss()
const href = `/${base64Encode(directory)}/session`
navigate(href)
layout.mobileSidebar.hide()
showToast({
title: "Workspace reset",
description: "Workspace now matches the default branch.",
})
}
function DialogDeleteWorkspace(props: { directory: string }) {
const name = createMemo(() => getFilename(props.directory))
const [data, setData] = createStore({
status: "loading" as "loading" | "ready" | "error",
dirty: false,
})
onMount(() => {
const current = currentProject()
if (!current) {
setData({ status: "error", dirty: false })
return
}
globalSDK.client.file
.status({ directory: props.directory })
.then((x) => {
const files = x.data ?? []
const dirty = files.length > 0
setData({ status: "ready", dirty })
})
.catch(() => {
setData({ status: "error", dirty: false })
})
})
const handleDelete = async () => {
await deleteWorkspace(props.directory)
dialog.close()
}
const description = () => {
if (data.status === "loading") return "Checking for unmerged changes..."
if (data.status === "error") return "Unable to verify git status."
if (!data.dirty) return "No unmerged changes detected."
return "Unmerged changes detected in this workspace."
}
return (
<Dialog title="Delete workspace" fit>
<div class="flex flex-col gap-4 px-2.5 pb-3">
<div class="flex flex-col gap-1">
<span class="text-14-regular text-text-strong">Delete workspace "{name()}"?</span>
<span class="text-12-regular text-text-weak">{description()}</span>
</div>
<div class="flex justify-end gap-2">
<Button variant="ghost" size="large" onClick={() => dialog.close()}>
Cancel
</Button>
<Button variant="primary" size="large" disabled={data.status === "loading"} onClick={handleDelete}>
Delete workspace
</Button>
</div>
</div>
</Dialog>
)
}
function DialogResetWorkspace(props: { directory: string }) {
const name = createMemo(() => getFilename(props.directory))
const [state, setState] = createStore({
status: "loading" as "loading" | "ready" | "error",
dirty: false,
sessions: [] as Session[],
})
const refresh = async () => {
const sessions = await globalSDK.client.session
.list({ directory: props.directory })
.then((x) => x.data ?? [])
.catch(() => [])
const active = sessions.filter((session) => session.time.archived === undefined)
setState({ sessions: active })
}
onMount(() => {
const current = currentProject()
if (!current) {
setState({ status: "error", dirty: false })
return
}
globalSDK.client.file
.status({ directory: props.directory })
.then((x) => {
const files = x.data ?? []
const dirty = files.length > 0
setState({ status: "ready", dirty })
void refresh()
})
.catch(() => {
setState({ status: "error", dirty: false })
})
})
const handleReset = () => {
dialog.close()
void resetWorkspace(props.directory)
}
const archivedCount = () => state.sessions.length
const description = () => {
if (state.status === "loading") return "Checking for unmerged changes..."
if (state.status === "error") return "Unable to verify git status."
if (!state.dirty) return "No unmerged changes detected."
return "Unmerged changes detected in this workspace."
}
const archivedLabel = () => {
const count = archivedCount()
if (count === 0) return "No active sessions will be archived."
const label = count === 1 ? "1 session" : `${count} sessions`
return `${label} will be archived.`
}
return (
<Dialog title="Reset workspace" fit>
<div class="flex flex-col gap-4 px-2.5 pb-3">
<div class="flex flex-col gap-1">
<span class="text-14-regular text-text-strong">Reset workspace "{name()}"?</span>
<span class="text-12-regular text-text-weak">
{description()} {archivedLabel()} This will reset the workspace to match the default branch.
</span>
</div>
<div class="flex justify-end gap-2">
<Button variant="ghost" size="large" onClick={() => dialog.close()}>
Cancel
</Button>
<Button variant="primary" size="large" disabled={state.status === "loading"} onClick={handleReset}>
Reset workspace
</Button>
</div>
</div>
</Dialog>
)
}
createEffect(
on(
() => ({ ready: pageReady(), dir: params.dir, id: params.id }),
@@ -927,6 +1191,11 @@ export default function Layout(props: ParentProps) {
),
)
createEffect(() => {
const sidebarWidth = layout.sidebar.opened() ? layout.sidebar.width() : 48
document.documentElement.style.setProperty("--dialog-left-margin", `${sidebarWidth}px`)
})
createEffect(() => {
const project = currentProject()
if (!project) return
@@ -975,11 +1244,15 @@ export default function Layout(props: ParentProps) {
function workspaceIds(project: LocalProject | undefined) {
if (!project) return []
const dirs = [project.worktree, ...(project.sandboxes ?? [])]
const existing = store.workspaceOrder[project.worktree]
if (!existing) return dirs
const active = currentProject()
const directory = active?.worktree === project.worktree && params.dir ? base64Decode(params.dir) : undefined
const next = directory && directory !== project.worktree && !dirs.includes(directory) ? [...dirs, directory] : dirs
const keep = existing.filter((d) => dirs.includes(d))
const missing = dirs.filter((d) => !existing.includes(d))
const existing = store.workspaceOrder[project.worktree]
if (!existing) return next
const keep = existing.filter((d) => next.includes(d))
const missing = next.filter((d) => !existing.includes(d))
return [...keep, ...missing]
}
@@ -1049,7 +1322,13 @@ export default function Layout(props: ParentProps) {
)
}
const SessionItem = (props: { session: Session; slug: string; mobile?: boolean; dense?: boolean }): JSX.Element => {
const SessionItem = (props: {
session: Session
slug: string
mobile?: boolean
dense?: boolean
popover?: boolean
}): JSX.Element => {
const notification = useNotification()
const notifications = createMemo(() => notification.session.unseen(props.session.id))
const hasError = createMemo(() => notifications().some((n) => n.type === "error"))
@@ -1083,63 +1362,100 @@ export default function Layout(props: ParentProps) {
return agent?.color
})
const hoverMessages = createMemo(() =>
sessionStore.message[props.session.id]?.filter((message) => message.role === "user"),
)
const hoverReady = createMemo(() => sessionStore.message[props.session.id] !== undefined)
const hoverAllowed = createMemo(() => !props.mobile && layout.sidebar.opened())
const hoverEnabled = createMemo(() => (props.popover ?? true) && hoverAllowed())
const isActive = createMemo(() => props.session.id === params.id)
const messageLabel = (message: Message) => {
const parts = sessionStore.part[message.id] ?? []
const text = parts.find((part): part is TextPart => part?.type === "text" && !part.synthetic && !part.ignored)
return text?.text
}
const item = (
<A
href={`${props.slug}/session/${props.session.id}`}
class={`flex items-center justify-between gap-3 min-w-0 text-left w-full focus:outline-none transition-[padding] group-hover/session:pr-7 group-focus-within/session:pr-7 group-active/session:pr-7 ${props.dense ? "py-0.5" : "py-1"}`}
onMouseEnter={() => prefetchSession(props.session, "high")}
onFocus={() => prefetchSession(props.session, "high")}
>
<div class="flex items-center gap-1 w-full">
<div
class="shrink-0 size-6 flex items-center justify-center"
style={{ color: tint() ?? "var(--icon-interactive-base)" }}
>
<Switch fallback={<Icon name="dash" size="small" class="text-icon-weak" />}>
<Match when={isWorking()}>
<Spinner class="size-[15px]" />
</Match>
<Match when={hasPermissions()}>
<div class="size-1.5 rounded-full bg-surface-warning-strong" />
</Match>
<Match when={hasError()}>
<div class="size-1.5 rounded-full bg-text-diff-delete-base" />
</Match>
<Match when={notifications().length > 0}>
<div class="size-1.5 rounded-full bg-text-interactive-base" />
</Match>
</Switch>
</div>
<InlineEditor
id={`session:${props.session.id}`}
value={() => props.session.title}
onSave={(next) => renameSession(props.session, next)}
class="text-14-regular text-text-strong grow-1 min-w-0 overflow-hidden text-ellipsis truncate"
displayClass="text-14-regular text-text-strong grow-1 min-w-0 overflow-hidden text-ellipsis truncate"
stopPropagation
/>
<Show when={props.session.summary}>
{(summary) => (
<div class="group-hover/session:hidden group-active/session:hidden group-focus-within/session:hidden">
<DiffChanges changes={summary()} />
</div>
)}
</Show>
</div>
</A>
)
return (
<div
data-session-id={props.session.id}
class="group/session relative w-full rounded-md cursor-default transition-colors pl-2 pr-3
hover:bg-surface-raised-base-hover focus-within:bg-surface-raised-base-hover has-[.active]:bg-surface-base-active"
>
<A
href={`${props.slug}/session/${props.session.id}`}
class={`flex items-center justify-between gap-3 min-w-0 text-left w-full focus:outline-none transition-[padding] group-hover/session:pr-7 group-focus-within/session:pr-7 group-active/session:pr-7 ${props.dense ? "py-0.5" : "py-1"}`}
onMouseEnter={() => prefetchSession(props.session, "high")}
onFocus={() => prefetchSession(props.session, "high")}
>
<div class="flex items-center gap-1 w-full">
<div
class="shrink-0 size-6 flex items-center justify-center"
style={{ color: tint() ?? "var(--icon-interactive-base)" }}
>
<Switch fallback={<Icon name="dash" size="small" class="text-icon-weak" />}>
<Match when={isWorking()}>
<Spinner class="size-[15px]" />
</Match>
<Match when={hasPermissions()}>
<div class="size-1.5 rounded-full bg-surface-warning-strong" />
</Match>
<Match when={hasError()}>
<div class="size-1.5 rounded-full bg-text-diff-delete-base" />
</Match>
<Match when={notifications().length > 0}>
<div class="size-1.5 rounded-full bg-text-interactive-base" />
</Match>
</Switch>
</div>
<Tooltip
placement="top-start"
value={props.session.title}
gutter={0}
openDelay={3000}
class="grow-1 min-w-0"
>
<InlineEditor
id={`session:${props.session.id}`}
value={() => props.session.title}
onSave={(next) => renameSession(props.session, next)}
class="text-14-regular text-text-strong grow-1 min-w-0 overflow-hidden text-ellipsis truncate"
displayClass="text-14-regular text-text-strong grow-1 min-w-0 overflow-hidden text-ellipsis truncate"
stopPropagation
/>
<Show
when={hoverEnabled()}
fallback={
<Tooltip placement={props.mobile ? "bottom" : "right"} value={props.session.title} gutter={10}>
{item}
</Tooltip>
<Show when={props.session.summary}>
{(summary) => (
<div class="group-hover/session:hidden group-active/session:hidden group-focus-within/session:hidden">
<DiffChanges changes={summary()} />
</div>
)}
}
>
<HoverCard openDelay={150} closeDelay={100} placement="right" gutter={12} trigger={item}>
<Show when={hoverReady()} fallback={<div class="text-12-regular text-text-weak">Loading messages</div>}>
<MessageNav
messages={hoverMessages() ?? []}
current={undefined}
getLabel={messageLabel}
onMessageSelect={(message) => {
if (!isActive()) {
navigate(`${props.slug}/session/${props.session.id}#message-${message.id}`)
return
}
window.location.hash = `message-${message.id}`
window.dispatchEvent(new HashChangeEvent("hashchange"))
}}
size="normal"
class="w-60"
/>
</Show>
</div>
</A>
</HoverCard>
</Show>
<div
class={`hidden group-hover/session:flex group-active/session:flex group-focus-within/session:flex text-text-base gap-1 items-center absolute ${props.dense ? "top-0.5 right-0.5" : "top-1 right-1"}`}
>
@@ -1205,6 +1521,7 @@ export default function Layout(props: ParentProps) {
const SortableWorkspace = (props: { directory: string; project: LocalProject; mobile?: boolean }): JSX.Element => {
const sortable = createSortable(props.directory)
const [workspaceStore, setWorkspaceStore] = globalSync.child(props.directory)
const [menuOpen, setMenuOpen] = createSignal(false)
const slug = createMemo(() => base64Encode(props.directory))
const sessions = createMemo(() =>
workspaceStore.session
@@ -1239,62 +1556,91 @@ export default function Layout(props: ParentProps) {
<div use:sortable classList={{ "opacity-30": sortable.isActiveDraggable }}>
<Collapsible variant="ghost" open={open()} class="shrink-0" onOpenChange={openWrapper}>
<div class="px-2 py-1">
<div class="group/trigger relative">
<Collapsible.Trigger class="flex items-center justify-between w-full pl-2 pr-16 py-1.5 rounded-md hover:bg-surface-raised-base-hover">
<div class="flex items-center gap-1 min-w-0 flex-1">
<div class="flex items-center justify-center shrink-0 size-6">
<Icon name="branch" size="small" />
</div>
<span class="text-14-medium text-text-base shrink-0">{local() ? "local" : "sandbox"} :</span>
<Show
when={!local()}
fallback={
<span class="text-14-medium text-text-base min-w-0 truncate">
{workspaceStore.vcs?.branch ?? getFilename(props.directory)}
</span>
}
>
<InlineEditor
id={`workspace:${props.directory}`}
value={workspaceValue}
onSave={(next) => {
const trimmed = next.trim()
if (!trimmed) return
renameWorkspace(props.directory, trimmed)
setEditor("value", workspaceValue())
}}
class="text-14-medium text-text-base min-w-0 truncate"
displayClass="text-14-medium text-text-base min-w-0 truncate"
editing={workspaceEditActive()}
stopPropagation={false}
openOnDblClick={false}
<div class="group/workspace relative">
<div class="flex items-center gap-1">
<Collapsible.Trigger class="flex items-center justify-between w-full pl-2 pr-16 py-1.5 rounded-md hover:bg-surface-raised-base-hover">
<div class="flex items-center gap-1 min-w-0 flex-1">
<div class="flex items-center justify-center shrink-0 size-6">
<Icon name="branch" size="small" />
</div>
<span class="text-14-medium text-text-base shrink-0">{local() ? "local" : "sandbox"} :</span>
<Show
when={!local()}
fallback={
<span class="text-14-medium text-text-base min-w-0 truncate">
{workspaceStore.vcs?.branch ?? getFilename(props.directory)}
</span>
}
>
<InlineEditor
id={`workspace:${props.directory}`}
value={workspaceValue}
onSave={(next) => {
const trimmed = next.trim()
if (!trimmed) return
renameWorkspace(props.directory, trimmed)
setEditor("value", workspaceValue())
}}
class="text-14-medium text-text-base min-w-0 truncate"
displayClass="text-14-medium text-text-base min-w-0 truncate"
editing={workspaceEditActive()}
stopPropagation={false}
openOnDblClick={false}
/>
</Show>
<Icon
name={open() ? "chevron-down" : "chevron-right"}
size="small"
class="shrink-0 text-icon-base opacity-0 transition-opacity group-hover/workspace:opacity-100 group-focus-within/workspace:opacity-100"
/>
</Show>
<Icon
name={open() ? "chevron-down" : "chevron-right"}
size="small"
class="shrink-0 text-icon-base opacity-0 transition-opacity group-hover/trigger:opacity-100 group-focus-within/trigger:opacity-100"
/>
</div>
</Collapsible.Trigger>
<div class="absolute right-1 top-1/2 -translate-y-1/2 hidden items-center gap-0.5 pointer-events-none group-hover/trigger:flex group-focus-within/trigger:flex">
<IconButton icon="dot-grid" variant="ghost" class="size-6 rounded-md pointer-events-auto" />
<TooltipKeybind
class="pointer-events-auto"
placement="right"
title="New session"
keybind={command.keybind("session.new")}
</div>
</Collapsible.Trigger>
<div
class="absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-0.5 transition-opacity"
classList={{
"opacity-100 pointer-events-auto": menuOpen(),
"opacity-0 pointer-events-none": !menuOpen(),
"group-hover/workspace:opacity-100 group-hover/workspace:pointer-events-auto": true,
"group-focus-within/workspace:opacity-100 group-focus-within/workspace:pointer-events-auto": true,
}}
>
<IconButton
icon="plus-small"
variant="ghost"
class="size-6 rounded-md"
onClick={() => navigate(`/${slug()}/session`)}
/>
</TooltipKeybind>
<DropdownMenu open={menuOpen()} onOpenChange={setMenuOpen}>
<Tooltip value="More options" placement="top">
<DropdownMenu.Trigger as={IconButton} icon="dot-grid" variant="ghost" class="size-6 rounded-md" />
</Tooltip>
<DropdownMenu.Portal>
<DropdownMenu.Content>
<DropdownMenu.Item onSelect={() => navigate(`/${slug()}/session`)}>
<DropdownMenu.ItemLabel>New session</DropdownMenu.ItemLabel>
</DropdownMenu.Item>
<DropdownMenu.Item
disabled={local()}
onSelect={() => dialog.show(() => <DialogResetWorkspace directory={props.directory} />)}
>
<DropdownMenu.ItemLabel>Reset workspace</DropdownMenu.ItemLabel>
</DropdownMenu.Item>
<DropdownMenu.Item
disabled={local()}
onSelect={() => dialog.show(() => <DialogDeleteWorkspace directory={props.directory} />)}
>
<DropdownMenu.ItemLabel>Delete workspace</DropdownMenu.ItemLabel>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu>
<TooltipKeybind placement="right" title="New session" keybind={command.keybind("session.new")}>
<IconButton
icon="plus-small"
variant="ghost"
class="size-6 rounded-md"
onClick={() => navigate(`/${slug()}/session`)}
/>
</TooltipKeybind>
</div>
</div>
</div>
</div>
<Collapsible.Content>
<nav class="flex flex-col gap-1 px-2">
<Button
@@ -1412,6 +1758,7 @@ export default function Layout(props: ParentProps) {
slug={base64Encode(props.project.worktree)}
dense
mobile={props.mobile}
popover={false}
/>
)}
</For>
@@ -1428,7 +1775,13 @@ export default function Layout(props: ParentProps) {
</div>
<For each={sessions(directory)}>
{(session) => (
<SessionItem session={session} slug={base64Encode(directory)} dense mobile={props.mobile} />
<SessionItem
session={session}
slug={base64Encode(directory)}
dense
mobile={props.mobile}
popover={false}
/>
)}
</For>
</div>
@@ -1520,15 +1873,6 @@ export default function Layout(props: ParentProps) {
const projectId = createMemo(() => project()?.id ?? "")
const workspaces = createMemo(() => workspaceIds(project()))
const errorMessage = (err: unknown) => {
if (err && typeof err === "object" && "data" in err) {
const data = (err as { data?: { message?: string } }).data
if (data?.message) return data.message
}
if (err instanceof Error) return err.message
return "Request failed"
}
const createWorkspace = async () => {
const current = project()
if (!current) return
@@ -1553,7 +1897,7 @@ export default function Layout(props: ParentProps) {
const homedir = createMemo(() => sync.data.path.home)
return (
<div class="flex h-full w-full overflow-hidden">
<div class="flex h-full w-full overflow-hidden" classList={{ "sidebar-shortcuts-open": layout.shortcuts.opened() }}>
<div class="w-16 shrink-0 bg-background-base flex flex-col items-center overflow-hidden">
<div class="flex-1 min-h-0 w-full">
<DragDropProvider
@@ -1590,17 +1934,38 @@ export default function Layout(props: ParentProps) {
</DragDropProvider>
</div>
<div class="shrink-0 w-full pt-3 pb-3 flex flex-col items-center gap-2">
<Tooltip placement={sidebarProps.mobile ? "bottom" : "right"} value="Settings">
<Tooltip placement={sidebarProps.mobile ? "bottom" : "right"} value="Settings" class="hidden">
<IconButton disabled icon="settings-gear" variant="ghost" size="large" />
</Tooltip>
<Tooltip placement={sidebarProps.mobile ? "bottom" : "right"} value="Help">
<IconButton
icon="help"
variant="ghost"
size="large"
onClick={() => platform.openLink("https://opencode.ai/desktop-feedback")}
/>
</Tooltip>
<DropdownMenu
placement="top-start"
gutter={8}
onOpenChange={(open) => {
if (open && layout.sidebar.opened()) {
setHelpDropdownWidth(layout.sidebar.width() - 16)
return
}
if (!open) setHelpDropdownWidth(undefined)
}}
>
<Tooltip placement={sidebarProps.mobile ? "bottom" : "right"} value="Help">
<DropdownMenu.Trigger as={IconButton} icon="question-mark" variant="ghost" size="large" />
</Tooltip>
<DropdownMenu.Portal>
<DropdownMenu.Content
style={{
width: helpDropdownWidth() ? `${helpDropdownWidth()}px` : undefined,
}}
>
<DropdownMenu.Item onSelect={() => platform.openLink("https://opencode.ai/desktop-feedback")}>
Submit feedback
</DropdownMenu.Item>
<DropdownMenu.Item class="flex justify-between gap-6" onSelect={() => layout.shortcuts.toggle()}>
Keyboard shortcuts <span class="text-text-weaker">{formatKeybind("ctrl+/")}</span>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu>
</div>
</div>
@@ -1811,12 +2176,17 @@ export default function Layout(props: ParentProps) {
classList={{
"size-full overflow-x-hidden flex flex-col items-start contain-strict border-t border-border-weak-base": true,
"xl:border-l xl:rounded-tl-sm": !layout.sidebar.opened(),
"shortcuts-open": layout.shortcuts.opened(),
}}
>
{props.children}
</main>
</div>
<Show when={layout.shortcuts.opened()}>
<ShortcutsPanel onClose={() => layout.shortcuts.close()} />
</Show>
<Toast.Region />
<ReleaseNotesHandler />
</div>
)
}
+89 -68
View File
@@ -18,7 +18,7 @@ import { useCodeComponent } from "@opencode-ai/ui/context/code"
import { SessionTurn } from "@opencode-ai/ui/session-turn"
import { createAutoScroll } from "@opencode-ai/ui/hooks"
import { SessionReview } from "@opencode-ai/ui/session-review"
import { SessionMessageRail } from "@opencode-ai/ui/session-message-rail"
import { Mark } from "@opencode-ai/ui/logo"
import { DragDropProvider, DragDropSensors, DragOverlay, SortableProvider, closestCenter } from "@thisbeyond/solid-dnd"
import type { DragEvent } from "@thisbeyond/solid-dnd"
@@ -788,17 +788,14 @@ export default function Page() {
.filter((tab) => tab !== "context"),
)
const reviewTab = createMemo(() => hasReview() || tabs().active() === "review")
const mobileReview = createMemo(() => !isDesktop() && hasReview() && store.mobileTab === "review")
const mobileReview = createMemo(() => !isDesktop() && view().reviewPanel.opened() && store.mobileTab === "review")
const showTabs = createMemo(
() => view().reviewPanel.opened() && (hasReview() || tabs().all().length > 0 || contextOpen()),
)
const showTabs = createMemo(() => view().reviewPanel.opened())
const activeTab = createMemo(() => {
const active = tabs().active()
if (active) return active
if (reviewTab()) return "review"
if (hasReview()) return "review"
const first = openedTabs()[0]
if (first) return first
@@ -1096,8 +1093,8 @@ export default function Page() {
<div class="relative bg-background-base size-full overflow-hidden flex flex-col">
<SessionHeader />
<div class="flex-1 min-h-0 flex flex-col md:flex-row">
{/* Mobile tab bar - only shown on mobile when there are diffs */}
<Show when={!isDesktop() && hasReview()}>
{/* Mobile tab bar - only shown on mobile when user opened review */}
<Show when={!isDesktop() && view().reviewPanel.opened()}>
<Tabs class="h-auto">
<Tabs.List>
<Tabs.Trigger
@@ -1114,7 +1111,10 @@ export default function Page() {
classes={{ button: "w-full" }}
onClick={() => setStore("mobileTab", "review")}
>
{reviewCount()} Files Changed
<Switch>
<Match when={hasReview()}>{reviewCount()} Files Changed</Match>
<Match when={true}>Review</Match>
</Switch>
</Tabs.Trigger>
</Tabs.List>
</Tabs>
@@ -1139,41 +1139,40 @@ export default function Page() {
when={!mobileReview()}
fallback={
<div class="relative h-full overflow-hidden">
<Show
when={diffsReady()}
fallback={<div class="px-4 py-4 text-text-weak">Loading changes...</div>}
>
<SessionReviewTab
diffs={diffs}
view={view}
diffStyle="unified"
onViewFile={(path) => {
const value = file.tab(path)
tabs().open(value)
file.load(path)
}}
classes={{
root: "pb-[calc(var(--prompt-height,8rem)+24px)]",
header: "px-4",
container: "px-4",
}}
/>
</Show>
<Switch>
<Match when={hasReview()}>
<Show
when={diffsReady()}
fallback={<div class="px-4 py-4 text-text-weak">Loading changes...</div>}
>
<SessionReviewTab
diffs={diffs}
view={view}
diffStyle="unified"
onViewFile={(path) => {
const value = file.tab(path)
tabs().open(value)
file.load(path)
}}
classes={{
root: "pb-[calc(var(--prompt-height,8rem)+32px)]",
header: "px-4",
container: "px-4",
}}
/>
</Show>
</Match>
<Match when={true}>
<div class="px-4 pt-18 pb-6 flex flex-col items-center justify-center text-center gap-3">
<Mark class="w-6 opacity-40" />
<div class="text-13-regular text-text-weak max-w-56">No changes in this session yet.</div>
</div>
</Match>
</Switch>
</div>
}
>
<div class="relative w-full h-full min-w-0">
<Show when={isDesktop()}>
<div class="absolute inset-0 pointer-events-none z-10">
<SessionMessageRail
messages={visibleUserMessages()}
current={activeMessage()}
onMessageSelect={scrollToMessage}
wide={!showTabs()}
class="pointer-events-auto"
/>
</div>
</Show>
<div
ref={setScrollRef}
onScroll={(e) => {
@@ -1182,11 +1181,29 @@ export default function Page() {
}}
onClick={autoScroll.handleInteraction}
class="relative min-w-0 w-full h-full overflow-y-auto no-scrollbar"
style={{ "--session-title-height": info()?.title ? "40px" : "0px" }}
>
<Show when={info()?.title}>
<div
classList={{
"sticky top-0 z-30 bg-background-stronger": true,
"w-full": true,
"px-4 md:px-6": true,
"md:max-w-200 md:mx-auto": !showTabs(),
}}
>
<div class="h-10 flex items-center">
<h1 class="text-16-medium text-text-strong truncate">{info()?.title}</h1>
</div>
</div>
</Show>
<div
ref={autoScroll.contentRef}
class="flex flex-col gap-32 items-start justify-start pb-[calc(var(--prompt-height,8rem)+64px)] md:pb-[calc(var(--prompt-height,10rem)+64px)] transition-[margin]"
classList={{
"w-full": true,
"md:max-w-200 md:mx-auto": !showTabs(),
"mt-0.5": !showTabs(),
"mt-0": showTabs(),
}}
@@ -1237,6 +1254,7 @@ export default function Page() {
data-message-id={message.id}
classList={{
"min-w-0 w-full max-w-full": true,
"md:max-w-200": !showTabs(),
"last:min-h-[calc(100vh-5.5rem-var(--prompt-height,8rem)-64px)] md:last:min-h-[calc(100vh-4.5rem-var(--prompt-height,10rem)-64px)]":
platform.platform !== "desktop",
"last:min-h-[calc(100vh-7rem-var(--prompt-height,8rem)-64px)] md:last:min-h-[calc(100vh-6rem-var(--prompt-height,10rem)-64px)]":
@@ -1253,15 +1271,8 @@ export default function Page() {
}
classes={{
root: "min-w-0 w-full relative",
content:
"flex flex-col justify-between !overflow-visible [&_[data-slot=session-turn-message-header]]:top-[-32px]",
container:
"px-4 md:px-6 " +
(!showTabs()
? "md:max-w-200 md:mx-auto"
: visibleUserMessages().length > 1
? "md:pr-6 md:pl-18"
: ""),
content: "flex flex-col justify-between !overflow-visible",
container: "w-full px-4 md:px-6",
}}
/>
</div>
@@ -1351,7 +1362,7 @@ export default function Page() {
<Tabs value={activeTab()} onChange={openTab}>
<div class="sticky top-0 shrink-0 flex">
<Tabs.List>
<Show when={reviewTab()}>
<Show when={true}>
<Tabs.Trigger value="review">
<div class="flex items-center gap-3">
<Show when={diffs()}>
@@ -1404,26 +1415,36 @@ export default function Page() {
</div>
</Tabs.List>
</div>
<Show when={reviewTab()}>
<Show when={true}>
<Tabs.Content value="review" class="flex flex-col h-full overflow-hidden contain-strict">
<Show when={activeTab() === "review"}>
<div class="relative pt-2 flex-1 min-h-0 overflow-hidden">
<Show
when={diffsReady()}
fallback={<div class="px-6 py-4 text-text-weak">Loading changes...</div>}
>
<SessionReviewTab
diffs={diffs}
view={view}
diffStyle={layout.review.diffStyle()}
onDiffStyleChange={layout.review.setDiffStyle}
onViewFile={(path) => {
const value = file.tab(path)
tabs().open(value)
file.load(path)
}}
/>
</Show>
<Switch>
<Match when={hasReview()}>
<Show
when={diffsReady()}
fallback={<div class="px-6 py-4 text-text-weak">Loading changes...</div>}
>
<SessionReviewTab
diffs={diffs}
view={view}
diffStyle={layout.review.diffStyle()}
onDiffStyleChange={layout.review.setDiffStyle}
onViewFile={(path) => {
const value = file.tab(path)
tabs().open(value)
file.load(path)
}}
/>
</Show>
</Match>
<Match when={true}>
<div class="px-6 pt-18 pb-6 flex flex-col items-center justify-center text-center gap-3">
<Mark class="w-6 opacity-40" />
<div class="text-13-regular text-text-weak max-w-56">No changes in this session yet.</div>
</div>
</Match>
</Switch>
</div>
</Show>
</Tabs.Content>
+45 -6
View File
@@ -17,6 +17,36 @@ type PersistTarget = {
const LEGACY_STORAGE = "default.dat"
const GLOBAL_STORAGE = "opencode.global.dat"
function quota(error: unknown) {
if (error instanceof DOMException) {
if (error.name === "QuotaExceededError") return true
if (error.name === "NS_ERROR_DOM_QUOTA_REACHED") return true
if (error.code === 22 || error.code === 1014) return true
return false
}
if (!error || typeof error !== "object") return false
const name = (error as { name?: string }).name
if (name === "QuotaExceededError" || name === "NS_ERROR_DOM_QUOTA_REACHED") return true
return false
}
function write(storage: Storage, key: string, value: string) {
try {
storage.setItem(key, value)
return
} catch (error) {
if (!quota(error)) throw error
}
try {
storage.removeItem(key)
storage.setItem(key, value)
} catch (error) {
if (!quota(error)) throw error
}
}
function snapshot(value: unknown) {
return JSON.parse(JSON.stringify(value)) as unknown
}
@@ -67,10 +97,19 @@ function workspaceStorage(dir: string) {
function localStorageWithPrefix(prefix: string): SyncStorage {
const base = `${prefix}:`
const item = (key: string) => base + key
return {
getItem: (key) => localStorage.getItem(base + key),
setItem: (key, value) => localStorage.setItem(base + key, value),
removeItem: (key) => localStorage.removeItem(base + key),
getItem: (key) => localStorage.getItem(item(key)),
setItem: (key, value) => write(localStorage, item(key), value),
removeItem: (key) => localStorage.removeItem(item(key)),
}
}
function localStorageDirect(): SyncStorage {
return {
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => write(localStorage, key, value),
removeItem: (key) => localStorage.removeItem(key),
}
}
@@ -99,7 +138,7 @@ export function removePersisted(target: { storage?: string; key: string }) {
}
if (!target.storage) {
localStorage.removeItem(target.key)
localStorageDirect().removeItem(target.key)
return
}
@@ -120,12 +159,12 @@ export function persisted<T>(
const currentStorage = (() => {
if (isDesktop) return platform.storage?.(config.storage)
if (!config.storage) return localStorage
if (!config.storage) return localStorageDirect()
return localStorageWithPrefix(config.storage)
})()
const legacyStorage = (() => {
if (!isDesktop) return localStorage
if (!isDesktop) return localStorageDirect()
if (!config.storage) return platform.storage?.()
return platform.storage?.(LEGACY_STORAGE)
})()
+1
View File
@@ -218,6 +218,7 @@ export namespace Billing {
customer: customer.customerID,
customer_update: {
name: "auto",
address: "auto",
},
}
: {
@@ -0,0 +1,20 @@
import { describe, expect, test } from "bun:test"
import { getWeekBounds } from "./date"
describe("util.date.getWeekBounds", () => {
test("returns a Monday-based week for Sunday dates", () => {
const date = new Date("2026-01-18T12:00:00Z")
const bounds = getWeekBounds(date)
expect(bounds.start.toISOString()).toBe("2026-01-12T00:00:00.000Z")
expect(bounds.end.toISOString()).toBe("2026-01-19T00:00:00.000Z")
})
test("returns a seven day window", () => {
const date = new Date("2026-01-14T12:00:00Z")
const bounds = getWeekBounds(date)
const span = bounds.end.getTime() - bounds.start.getTime()
expect(span).toBe(7 * 24 * 60 * 60 * 1000)
})
})
+2 -2
View File
@@ -1,7 +1,7 @@
export function getWeekBounds(date: Date) {
const dayOfWeek = date.getUTCDay()
const offset = (date.getUTCDay() + 6) % 7
const start = new Date(date)
start.setUTCDate(date.getUTCDate() - dayOfWeek + 1)
start.setUTCDate(date.getUTCDate() - offset)
start.setUTCHours(0, 0, 0, 0)
const end = new Date(start)
end.setUTCDate(start.getUTCDate() + 7)
+10 -11
View File
@@ -26,17 +26,16 @@ if (import.meta.env.DEV && !(root instanceof HTMLElement)) {
)
}
const isWindows = ostype() === "windows"
if (isWindows) {
const originalGetComputedStyle = window.getComputedStyle
window.getComputedStyle = ((elt: Element, pseudoElt?: string | null) => {
if (!(elt instanceof Element)) {
// WebView2 can call into Floating UI with non-elements; fall back to a safe element.
return originalGetComputedStyle(document.documentElement, pseudoElt ?? undefined)
}
return originalGetComputedStyle(elt, pseudoElt ?? undefined)
}) as typeof window.getComputedStyle
}
// Floating UI can call getComputedStyle with non-elements (e.g., null refs, virtual elements).
// This happens on all platforms (WebView2 on Windows, WKWebView on macOS), not just Windows.
const originalGetComputedStyle = window.getComputedStyle
window.getComputedStyle = ((elt: Element, pseudoElt?: string | null) => {
if (!(elt instanceof Element)) {
// Fall back to a safe element when a non-element is passed.
return originalGetComputedStyle(document.documentElement, pseudoElt ?? undefined)
}
return originalGetComputedStyle(elt, pseudoElt ?? undefined)
}) as typeof window.getComputedStyle
let update: Update | null = null
@@ -16,7 +16,6 @@ import { iife } from "@opencode-ai/util/iife"
import { Binary } from "@opencode-ai/util/binary"
import { NamedError } from "@opencode-ai/util/error"
import { DateTime } from "luxon"
import { SessionMessageRail } from "@opencode-ai/ui/session-message-rail"
import { createStore } from "solid-js/store"
import z from "zod"
import NotFound from "../[...404]"
@@ -296,13 +295,13 @@ export default function () {
{(message) => (
<SessionTurn
sessionID={data().sessionID}
sessionTitle={info().title}
messageID={message.id}
stepsExpanded={store.expandedSteps[message.id] ?? false}
onStepsExpandedToggle={() => setStore("expandedSteps", message.id, (v) => !v)}
classes={{
root: "min-w-0 w-full relative",
content:
"flex flex-col justify-between !overflow-visible [&_[data-slot=session-turn-message-header]]:top-[-32px]",
content: "flex flex-col justify-between !overflow-visible",
container: "px-4",
}}
/>
@@ -353,26 +352,16 @@ export default function () {
<div
classList={{
"@container relative shrink-0 pt-14 flex flex-col gap-10 min-h-0 w-full": true,
"mx-auto max-w-200": !wide(),
}}
>
<div
classList={{
"w-full flex justify-start items-start min-w-0": true,
"max-w-200 mx-auto px-6": wide(),
"pr-6 pl-18": !wide() && messages().length > 1,
"px-6": !wide() && messages().length === 1,
"w-full flex justify-start items-start min-w-0 px-6": true,
}}
>
{title()}
</div>
<div class="flex items-start justify-start h-full min-h-0">
<SessionMessageRail
messages={messages()}
current={activeMessage()}
onMessageSelect={setActiveMessage}
wide={wide()}
/>
<SessionTurn
sessionID={data().sessionID}
messageID={store.messageId ?? firstUserMessage()!.id!}
@@ -386,13 +375,7 @@ export default function () {
classes={{
root: "grow",
content: "flex flex-col justify-between",
container:
"w-full pb-20 " +
(wide()
? "max-w-200 mx-auto px-6"
: messages().length > 1
? "pr-6 pl-18"
: "px-6"),
container: "w-full pb-20 px-6",
}}
>
<div
+50
View File
@@ -0,0 +1,50 @@
const dir = process.env.OPENCODE_E2E_PROJECT_DIR ?? process.cwd()
const title = process.env.OPENCODE_E2E_SESSION_TITLE ?? "E2E Session"
const text = process.env.OPENCODE_E2E_MESSAGE ?? "Seeded for UI e2e"
const model = process.env.OPENCODE_E2E_MODEL ?? "opencode/gpt-5-nano"
const parts = model.split("/")
const providerID = parts[0] ?? "opencode"
const modelID = parts[1] ?? "gpt-5-nano"
const now = Date.now()
const seed = async () => {
const { Instance } = await import("../src/project/instance")
const { InstanceBootstrap } = await import("../src/project/bootstrap")
const { Session } = await import("../src/session")
const { Identifier } = await import("../src/id/id")
const { Project } = await import("../src/project/project")
await Instance.provide({
directory: dir,
init: InstanceBootstrap,
fn: async () => {
const session = await Session.create({ title })
const messageID = Identifier.descending("message")
const partID = Identifier.descending("part")
const message = {
id: messageID,
sessionID: session.id,
role: "user" as const,
time: { created: now },
agent: "build",
model: {
providerID,
modelID,
},
}
const part = {
id: partID,
sessionID: session.id,
messageID,
type: "text" as const,
text,
time: { start: now },
}
await Session.updateMessage(message)
await Session.updatePart(part)
await Project.update({ projectID: Instance.project.id, name: "E2E Project" })
},
})
}
await seed()
+24 -3
View File
@@ -1,10 +1,12 @@
import { Config } from "../config/config"
import z from "zod"
import { Provider } from "../provider/provider"
import { generateObject, type ModelMessage } from "ai"
import { generateObject, streamObject, type ModelMessage } from "ai"
import { SystemPrompt } from "../session/system"
import { Instance } from "../project/instance"
import { Truncate } from "../tool/truncation"
import { Auth } from "../auth"
import { ProviderTransform } from "../provider/transform"
import PROMPT_GENERATE from "./generate.txt"
import PROMPT_COMPACTION from "./prompt/compaction.txt"
@@ -276,10 +278,12 @@ export namespace Agent {
const defaultModel = input.model ?? (await Provider.defaultModel())
const model = await Provider.getModel(defaultModel.providerID, defaultModel.modelID)
const language = await Provider.getLanguage(model)
const system = SystemPrompt.header(defaultModel.providerID)
system.push(PROMPT_GENERATE)
const existing = await list()
const result = await generateObject({
const params = {
experimental_telemetry: {
isEnabled: cfg.experimental?.openTelemetry,
metadata: {
@@ -305,7 +309,24 @@ export namespace Agent {
whenToUse: z.string(),
systemPrompt: z.string(),
}),
})
} satisfies Parameters<typeof generateObject>[0]
if (defaultModel.providerID === "openai" && (await Auth.get(defaultModel.providerID))?.type === "oauth") {
const result = streamObject({
...params,
providerOptions: ProviderTransform.providerOptions(model, {
instructions: SystemPrompt.instructions(),
store: false,
}),
onError: () => {},
})
for await (const part of result.fullStream) {
if (part.type === "error") throw part.error
}
return result.object
}
const result = await generateObject(params)
return result.object
}
}
@@ -0,0 +1,94 @@
import { createMemo, For } from "solid-js"
import { useTheme } from "@tui/context/theme"
import { TIPS } from "./tips"
import { EmptyBorder } from "./border"
const tip = TIPS[Math.floor(Math.random() * TIPS.length)]
type TipPart = { text: string; highlight: boolean }
function parseTip(tip: string): TipPart[] {
const parts: TipPart[] = []
const regex = /\{highlight\}(.*?)\{\/highlight\}/g
let lastIndex = 0
let match
while ((match = regex.exec(tip)) !== null) {
if (match.index > lastIndex) {
parts.push({ text: tip.slice(lastIndex, match.index), highlight: false })
}
parts.push({ text: match[1], highlight: true })
lastIndex = regex.lastIndex
}
if (lastIndex < tip.length) {
parts.push({ text: tip.slice(lastIndex), highlight: false })
}
return parts
}
const tipParts = parseTip(tip)
const BOX_WIDTH = 42
const TITLE = " 🅘 Did you know? "
export function DidYouKnow() {
const { theme } = useTheme()
const dashes = createMemo(() => {
// ╭─ + title + ─...─ + ╮ = BOX_WIDTH
// 1 + 1 + title.length + dashes + 1 = BOX_WIDTH
return Math.max(0, BOX_WIDTH - 2 - TITLE.length - 1)
})
return (
<box position="absolute" bottom={3} right={2} width={BOX_WIDTH}>
<text>
<span style={{ fg: theme.border }}></span>
<span style={{ fg: theme.text }}>{TITLE}</span>
<span style={{ fg: theme.border }}>{"─".repeat(dashes())}</span>
</text>
<box
border={["left", "right", "bottom"]}
borderColor={theme.border}
customBorderChars={{
...EmptyBorder,
bottomLeft: "╰",
bottomRight: "╯",
horizontal: "─",
vertical: "│",
}}
>
<box paddingLeft={2} paddingRight={2} paddingTop={1} paddingBottom={1}>
<text>
<For each={tipParts}>
{(part) => <span style={{ fg: part.highlight ? theme.text : theme.textMuted }}>{part.text}</span>}
</For>
</text>
</box>
</box>
<box flexDirection="row" justifyContent="flex-end">
<text>
<span style={{ fg: theme.text }}>ctrl+h</span>
<span style={{ fg: theme.textMuted }}> hide tips</span>
</text>
</box>
</box>
)
}
export function ShowTipsHint() {
const { theme } = useTheme()
return (
<box position="absolute" bottom={3} right={2}>
<box flexDirection="row" justifyContent="flex-end">
<text>
<span style={{ fg: theme.text }}>ctrl+h</span>
<span style={{ fg: theme.textMuted }}> show tips</span>
</text>
</box>
</box>
)
}
@@ -0,0 +1,103 @@
export const TIPS = [
"Type {highlight}@{/highlight} followed by a filename to fuzzy search and attach files to your prompt.",
"Start a message with {highlight}!{/highlight} to run shell commands directly (e.g., {highlight}!ls -la{/highlight}).",
"Press {highlight}Tab{/highlight} to cycle between Build (full access) and Plan (read-only) agents.",
"Use {highlight}/undo{/highlight} to revert the last message and any file changes made by OpenCode.",
"Use {highlight}/redo{/highlight} to restore previously undone messages and file changes.",
"Run {highlight}/share{/highlight} to create a public link to your conversation at opencode.ai.",
"Drag and drop images into the terminal to add them as context for your prompts.",
"Press {highlight}Ctrl+V{/highlight} to paste images from your clipboard directly into the prompt.",
"Press {highlight}Ctrl+X E{/highlight} or {highlight}/editor{/highlight} to compose messages in your external editor.",
"Run {highlight}/init{/highlight} to auto-generate project rules based on your codebase structure.",
"Run {highlight}/models{/highlight} or {highlight}Ctrl+X M{/highlight} to see and switch between available AI models.",
"Use {highlight}/theme{/highlight} or {highlight}Ctrl+X T{/highlight} to preview and switch between 50+ built-in themes.",
"Press {highlight}Ctrl+X N{/highlight} or {highlight}/new{/highlight} to start a fresh conversation session.",
"Use {highlight}/sessions{/highlight} or {highlight}Ctrl+X L{/highlight} to list and continue previous conversations.",
"Run {highlight}/compact{/highlight} to summarize long sessions when approaching context limits.",
"Press {highlight}Ctrl+X X{/highlight} or {highlight}/export{/highlight} to save the conversation as Markdown.",
"Press {highlight}Ctrl+X Y{/highlight} to copy the assistant's last message to clipboard.",
"Press {highlight}Ctrl+P{/highlight} to see all available actions and commands.",
"Run {highlight}/connect{/highlight} to add API keys for 75+ supported LLM providers.",
"The default leader key is {highlight}Ctrl+X{/highlight}; combine with other keys for quick actions.",
"Press {highlight}F2{/highlight} to quickly switch between recently used models.",
"Press {highlight}Ctrl+X B{/highlight} to show/hide the sidebar panel.",
"Use {highlight}PageUp{/highlight}/{highlight}PageDown{/highlight} to navigate through conversation history.",
"Press {highlight}Ctrl+G{/highlight} or {highlight}Home{/highlight} to jump to the beginning of the conversation.",
"Press {highlight}Ctrl+Alt+G{/highlight} or {highlight}End{/highlight} to jump to the most recent message.",
"Press {highlight}Shift+Enter{/highlight} or {highlight}Ctrl+J{/highlight} to add newlines in your prompt.",
"Press {highlight}Ctrl+C{/highlight} when typing to clear the input field.",
"Press {highlight}Escape{/highlight} to stop the AI mid-response.",
"Switch to {highlight}Plan{/highlight} agent to get suggestions without making actual changes.",
"Use {highlight}@agent-name{/highlight} in prompts to invoke specialized subagents.",
"Press {highlight}Ctrl+X Right/Left{/highlight} to cycle through parent and child sessions.",
"Create {highlight}opencode.json{/highlight} in project root for project-specific settings.",
"Place settings in {highlight}~/.config/opencode/opencode.json{/highlight} for global config.",
"Add {highlight}$schema{/highlight} to your config for autocomplete in your editor.",
"Configure {highlight}model{/highlight} in config to set your default model.",
"Override any keybind in config via the {highlight}keybinds{/highlight} section.",
"Set any keybind to {highlight}none{/highlight} to disable it completely.",
"Configure local or remote MCP servers in the {highlight}mcp{/highlight} config section.",
"OpenCode auto-handles OAuth for remote MCP servers requiring auth.",
"Add {highlight}.md{/highlight} files to {highlight}.opencode/command/{/highlight} to define reusable custom prompts.",
"Use {highlight}$ARGUMENTS{/highlight}, {highlight}$1{/highlight}, {highlight}$2{/highlight} in custom commands for dynamic input.",
"Use backticks in commands to inject shell output (e.g., {highlight}`git status`{/highlight}).",
"Add {highlight}.md{/highlight} files to {highlight}.opencode/agent/{/highlight} for specialized AI personas.",
"Configure per-agent permissions for {highlight}edit{/highlight}, {highlight}bash{/highlight}, and {highlight}webfetch{/highlight} tools.",
'Use patterns like {highlight}"git *": "allow"{/highlight} for granular bash permissions.',
'Set {highlight}"rm -rf *": "deny"{/highlight} to block destructive commands.',
'Configure {highlight}"git push": "ask"{/highlight} to require approval before pushing.',
"OpenCode auto-formats files using prettier, gofmt, ruff, and more.",
'Set {highlight}"formatter": false{/highlight} in config to disable all auto-formatting.',
"Define custom formatter commands with file extensions in config.",
"OpenCode uses LSP servers for intelligent code analysis.",
"Create {highlight}.ts{/highlight} files in {highlight}.opencode/tool/{/highlight} to define new LLM tools.",
"Tool definitions can invoke scripts written in Python, Go, etc.",
"Add {highlight}.ts{/highlight} files to {highlight}.opencode/plugin/{/highlight} for event hooks.",
"Use plugins to send OS notifications when sessions complete.",
"Create a plugin to prevent OpenCode from reading sensitive files.",
"Use {highlight}opencode run{/highlight} for non-interactive scripting.",
"Use {highlight}opencode run --continue{/highlight} to resume the last session.",
"Use {highlight}opencode run -f file.ts{/highlight} to attach files via CLI.",
"Use {highlight}--format json{/highlight} for machine-readable output in scripts.",
"Run {highlight}opencode serve{/highlight} for headless API access to OpenCode.",
"Use {highlight}opencode run --attach{/highlight} to connect to a running server for faster runs.",
"Run {highlight}opencode upgrade{/highlight} to update to the latest version.",
"Run {highlight}opencode auth list{/highlight} to see all configured providers.",
"Run {highlight}opencode agent create{/highlight} for guided agent creation.",
"Use {highlight}/opencode{/highlight} in GitHub issues/PRs to trigger AI actions.",
"Run {highlight}opencode github install{/highlight} to set up the GitHub workflow.",
"Comment {highlight}/opencode fix this{/highlight} on issues to auto-create PRs.",
"Comment {highlight}/oc{/highlight} on PR code lines for targeted code reviews.",
'Use {highlight}"theme": "system"{/highlight} to match your terminal\'s colors.',
"Create JSON theme files in {highlight}.opencode/themes/{/highlight} directory.",
"Themes support dark/light variants for both modes.",
"Reference ANSI colors 0-255 in custom themes.",
"Use {highlight}{env:VAR_NAME}{/highlight} syntax to reference environment variables in config.",
"Use {highlight}{file:path}{/highlight} to include file contents in config values.",
"Use {highlight}instructions{/highlight} in config to load additional rules files.",
"Set agent {highlight}temperature{/highlight} from 0.0 (focused) to 1.0 (creative).",
"Configure {highlight}maxSteps{/highlight} to limit agentic iterations per request.",
'Set {highlight}"tools": {"bash": false}{/highlight} to disable specific tools.',
'Use {highlight}"mcp_*": false{/highlight} to disable all tools from an MCP server.',
"Override global tool settings per agent configuration.",
'Set {highlight}"share": "auto"{/highlight} to automatically share all sessions.',
'Set {highlight}"share": "disabled"{/highlight} to prevent any session sharing.',
"Run {highlight}/unshare{/highlight} to remove a session from public access.",
"Permission {highlight}doom_loop{/highlight} prevents infinite tool call loops.",
"Permission {highlight}external_directory{/highlight} protects files outside project.",
"Run {highlight}opencode debug config{/highlight} to troubleshoot configuration.",
"Use {highlight}--print-logs{/highlight} flag to see detailed logs in stderr.",
"Press {highlight}Ctrl+X G{/highlight} or {highlight}/timeline{/highlight} to jump to specific messages.",
"Press {highlight}Ctrl+X H{/highlight} to toggle code block visibility in messages.",
"Press {highlight}Ctrl+X S{/highlight} or {highlight}/status{/highlight} to see system status info.",
"Enable {highlight}tui.scroll_acceleration{/highlight} for smooth macOS-style scrolling.",
"Toggle username display in chat via command palette ({highlight}Ctrl+P{/highlight}).",
"Run {highlight}docker run -it --rm ghcr.io/sst/opencode{/highlight} for containerized use.",
"Use {highlight}/connect{/highlight} with OpenCode Zen for curated, tested models.",
"Commit your project's {highlight}AGENTS.md{/highlight} file to Git for team sharing.",
"Use {highlight}/review{/highlight} to review uncommitted changes, branches, or PRs.",
"Run {highlight}/help{/highlight} or {highlight}Ctrl+X H{/highlight} to show the help dialog.",
"Use {highlight}/details{/highlight} to toggle tool execution details visibility.",
"Use {highlight}/rename{/highlight} to rename the current session.",
"Press {highlight}Ctrl+Z{/highlight} to suspend the terminal and return to your shell.",
]
@@ -1,9 +1,10 @@
import { Prompt, type PromptRef } from "@tui/component/prompt"
import { createMemo, Match, onMount, Show, Switch } from "solid-js"
import { useTheme } from "@tui/context/theme"
import { useKeybind } from "@tui/context/keybind"
import { useKeyboard } from "@opentui/solid"
import { Logo } from "../component/logo"
import { Tips } from "../component/tips"
import { DidYouKnow, ShowTipsHint } from "../component/did-you-know"
import { Locale } from "@/util/locale"
import { useSync } from "../context/sync"
import { Toast } from "../ui/toast"
@@ -42,6 +43,22 @@ export function Home() {
return !tipsHidden()
})
function hideTips() {
kv.set("tips_hidden", true)
}
function enableTips() {
kv.set("tips_hidden", false)
}
function toggleTips() {
if (showTips()) {
hideTips()
return
}
enableTips()
}
command.register(() => [
{
title: tipsHidden() ? "Show tips" : "Hide tips",
@@ -49,12 +66,20 @@ export function Home() {
keybind: "tips_toggle",
category: "System",
onSelect: (dialog) => {
kv.set("tips_hidden", !tipsHidden())
toggleTips()
dialog.clear()
},
},
])
useKeyboard((evt) => {
// Don't handle tips keybind for first-time users
if (isFirstTimeUser()) return
if (evt.name !== "h" || !evt.ctrl || evt.meta || evt.shift) return
toggleTips()
evt.preventDefault()
})
const Hint = (
<Show when={connectedMcpCount() > 0}>
<box flexShrink={0} flexDirection="row" gap={1}>
@@ -89,8 +114,6 @@ export function Home() {
})
const directory = useDirectory()
const keybind = useKeybind()
return (
<>
<box flexGrow={1} justifyContent="center" alignItems="center" paddingLeft={2} paddingRight={2} gap={1}>
@@ -112,6 +135,11 @@ export function Home() {
</box>
<Toast />
</box>
<Show when={!isFirstTimeUser()}>
<Show when={showTips()} fallback={<ShowTipsHint />}>
<DidYouKnow />
</Show>
</Show>
<box paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2} flexDirection="row" flexShrink={0} gap={2}>
<text fg={theme.textMuted}>{directory()}</text>
<box gap={1} flexDirection="row" flexShrink={0}>
@@ -280,6 +280,7 @@ export function PermissionPrompt(props: { request: PermissionRequest }) {
reply: "reject",
requestID: props.request.id,
})
return
}
sdk.client.permission.reply({
reply: "once",
@@ -456,6 +457,11 @@ function Prompt<const T extends Record<string, string>>(props: {
paddingLeft={1}
paddingRight={1}
backgroundColor={option === store.selected ? theme.warning : theme.backgroundMenu}
onMouseOver={() => setStore("selected", option)}
onMouseUp={() => {
setStore("selected", option)
props.onSelect(option)
}}
>
<text fg={option === store.selected ? selectedForeground(theme, theme.warning) : theme.textMuted}>
{props.options[option]}
@@ -125,9 +125,25 @@ export namespace Clipboard {
if (os === "win32") {
console.log("clipboard: using powershell")
return async (text: string) => {
// need to escape backticks because powershell uses them as escape code
const escaped = text.replace(/"/g, '""').replace(/`/g, "``")
await $`powershell -NonInteractive -NoProfile -Command "Set-Clipboard -Value \"${escaped}\""`.nothrow().quiet()
// Pipe via stdin to avoid PowerShell string interpolation ($env:FOO, $(), etc.)
const proc = Bun.spawn(
[
"powershell.exe",
"-NonInteractive",
"-NoProfile",
"-Command",
"[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())",
],
{
stdin: "pipe",
stdout: "ignore",
stderr: "ignore",
},
)
proc.stdin.write(text)
proc.stdin.end()
await proc.exited.catch(() => {})
}
}
+2 -19
View File
@@ -226,7 +226,7 @@ export const rlang: Info = {
}
export const uvformat: Info = {
name: "uv format",
name: "uv",
command: ["uv", "format", "--", "$FILE"],
extensions: [".py", ".pyi"],
async enabled() {
@@ -337,23 +337,6 @@ export const rustfmt: Info = {
command: ["rustfmt", "$FILE"],
extensions: [".rs"],
async enabled() {
if (!Bun.which("rustfmt")) return false
const configs = ["rustfmt.toml", ".rustfmt.toml"]
for (const config of configs) {
const found = await Filesystem.findUp(config, Instance.directory, Instance.worktree)
if (found.length > 0) return true
}
return false
},
}
export const cargofmt: Info = {
name: "cargofmt",
command: ["cargo", "fmt", "--", "$FILE"],
extensions: [".rs"],
async enabled() {
if (!Bun.which("cargo")) return false
const found = await Filesystem.findUp("Cargo.toml", Instance.directory, Instance.worktree)
return found.length > 0
return Bun.which("rustfmt") !== null
},
}
@@ -11,6 +11,8 @@ import { Instance } from "./instance"
import { Vcs } from "./vcs"
import { Log } from "@/util/log"
import { ShareNext } from "@/share/share-next"
import { Snapshot } from "../snapshot"
import { Truncate } from "../tool/truncation"
export async function InstanceBootstrap() {
Log.Default.info("bootstrapping", { directory: Instance.directory })
@@ -22,6 +24,8 @@ export async function InstanceBootstrap() {
FileWatcher.init()
File.init()
Vcs.init()
Snapshot.init()
Truncate.init()
Bus.subscribe(Command.Event.Executed, async (payload) => {
if (payload.properties.name === Command.Default.INIT) {
+15
View File
@@ -317,4 +317,19 @@ export namespace Project {
}
return valid
}
export async function removeSandbox(projectID: string, directory: string) {
const result = await Storage.update<Info>(["project", projectID], (draft) => {
const sandboxes = draft.sandboxes ?? []
draft.sandboxes = sandboxes.filter((sandbox) => sandbox !== directory)
draft.time.updated = Date.now()
})
GlobalBus.emit("event", {
payload: {
type: Event.Updated.type,
properties: result,
},
})
return result
}
}
+1 -6
View File
@@ -60,12 +60,7 @@ export namespace ModelsDev {
status: z.enum(["alpha", "beta", "deprecated"]).optional(),
options: z.record(z.string(), z.any()),
headers: z.record(z.string(), z.string()).optional(),
provider: z
.object({
npm: z.string().optional(),
api: z.string().optional(),
})
.optional(),
provider: z.object({ npm: z.string() }).optional(),
variants: z.record(z.string(), z.record(z.string(), z.any())).optional(),
})
export type Model = z.infer<typeof Model>
+51 -70
View File
@@ -41,6 +41,18 @@ import { ProviderTransform } from "./transform"
export namespace Provider {
const log = Log.create({ service: "provider" })
function isGpt5OrLater(modelID: string): boolean {
const match = /^gpt-(\d+)/.exec(modelID)
if (!match) {
return false
}
return Number(match[1]) >= 5
}
function shouldUseCopilotResponsesApi(modelID: string): boolean {
return isGpt5OrLater(modelID) && !modelID.startsWith("gpt-5-mini")
}
const BUNDLED_PROVIDERS: Record<string, (options: any) => SDK> = {
"@ai-sdk/amazon-bedrock": createAmazonBedrock,
"@ai-sdk/anthropic": createAnthropic,
@@ -66,7 +78,7 @@ export namespace Provider {
"@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
}
type CustomModelLoader = (sdk: any, model: Model, options?: Record<string, any>) => Promise<any>
type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
type CustomLoader = (provider: Info) => Promise<{
autoload: boolean
getModel?: CustomModelLoader
@@ -110,8 +122,8 @@ export namespace Provider {
openai: async () => {
return {
autoload: false,
async getModel(sdk: any, model: Model, _options?: Record<string, any>) {
return sdk.responses(model.api.id)
async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
return sdk.responses(modelID)
},
options: {},
}
@@ -119,11 +131,8 @@ export namespace Provider {
"github-copilot": async () => {
return {
autoload: false,
async getModel(sdk: any, model: Model, _options?: Record<string, any>) {
if (model.api.id.includes("codex")) {
return sdk.responses(model.api.id)
}
return sdk.chat(model.api.id)
async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
return shouldUseCopilotResponsesApi(modelID) ? sdk.responses(modelID) : sdk.chat(modelID)
},
options: {},
}
@@ -131,44 +140,39 @@ export namespace Provider {
"github-copilot-enterprise": async () => {
return {
autoload: false,
async getModel(sdk: any, model: Model, _options?: Record<string, any>) {
if (model.api.id.includes("codex")) {
return sdk.responses(model.api.id)
}
return sdk.chat(model.api.id)
async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
return shouldUseCopilotResponsesApi(modelID) ? sdk.responses(modelID) : sdk.chat(modelID)
},
options: {},
}
},
// TODO: handle the openai and anthropic deployments
azure: async () => {
return {
autoload: false,
async getModel(sdk: any, model: Model, options?: Record<string, any>) {
if (model && model.api.npm !== "@ai-sdk/azure") {
return sdk.languageModel(model.api.id)
}
async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
if (options?.["useCompletionUrls"]) {
return sdk.chat(model.api.id)
return sdk.chat(modelID)
} else {
return sdk.responses(modelID)
}
return sdk.responses(model.api.id)
},
options: {},
}
},
"azure-cognitive-services": async () => {
const resourceName = Env.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
return {
autoload: false,
async getModel(sdk: any, model: Model, options?: Record<string, any>) {
if (model && model.api.npm !== "@ai-sdk/azure") {
return sdk.languageModel(model.api.id)
}
async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
if (options?.["useCompletionUrls"]) {
return sdk.chat(model.api.id)
return sdk.chat(modelID)
} else {
return sdk.responses(modelID)
}
return sdk.responses(model.api.id)
},
options: {},
options: {
baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
},
}
},
"amazon-bedrock": async () => {
@@ -227,8 +231,7 @@ export namespace Provider {
return {
autoload: true,
options: providerOptions,
async getModel(sdk: any, model: Model, options?: Record<string, any>) {
let modelID = model.api.id
async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
// Skip region prefixing if model already has a cross-region inference profile prefix
if (modelID.startsWith("global.") || modelID.startsWith("jp.")) {
return sdk.languageModel(modelID)
@@ -346,8 +349,8 @@ export namespace Provider {
project,
location,
},
async getModel(sdk: any, model: Model) {
const id = String(model.api.id).trim()
async getModel(sdk: any, modelID: string) {
const id = String(modelID).trim()
return sdk.languageModel(id)
},
}
@@ -363,8 +366,8 @@ export namespace Provider {
project,
location,
},
async getModel(sdk: any, model: Model) {
const id = String(model.api.id).trim()
async getModel(sdk: any, modelID) {
const id = String(modelID).trim()
return sdk.languageModel(id)
},
}
@@ -386,8 +389,8 @@ export namespace Provider {
return {
autoload: !!envServiceKey,
options: envServiceKey ? { deploymentId, resourceGroup } : {},
async getModel(sdk: any, model: Model) {
return sdk(model.api.id)
async getModel(sdk: any, modelID: string) {
return sdk(modelID)
},
}
},
@@ -426,8 +429,8 @@ export namespace Provider {
...(providerConfig?.options?.featureFlags || {}),
},
},
async getModel(sdk: ReturnType<typeof createGitLab>, model: Model) {
return sdk.agenticChat(model.api.id, {
async getModel(sdk: ReturnType<typeof createGitLab>, modelID: string) {
return sdk.agenticChat(modelID, {
featureFlags: {
duo_agent_platform_agentic_chat: true,
duo_agent_platform: true,
@@ -454,8 +457,8 @@ export namespace Provider {
return {
autoload: true,
async getModel(sdk: any, model: Model, _options?: Record<string, any>) {
return sdk.languageModel(model.api.id)
async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
return sdk.languageModel(modelID)
},
options: {
baseURL: `https://gateway.ai.cloudflare.com/v1/${accountId}/${gateway}/compat`,
@@ -597,8 +600,11 @@ export namespace Provider {
family: model.family,
api: {
id: model.id,
url: model.provider?.api ?? provider.api!,
npm: model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible",
url: provider.api!,
npm: iife(() => {
if (provider.id.startsWith("github-copilot")) return "@ai-sdk/github-copilot"
return model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible"
}),
},
status: model.status ?? "active",
headers: model.headers ?? {},
@@ -905,16 +911,6 @@ export namespace Provider {
continue
}
if (providerID === "github-copilot" || providerID === "github-copilot-enterprise") {
provider.models = mapValues(provider.models, (model) => ({
...model,
api: {
...model.api,
npm: "@ai-sdk/github-copilot",
},
}))
}
const configProvider = config.provider?.[providerID]
for (const [modelID, model] of Object.entries(provider.models)) {
@@ -960,21 +956,6 @@ export namespace Provider {
return state().then((state) => state.providers)
}
export function resolveModelBaseURL(model: Model, options: Record<string, any>): string {
const template = model.api?.url ?? ""
if (!template) return ""
const matches = [...template.matchAll(/{{([^}]+)}}/g)]
if (matches.length === 0) return template
return matches.reduce((url, match) => {
const keys = match[1].split("|").map((item) => item.trim())
const resolved = keys
.map((key) => Env.get(key) ?? options[key])
.find((value) => value !== undefined && value !== null && value !== "")
if (resolved === undefined || resolved === null || resolved === "") return url
return url.replaceAll(match[0], String(resolved))
}, template)
}
async function getSDK(model: Model) {
try {
using _ = log.time("getSDK", {
@@ -988,8 +969,7 @@ export namespace Provider {
options["includeUsage"] = true
}
const resolvedBaseURL = resolveModelBaseURL(model, options)
if (!options["baseURL"] && resolvedBaseURL) options["baseURL"] = resolvedBaseURL
if (!options["baseURL"]) options["baseURL"] = model.api.url
if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
if (model.headers)
options["headers"] = {
@@ -1112,8 +1092,9 @@ export namespace Provider {
const sdk = await getSDK(model)
try {
const loader = s.modelLoaders[model.providerID]
const language = loader ? await loader(sdk, model, provider.options) : sdk.languageModel(model.api.id)
const language = s.modelLoaders[model.providerID]
? await s.modelLoaders[model.providerID](sdk, model.api.id, provider.options)
: sdk.languageModel(model.api.id)
s.models.set(key, language)
return language
} catch (e) {
@@ -815,14 +815,20 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV2 {
// flag that checks if there have been client-side tool calls (not executed by openai)
let hasFunctionCall = false
// Track reasoning by output_index instead of item_id
// GitHub Copilot rotates encrypted item IDs on every event
const activeReasoning: Record<
string,
number,
{
canonicalId: string // the item.id from output_item.added
encryptedContent?: string | null
summaryParts: number[]
}
> = {}
// Track current active reasoning output_index for correlating summary events
let currentReasoningOutputIndex: number | null = null
// Track a stable text part id for the current assistant message.
// Copilot may change item_id across text deltas; normalize to one id.
let currentTextId: string | null = null
@@ -933,10 +939,12 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV2 {
},
})
} else if (isResponseOutputItemAddedReasoningChunk(value)) {
activeReasoning[value.item.id] = {
activeReasoning[value.output_index] = {
canonicalId: value.item.id,
encryptedContent: value.item.encrypted_content,
summaryParts: [0],
}
currentReasoningOutputIndex = value.output_index
controller.enqueue({
type: "reasoning-start",
@@ -1091,22 +1099,25 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV2 {
currentTextId = null
}
} else if (isResponseOutputItemDoneReasoningChunk(value)) {
const activeReasoningPart = activeReasoning[value.item.id]
const activeReasoningPart = activeReasoning[value.output_index]
if (activeReasoningPart) {
for (const summaryIndex of activeReasoningPart.summaryParts) {
controller.enqueue({
type: "reasoning-end",
id: `${value.item.id}:${summaryIndex}`,
id: `${activeReasoningPart.canonicalId}:${summaryIndex}`,
providerMetadata: {
openai: {
itemId: value.item.id,
itemId: activeReasoningPart.canonicalId,
reasoningEncryptedContent: value.item.encrypted_content ?? null,
},
},
})
}
delete activeReasoning[value.output_index]
if (currentReasoningOutputIndex === value.output_index) {
currentReasoningOutputIndex = null
}
}
delete activeReasoning[value.item.id]
}
} else if (isResponseFunctionCallArgumentsDeltaChunk(value)) {
const toolCall = ongoingToolCalls[value.output_index]
@@ -1198,32 +1209,40 @@ export class OpenAIResponsesLanguageModel implements LanguageModelV2 {
logprobs.push(value.logprobs)
}
} else if (isResponseReasoningSummaryPartAddedChunk(value)) {
const activeItem =
currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
// the first reasoning start is pushed in isResponseOutputItemAddedReasoningChunk.
if (value.summary_index > 0) {
activeReasoning[value.item_id]?.summaryParts.push(value.summary_index)
if (activeItem && value.summary_index > 0) {
activeItem.summaryParts.push(value.summary_index)
controller.enqueue({
type: "reasoning-start",
id: `${value.item_id}:${value.summary_index}`,
id: `${activeItem.canonicalId}:${value.summary_index}`,
providerMetadata: {
openai: {
itemId: value.item_id,
reasoningEncryptedContent: activeReasoning[value.item_id]?.encryptedContent ?? null,
itemId: activeItem.canonicalId,
reasoningEncryptedContent: activeItem.encryptedContent ?? null,
},
},
})
}
} else if (isResponseReasoningSummaryTextDeltaChunk(value)) {
controller.enqueue({
type: "reasoning-delta",
id: `${value.item_id}:${value.summary_index}`,
delta: value.delta,
providerMetadata: {
openai: {
itemId: value.item_id,
const activeItem =
currentReasoningOutputIndex !== null ? activeReasoning[currentReasoningOutputIndex] : null
if (activeItem) {
controller.enqueue({
type: "reasoning-delta",
id: `${activeItem.canonicalId}:${value.summary_index}`,
delta: value.delta,
providerMetadata: {
openai: {
itemId: activeItem.canonicalId,
},
},
},
})
})
}
} else if (isResponseFinishedChunk(value)) {
finishReason = mapOpenAIResponseFinishReason({
finishReason: value.response.incomplete_details?.reason,
+21 -8
View File
@@ -123,11 +123,8 @@ export namespace ProviderTransform {
return result
}
if (
model.capabilities.interleaved &&
typeof model.capabilities.interleaved === "object" &&
model.capabilities.interleaved.field === "reasoning_content"
) {
if (typeof model.capabilities.interleaved === "object" && model.capabilities.interleaved.field) {
const field = model.capabilities.interleaved.field
return msgs.map((msg) => {
if (msg.role === "assistant" && Array.isArray(msg.content)) {
const reasoningParts = msg.content.filter((part: any) => part.type === "reasoning")
@@ -136,7 +133,7 @@ export namespace ProviderTransform {
// Filter out reasoning parts from content
const filteredContent = msg.content.filter((part: any) => part.type !== "reasoning")
// Include reasoning_content directly on the message for all assistant messages
// Include reasoning_content | reasoning_details directly on the message for all assistant messages
if (reasoningText) {
return {
...msg,
@@ -145,7 +142,7 @@ export namespace ProviderTransform {
...msg.providerOptions,
openaiCompatible: {
...(msg.providerOptions as any)?.openaiCompatible,
reasoning_content: reasoningText,
[field]: reasoningText,
},
},
}
@@ -349,6 +346,18 @@ export namespace ProviderTransform {
case "@ai-sdk/gateway":
return Object.fromEntries(OPENAI_EFFORTS.map((effort) => [effort, { reasoningEffort: effort }]))
case "@ai-sdk/github-copilot":
return Object.fromEntries(
WIDELY_SUPPORTED_EFFORTS.map((effort) => [
effort,
{
reasoningEffort: effort,
reasoningSummary: "auto",
include: ["reasoning.encrypted_content"],
},
]),
)
case "@ai-sdk/cerebras":
// https://v5.ai-sdk.dev/providers/ai-sdk-providers/cerebras
case "@ai-sdk/togetherai":
@@ -524,7 +533,11 @@ export namespace ProviderTransform {
const result: Record<string, any> = {}
// openai and providers using openai package should set store to false by default.
if (input.model.providerID === "openai" || input.model.api.npm === "@ai-sdk/openai") {
if (
input.model.providerID === "openai" ||
input.model.api.npm === "@ai-sdk/openai" ||
input.model.api.npm === "@ai-sdk/github-copilot"
) {
result["store"] = false
}
+61
View File
@@ -0,0 +1,61 @@
import { Instance } from "../project/instance"
import { Log } from "../util/log"
export namespace Scheduler {
const log = Log.create({ service: "scheduler" })
export type Task = {
id: string
interval: number
run: () => Promise<void>
scope?: "instance" | "global"
}
type Timer = ReturnType<typeof setInterval>
type Entry = {
tasks: Map<string, Task>
timers: Map<string, Timer>
}
const create = (): Entry => {
const tasks = new Map<string, Task>()
const timers = new Map<string, Timer>()
return { tasks, timers }
}
const shared = create()
const state = Instance.state(
() => create(),
async (entry) => {
for (const timer of entry.timers.values()) {
clearInterval(timer)
}
entry.tasks.clear()
entry.timers.clear()
},
)
export function register(task: Task) {
const scope = task.scope ?? "instance"
const entry = scope === "global" ? shared : state()
const current = entry.timers.get(task.id)
if (current && scope === "global") return
if (current) clearInterval(current)
entry.tasks.set(task.id, task)
void run(task)
const timer = setInterval(() => {
void run(task)
}, task.interval)
timer.unref()
entry.timers.set(task.id, timer)
}
async function run(task: Task) {
log.info("run", { id: task.id })
await task.run().catch((error) => {
log.error("run failed", { id: task.id, error })
})
}
}
@@ -133,6 +133,57 @@ export const ExperimentalRoutes = lazy(() =>
return c.json(sandboxes)
},
)
.delete(
"/worktree",
describeRoute({
summary: "Remove worktree",
description: "Remove a git worktree and delete its branch.",
operationId: "worktree.remove",
responses: {
200: {
description: "Worktree removed",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
...errors(400),
},
}),
validator("json", Worktree.remove.schema),
async (c) => {
const body = c.req.valid("json")
await Worktree.remove(body)
await Project.removeSandbox(Instance.project.id, body.directory)
return c.json(true)
},
)
.post(
"/worktree/reset",
describeRoute({
summary: "Reset worktree",
description: "Reset a worktree branch to the primary default branch.",
operationId: "worktree.reset",
responses: {
200: {
description: "Worktree reset",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
...errors(400),
},
}),
validator("json", Worktree.reset.schema),
async (c) => {
const body = c.req.valid("json")
await Worktree.reset(body)
return c.json(true)
},
)
.get(
"/resource",
describeRoute({
@@ -15,7 +15,10 @@ export namespace ShareNext {
return Config.get().then((x) => x.enterprise?.url ?? "https://opncd.ai")
}
const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1"
export async function init() {
if (disabled) return
Bus.subscribe(Session.Event.Updated, async (evt) => {
await sync(evt.properties.info.id, [
{
@@ -63,6 +66,7 @@ export namespace ShareNext {
}
export async function create(sessionID: string) {
if (disabled) return { id: "", url: "", secret: "" }
log.info("creating share", { sessionID })
const result = await fetch(`${await url()}/api/share`, {
method: "POST",
@@ -110,6 +114,7 @@ export namespace ShareNext {
const queue = new Map<string, { timeout: NodeJS.Timeout; data: Map<string, Data> }>()
async function sync(sessionID: string, data: Data[]) {
if (disabled) return
const existing = queue.get(sessionID)
if (existing) {
for (const item of data) {
@@ -145,6 +150,7 @@ export namespace ShareNext {
}
export async function remove(sessionID: string) {
if (disabled) return
log.info("removing share", { sessionID })
const share = await get(sessionID)
if (!share) return
+5
View File
@@ -11,6 +11,7 @@ export namespace Share {
const pending = new Map<string, any>()
export async function sync(key: string, content: any) {
if (disabled) return
const [root, ...splits] = key.split("/")
if (root !== "session") return
const [sub, sessionID] = splits
@@ -69,7 +70,10 @@ export namespace Share {
process.env["OPENCODE_API"] ??
(Installation.isPreview() || Installation.isLocal() ? "https://api.dev.opencode.ai" : "https://api.opencode.ai")
const disabled = process.env["OPENCODE_DISABLE_SHARE"] === "true" || process.env["OPENCODE_DISABLE_SHARE"] === "1"
export async function create(sessionID: string) {
if (disabled) return { url: "", secret: "" }
return fetch(`${URL}/share_create`, {
method: "POST",
body: JSON.stringify({ sessionID: sessionID }),
@@ -79,6 +83,7 @@ export namespace Share {
}
export async function remove(sessionID: string, secret: string) {
if (disabled) return {}
return fetch(`${URL}/share_delete`, {
method: "POST",
body: JSON.stringify({ sessionID, secret }),
+37
View File
@@ -6,9 +6,46 @@ import { Global } from "../global"
import z from "zod"
import { Config } from "../config/config"
import { Instance } from "../project/instance"
import { Scheduler } from "../scheduler"
export namespace Snapshot {
const log = Log.create({ service: "snapshot" })
const hour = 60 * 60 * 1000
const prune = "7.days"
export function init() {
Scheduler.register({
id: "snapshot.cleanup",
interval: hour,
run: cleanup,
scope: "instance",
})
}
export async function cleanup() {
if (Instance.project.vcs !== "git") return
const cfg = await Config.get()
if (cfg.snapshot === false) return
const git = gitdir()
const exists = await fs
.stat(git)
.then(() => true)
.catch(() => false)
if (!exists) return
const result = await $`git --git-dir ${git} --work-tree ${Instance.worktree} gc --prune=${prune}`
.quiet()
.cwd(Instance.directory)
.nothrow()
if (result.exitCode !== 0) {
log.warn("cleanup failed", {
exitCode: result.exitCode,
stderr: result.stderr.toString(),
stdout: result.stdout.toString(),
})
return
}
log.info("cleanup", { prune })
}
export async function track() {
if (Instance.project.vcs !== "git") return
+2 -1
View File
@@ -12,13 +12,14 @@ import { assertExternalDirectory } from "./external-directory"
import { trimDiff } from "./edit"
import { LSP } from "../lsp"
import { Filesystem } from "../util/filesystem"
import DESCRIPTION from "./apply_patch.txt"
const PatchParams = z.object({
patchText: z.string().describe("The full patch text that describes all changes to be made"),
})
export const ApplyPatchTool = Tool.define("apply_patch", {
description: "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.",
description: DESCRIPTION,
parameters: PatchParams,
async execute(params, ctx) {
if (!params.patchText) {
+33 -1
View File
@@ -1 +1,33 @@
Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.
Use the `apply_patch` tool to edit files. Your patch language is a strippeddown, fileoriented diff format designed to be easy to parse and safe to apply. You can think of it as a highlevel envelope:
*** Begin Patch
[ one or more file sections ]
*** End Patch
Within that envelope, you get a sequence of file operations.
You MUST include a header to specify the action you are taking.
Each operation starts with one of three headers:
*** Add File: <path> - create a new file. Every following line is a + line (the initial contents).
*** Delete File: <path> - remove an existing file. Nothing follows.
*** Update File: <path> - patch an existing file in place (optionally with a rename).
Example patch:
```
*** Begin Patch
*** Add File: hello.txt
+Hello world
*** Update File: src/app.py
*** Move to: src/main.py
@@ def greet():
-print("Hi")
+print("Hello, world!")
*** Delete File: obsolete.txt
*** End Patch
```
It is important to remember:
- You must include a header with your intended action (Add/Delete/Update)
- You must prefix new lines with `+` even when creating a new file
+5
View File
@@ -143,6 +143,11 @@ export namespace ToolRegistry {
if (t.id === "apply_patch") return usePatch
if (t.id === "edit" || t.id === "write") return !usePatch
// omit todo tools for openai models
if (t.id === "todoread" || t.id === "todowrite") {
if (model.modelID.includes("gpt-")) return false
}
return true
})
.map(async (t) => {
+11 -4
View File
@@ -2,9 +2,9 @@ import fs from "fs/promises"
import path from "path"
import { Global } from "../global"
import { Identifier } from "../id/id"
import { lazy } from "../util/lazy"
import { PermissionNext } from "../permission/next"
import type { Agent } from "../agent/agent"
import { Scheduler } from "../scheduler"
export namespace Truncate {
export const MAX_LINES = 2000
@@ -12,6 +12,7 @@ export namespace Truncate {
export const DIR = path.join(Global.Path.data, "tool-output")
export const GLOB = path.join(DIR, "*")
const RETENTION_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
const HOUR_MS = 60 * 60 * 1000
export type Result = { content: string; truncated: false } | { content: string; truncated: true; outputPath: string }
@@ -21,6 +22,15 @@ export namespace Truncate {
direction?: "head" | "tail"
}
export function init() {
Scheduler.register({
id: "tool.truncation.cleanup",
interval: HOUR_MS,
run: cleanup,
scope: "global",
})
}
export async function cleanup() {
const cutoff = Identifier.timestamp(Identifier.create("tool", false, Date.now() - RETENTION_MS))
const glob = new Bun.Glob("tool_*")
@@ -31,8 +41,6 @@ export namespace Truncate {
}
}
const init = lazy(cleanup)
function hasTaskTool(agent?: Agent.Info): boolean {
if (!agent?.permission) return false
const rule = PermissionNext.evaluate("task", "*", agent.permission)
@@ -81,7 +89,6 @@ export namespace Truncate {
const unit = hitBytes ? "bytes" : "lines"
const preview = out.join("\n")
await init()
const id = Identifier.ascending("tool")
const filepath = path.join(DIR, id)
await Bun.write(Bun.file(filepath), text)
+207
View File
@@ -33,6 +33,26 @@ export namespace Worktree {
export type CreateInput = z.infer<typeof CreateInput>
export const RemoveInput = z
.object({
directory: z.string(),
})
.meta({
ref: "WorktreeRemoveInput",
})
export type RemoveInput = z.infer<typeof RemoveInput>
export const ResetInput = z
.object({
directory: z.string(),
})
.meta({
ref: "WorktreeResetInput",
})
export type ResetInput = z.infer<typeof ResetInput>
export const NotGitError = NamedError.create(
"WorktreeNotGitError",
z.object({
@@ -61,6 +81,20 @@ export namespace Worktree {
}),
)
export const RemoveFailedError = NamedError.create(
"WorktreeRemoveFailedError",
z.object({
message: z.string(),
}),
)
export const ResetFailedError = NamedError.create(
"WorktreeResetFailedError",
z.object({
message: z.string(),
}),
)
const ADJECTIVES = [
"brave",
"calm",
@@ -214,4 +248,177 @@ export namespace Worktree {
return info
})
export const remove = fn(RemoveInput, async (input) => {
if (Instance.project.vcs !== "git") {
throw new NotGitError({ message: "Worktrees are only supported for git projects" })
}
const directory = path.resolve(input.directory)
const list = await $`git worktree list --porcelain`.quiet().nothrow().cwd(Instance.worktree)
if (list.exitCode !== 0) {
throw new RemoveFailedError({ message: errorText(list) || "Failed to read git worktrees" })
}
const lines = outputText(list.stdout)
.split("\n")
.map((line) => line.trim())
const entries = lines.reduce<{ path?: string; branch?: string }[]>((acc, line) => {
if (!line) return acc
if (line.startsWith("worktree ")) {
acc.push({ path: line.slice("worktree ".length).trim() })
return acc
}
const current = acc[acc.length - 1]
if (!current) return acc
if (line.startsWith("branch ")) {
current.branch = line.slice("branch ".length).trim()
}
return acc
}, [])
const entry = entries.find((item) => item.path && path.resolve(item.path) === directory)
if (!entry?.path) {
throw new RemoveFailedError({ message: "Worktree not found" })
}
const removed = await $`git worktree remove --force ${entry.path}`.quiet().nothrow().cwd(Instance.worktree)
if (removed.exitCode !== 0) {
throw new RemoveFailedError({ message: errorText(removed) || "Failed to remove git worktree" })
}
const branch = entry.branch?.replace(/^refs\/heads\//, "")
if (branch) {
const deleted = await $`git branch -D ${branch}`.quiet().nothrow().cwd(Instance.worktree)
if (deleted.exitCode !== 0) {
throw new RemoveFailedError({ message: errorText(deleted) || "Failed to delete worktree branch" })
}
}
return true
})
export const reset = fn(ResetInput, async (input) => {
if (Instance.project.vcs !== "git") {
throw new NotGitError({ message: "Worktrees are only supported for git projects" })
}
const directory = path.resolve(input.directory)
if (directory === path.resolve(Instance.worktree)) {
throw new ResetFailedError({ message: "Cannot reset the primary workspace" })
}
const list = await $`git worktree list --porcelain`.quiet().nothrow().cwd(Instance.worktree)
if (list.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(list) || "Failed to read git worktrees" })
}
const lines = outputText(list.stdout)
.split("\n")
.map((line) => line.trim())
const entries = lines.reduce<{ path?: string; branch?: string }[]>((acc, line) => {
if (!line) return acc
if (line.startsWith("worktree ")) {
acc.push({ path: line.slice("worktree ".length).trim() })
return acc
}
const current = acc[acc.length - 1]
if (!current) return acc
if (line.startsWith("branch ")) {
current.branch = line.slice("branch ".length).trim()
}
return acc
}, [])
const entry = entries.find((item) => item.path && path.resolve(item.path) === directory)
if (!entry?.path) {
throw new ResetFailedError({ message: "Worktree not found" })
}
const remoteList = await $`git remote`.quiet().nothrow().cwd(Instance.worktree)
if (remoteList.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(remoteList) || "Failed to list git remotes" })
}
const remotes = outputText(remoteList.stdout)
.split("\n")
.map((line) => line.trim())
.filter(Boolean)
const remote = remotes.includes("origin")
? "origin"
: remotes.length === 1
? remotes[0]
: remotes.includes("upstream")
? "upstream"
: ""
const remoteHead = remote
? await $`git symbolic-ref refs/remotes/${remote}/HEAD`.quiet().nothrow().cwd(Instance.worktree)
: { exitCode: 1, stdout: undefined, stderr: undefined }
const remoteRef = remoteHead.exitCode === 0 ? outputText(remoteHead.stdout) : ""
const remoteTarget = remoteRef ? remoteRef.replace(/^refs\/remotes\//, "") : ""
const remoteBranch = remote && remoteTarget.startsWith(`${remote}/`) ? remoteTarget.slice(`${remote}/`.length) : ""
const mainCheck = await $`git show-ref --verify --quiet refs/heads/main`.quiet().nothrow().cwd(Instance.worktree)
const masterCheck = await $`git show-ref --verify --quiet refs/heads/master`
.quiet()
.nothrow()
.cwd(Instance.worktree)
const localBranch = mainCheck.exitCode === 0 ? "main" : masterCheck.exitCode === 0 ? "master" : ""
const target = remoteBranch ? `${remote}/${remoteBranch}` : localBranch
if (!target) {
throw new ResetFailedError({ message: "Default branch not found" })
}
if (remoteBranch) {
const fetch = await $`git fetch ${remote} ${remoteBranch}`.quiet().nothrow().cwd(Instance.worktree)
if (fetch.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(fetch) || `Failed to fetch ${target}` })
}
}
if (!entry.path) {
throw new ResetFailedError({ message: "Worktree path not found" })
}
const worktreePath = entry.path
const resetToTarget = await $`git reset --hard ${target}`.quiet().nothrow().cwd(worktreePath)
if (resetToTarget.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(resetToTarget) || "Failed to reset worktree to target" })
}
const clean = await $`git clean -fdx`.quiet().nothrow().cwd(worktreePath)
if (clean.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(clean) || "Failed to clean worktree" })
}
const update = await $`git submodule update --init --recursive --force`.quiet().nothrow().cwd(worktreePath)
if (update.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(update) || "Failed to update submodules" })
}
const subReset = await $`git submodule foreach --recursive git reset --hard`.quiet().nothrow().cwd(worktreePath)
if (subReset.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(subReset) || "Failed to reset submodules" })
}
const subClean = await $`git submodule foreach --recursive git clean -fdx`.quiet().nothrow().cwd(worktreePath)
if (subClean.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(subClean) || "Failed to clean submodules" })
}
const status = await $`git status --porcelain=v1`.quiet().nothrow().cwd(worktreePath)
if (status.exitCode !== 0) {
throw new ResetFailedError({ message: errorText(status) || "Failed to read git status" })
}
const dirty = outputText(status.stdout)
if (!dirty) return true
throw new ResetFailedError({ message: `Worktree reset left local changes:\n${dirty}` })
})
}
@@ -381,160 +381,6 @@ test("parseModel handles model IDs with slashes", () => {
expect(result.modelID).toBe("anthropic/claude-3-opus")
})
test("resolveModelBaseURL returns empty when url missing", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const model = { api: { url: "" } } as Provider.Model
expect(Provider.resolveModelBaseURL(model, {})).toBe("")
},
})
})
test("resolveModelBaseURL returns template when no placeholders", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const model = { api: { url: "https://api.example.com/v1" } } as Provider.Model
expect(Provider.resolveModelBaseURL(model, {})).toBe("https://api.example.com/v1")
},
})
})
test("resolveModelBaseURL replaces placeholders from env", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
init: async () => {
Env.set("CUSTOM_HOST", "env.example.com")
},
fn: async () => {
const model = { api: { url: "https://{{CUSTOM_HOST}}/v1" } } as Provider.Model
expect(Provider.resolveModelBaseURL(model, {})).toBe("https://env.example.com/v1")
Env.remove("CUSTOM_HOST")
},
})
})
test("resolveModelBaseURL falls back to options when env missing", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const model = { api: { url: "https://{{HOST}}/v1" } } as Provider.Model
expect(Provider.resolveModelBaseURL(model, { HOST: "options.example.com" })).toBe(
"https://options.example.com/v1",
)
},
})
})
test("resolveModelBaseURL chooses first non-empty key", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const model = { api: { url: "https://{{PRIMARY|SECONDARY}}/v1" } } as Provider.Model
const options = {
PRIMARY: "",
SECONDARY: "fallback.example.com",
}
expect(Provider.resolveModelBaseURL(model, options)).toBe("https://fallback.example.com/v1")
},
})
})
test("resolveModelBaseURL keeps unresolved placeholders", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const model = { api: { url: "https://{{MISSING}}/v1" } } as Provider.Model
expect(Provider.resolveModelBaseURL(model, {})).toBe("https://{{MISSING}}/v1")
},
})
})
test("resolveModelBaseURL replaces multiple placeholders", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
const model = { api: { url: "https://{{HOST}}/{{VERSION}}" } } as Provider.Model
const options = {
HOST: "multi.example.com",
VERSION: "v1",
}
expect(Provider.resolveModelBaseURL(model, options)).toBe("https://multi.example.com/v1")
},
})
})
test("defaultModel returns first available model when no config set", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, test } from "bun:test"
import { Scheduler } from "../src/scheduler"
import { Instance } from "../src/project/instance"
import { tmpdir } from "./fixture/fixture"
describe("Scheduler.register", () => {
const hour = 60 * 60 * 1000
test("defaults to instance scope per directory", async () => {
await using one = await tmpdir({ git: true })
await using two = await tmpdir({ git: true })
const runs = { count: 0 }
const id = "scheduler.instance." + Math.random().toString(36).slice(2)
const task = {
id,
interval: hour,
run: async () => {
runs.count += 1
},
}
await Instance.provide({
directory: one.path,
fn: async () => {
Scheduler.register(task)
await Instance.dispose()
},
})
expect(runs.count).toBe(1)
await Instance.provide({
directory: two.path,
fn: async () => {
Scheduler.register(task)
await Instance.dispose()
},
})
expect(runs.count).toBe(2)
})
test("global scope runs once across instances", async () => {
await using one = await tmpdir({ git: true })
await using two = await tmpdir({ git: true })
const runs = { count: 0 }
const id = "scheduler.global." + Math.random().toString(36).slice(2)
const task = {
id,
interval: hour,
run: async () => {
runs.count += 1
},
scope: "global" as const,
}
await Instance.provide({
directory: one.path,
fn: async () => {
Scheduler.register(task)
await Instance.dispose()
},
})
expect(runs.count).toBe(1)
await Instance.provide({
directory: two.path,
fn: async () => {
Scheduler.register(task)
await Instance.dispose()
},
})
expect(runs.count).toBe(1)
})
})
+76
View File
@@ -162,6 +162,12 @@ import type {
WorktreeCreateInput,
WorktreeCreateResponses,
WorktreeListResponses,
WorktreeRemoveErrors,
WorktreeRemoveInput,
WorktreeRemoveResponses,
WorktreeResetErrors,
WorktreeResetInput,
WorktreeResetResponses,
} from "./types.gen.js"
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<
@@ -654,6 +660,41 @@ export class Tool extends HeyApiClient {
}
export class Worktree extends HeyApiClient {
/**
* Remove worktree
*
* Remove a git worktree and delete its branch.
*/
public remove<ThrowOnError extends boolean = false>(
parameters?: {
directory?: string
worktreeRemoveInput?: WorktreeRemoveInput
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ key: "worktreeRemoveInput", map: "body" },
],
},
],
)
return (options?.client ?? this.client).delete<WorktreeRemoveResponses, WorktreeRemoveErrors, ThrowOnError>({
url: "/experimental/worktree",
...options,
...params,
headers: {
"Content-Type": "application/json",
...options?.headers,
...params.headers,
},
})
}
/**
* List worktrees
*
@@ -707,6 +748,41 @@ export class Worktree extends HeyApiClient {
},
})
}
/**
* Reset worktree
*
* Reset a worktree branch to the primary default branch.
*/
public reset<ThrowOnError extends boolean = false>(
parameters?: {
directory?: string
worktreeResetInput?: WorktreeResetInput
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ key: "worktreeResetInput", map: "body" },
],
},
],
)
return (options?.client ?? this.client).post<WorktreeResetResponses, WorktreeResetErrors, ThrowOnError>({
url: "/experimental/worktree/reset",
...options,
...params,
headers: {
"Content-Type": "application/json",
...options?.headers,
...params.headers,
},
})
}
}
export class Resource extends HeyApiClient {
+62
View File
@@ -1908,6 +1908,14 @@ export type WorktreeCreateInput = {
startCommand?: string
}
export type WorktreeRemoveInput = {
directory: string
}
export type WorktreeResetInput = {
directory: string
}
export type McpResource = {
name: string
uri: string
@@ -2554,6 +2562,33 @@ export type ToolListResponses = {
export type ToolListResponse = ToolListResponses[keyof ToolListResponses]
export type WorktreeRemoveData = {
body?: WorktreeRemoveInput
path?: never
query?: {
directory?: string
}
url: "/experimental/worktree"
}
export type WorktreeRemoveErrors = {
/**
* Bad request
*/
400: BadRequestError
}
export type WorktreeRemoveError = WorktreeRemoveErrors[keyof WorktreeRemoveErrors]
export type WorktreeRemoveResponses = {
/**
* Worktree removed
*/
200: boolean
}
export type WorktreeRemoveResponse = WorktreeRemoveResponses[keyof WorktreeRemoveResponses]
export type WorktreeListData = {
body?: never
path?: never
@@ -2599,6 +2634,33 @@ export type WorktreeCreateResponses = {
export type WorktreeCreateResponse = WorktreeCreateResponses[keyof WorktreeCreateResponses]
export type WorktreeResetData = {
body?: WorktreeResetInput
path?: never
query?: {
directory?: string
}
url: "/experimental/worktree/reset"
}
export type WorktreeResetErrors = {
/**
* Bad request
*/
400: BadRequestError
}
export type WorktreeResetError = WorktreeResetErrors[keyof WorktreeResetErrors]
export type WorktreeResetResponses = {
/**
* Worktree reset
*/
200: boolean
}
export type WorktreeResetResponse = WorktreeResetResponses[keyof WorktreeResetResponses]
export type ExperimentalResourceListData = {
body?: never
path?: never
+122
View File
@@ -920,6 +920,110 @@
"source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.worktree.list({\n ...\n})"
}
]
},
"delete": {
"operationId": "worktree.remove",
"parameters": [
{
"in": "query",
"name": "directory",
"schema": {
"type": "string"
}
}
],
"summary": "Remove worktree",
"description": "Remove a git worktree and delete its branch.",
"responses": {
"200": {
"description": "Worktree removed",
"content": {
"application/json": {
"schema": {
"type": "boolean"
}
}
}
},
"400": {
"description": "Bad request",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/BadRequestError"
}
}
}
}
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/WorktreeRemoveInput"
}
}
}
},
"x-codeSamples": [
{
"lang": "js",
"source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.worktree.remove({\n ...\n})"
}
]
}
},
"/experimental/worktree/reset": {
"post": {
"operationId": "worktree.reset",
"parameters": [
{
"in": "query",
"name": "directory",
"schema": {
"type": "string"
}
}
],
"summary": "Reset worktree",
"description": "Reset a worktree branch to the primary default branch.",
"responses": {
"200": {
"description": "Worktree reset",
"content": {
"application/json": {
"schema": {
"type": "boolean"
}
}
}
},
"400": {
"description": "Bad request",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/BadRequestError"
}
}
}
}
},
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/WorktreeResetInput"
}
}
}
},
"x-codeSamples": [
{
"lang": "js",
"source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.worktree.reset({\n ...\n})"
}
]
}
},
"/experimental/resource": {
@@ -9988,6 +10092,24 @@
}
}
},
"WorktreeRemoveInput": {
"type": "object",
"properties": {
"directory": {
"type": "string"
}
},
"required": ["directory"]
},
"WorktreeResetInput": {
"type": "object",
"properties": {
"directory": {
"type": "string"
}
},
"required": ["directory"]
},
"McpResource": {
"type": "object",
"properties": {
+8 -2
View File
@@ -118,9 +118,15 @@
outline: none;
}
}
}
&:focus-visible {
outline: none;
&[data-fit] {
[data-slot="dialog-container"] {
height: auto;
[data-slot="dialog-content"] {
min-height: 0;
}
}
}
}
+2 -1
View File
@@ -8,11 +8,12 @@ export interface DialogProps extends ParentProps {
action?: JSXElement
class?: ComponentProps<"div">["class"]
classList?: ComponentProps<"div">["classList"]
fit?: boolean
}
export function Dialog(props: DialogProps) {
return (
<div data-component="dialog">
<div data-component="dialog" data-fit={props.fit ? true : undefined}>
<div data-slot="dialog-container">
<Kobalte.Content
data-slot="dialog-content"
@@ -11,6 +11,11 @@
z-index: 50;
transform-origin: var(--kb-menu-content-transform-origin);
&:focus,
&:focus-visible {
outline: none;
}
&[data-closed] {
animation: dropdown-menu-close 0.15s ease-out;
}
+4 -1
View File
@@ -1,5 +1,7 @@
[data-slot="hover-card-trigger"] {
display: inline-flex;
display: flex;
width: 100%;
min-width: 0;
}
[data-component="hover-card-content"] {
@@ -8,6 +10,7 @@
max-width: 320px;
border-radius: var(--radius-md);
background-color: var(--surface-raised-stronger-non-alpha);
pointer-events: auto;
border: 1px solid color-mix(in oklch, var(--border-base) 50%, transparent);
background-clip: padding-box;
+3
View File
@@ -64,6 +64,9 @@ const icons = {
help: `<path d="M7.91683 7.91927V6.2526H12.0835V8.7526L10.0002 10.0026V12.0859M10.0002 13.7526V13.7609M17.9168 10.0026C17.9168 14.3749 14.3724 17.9193 10.0002 17.9193C5.62791 17.9193 2.0835 14.3749 2.0835 10.0026C2.0835 5.63035 5.62791 2.08594 10.0002 2.08594C14.3724 2.08594 17.9168 5.63035 17.9168 10.0026Z" stroke="currentColor" stroke-linecap="square"/>`,
"settings-gear": `<path d="M7.62516 4.46094L5.05225 3.86719L3.86475 5.05469L4.4585 7.6276L2.0835 9.21094V10.7943L4.4585 12.3776L3.86475 14.9505L5.05225 16.138L7.62516 15.5443L9.2085 17.9193H10.7918L12.3752 15.5443L14.9481 16.138L16.1356 14.9505L15.5418 12.3776L17.9168 10.7943V9.21094L15.5418 7.6276L16.1356 5.05469L14.9481 3.86719L12.3752 4.46094L10.7918 2.08594H9.2085L7.62516 4.46094Z" stroke="currentColor"/><path d="M12.5002 10.0026C12.5002 11.3833 11.3809 12.5026 10.0002 12.5026C8.61945 12.5026 7.50016 11.3833 7.50016 10.0026C7.50016 8.62189 8.61945 7.5026 10.0002 7.5026C11.3809 7.5026 12.5002 8.62189 12.5002 10.0026Z" stroke="currentColor"/>`,
dash: `<rect x="5" y="9.5" width="10" height="1" fill="currentColor"/>`,
"cloud-upload": `<path d="M12.0833 16.25H15C17.0711 16.25 18.75 14.5711 18.75 12.5C18.75 10.5649 17.2843 8.97217 15.4025 8.77133C15.2 6.13103 12.8586 4.08333 10 4.08333C7.71532 4.08333 5.76101 5.49781 4.96501 7.49881C2.84892 7.90461 1.25 9.76559 1.25 11.6667C1.25 13.9813 3.30203 16.25 5.83333 16.25H7.91667M10 16.25V10.4167M12.0833 11.875L10 9.79167L7.91667 11.875" stroke="currentColor" stroke-linecap="square"/>`,
trash: `<path d="M4.58342 17.9134L4.58369 17.4134L4.22787 17.5384L4.22766 18.0384H4.58342V17.9134ZM15.4167 17.9134V18.0384H15.7725L15.7723 17.5384L15.4167 17.9134ZM2.08342 3.95508V3.45508H1.58342V3.95508H2.08342V4.45508V3.95508ZM17.9167 4.45508V4.95508H18.4167V4.45508H17.9167V3.95508V4.45508ZM4.16677 4.58008L3.66701 4.5996L4.22816 17.5379L4.72792 17.4934L5.22767 17.4489L4.66652 4.54055L4.16677 4.58008ZM4.58342 18.0384V17.9134H15.4167V18.0384V18.5384H4.58342V18.0384ZM15.4167 17.9134L15.8332 17.5379L16.2498 4.5996L15.7501 4.58008L15.2503 4.56055L14.8337 17.4989L15.4167 17.9134ZM15.8334 4.58008V4.08008H4.16677V4.58008V5.08008H15.8334V4.58008ZM2.08342 4.45508V4.95508H4.16677V4.58008V4.08008H2.08342V4.45508ZM15.8334 4.58008V5.08008H17.9167V4.45508V3.95508H15.8334V4.58008ZM6.83951 4.35149L7.432 4.55047C7.79251 3.47701 8.80699 2.70508 10.0001 2.70508V2.20508V1.70508C8.25392 1.70508 6.77335 2.83539 6.24702 4.15251L6.83951 4.35149ZM10.0001 2.20508V2.70508C11.1932 2.70508 12.2077 3.47701 12.5682 4.55047L13.1607 4.35149L13.7532 4.15251C13.2269 2.83539 11.7463 1.70508 10.0001 1.70508V2.20508Z" fill="currentColor"/>`,
"question-mark": `<path d="M6 3.9975V2H14V6.99376L10 9.99001V11.9875M10 17.98V18" stroke="currentColor" stroke-width="1.5" stroke-linecap="square" />`,
}
export interface IconProps extends ComponentProps<"svg"> {
+18
View File
@@ -74,6 +74,24 @@
color: var(--icon-active);
}
}
> [data-component="icon-button"] {
background-color: transparent;
&:hover:not(:disabled),
&:focus:not(:disabled),
&:active:not(:disabled) {
background-color: transparent;
}
&:hover:not(:disabled) [data-slot="icon-svg"] {
color: var(--icon-hover);
}
&:active:not(:disabled) [data-slot="icon-svg"] {
color: var(--icon-active);
}
}
}
[data-slot="list-scroll"] {
+33 -6
View File
@@ -35,6 +35,25 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
mouseActive: false,
})
const scrollIntoView = (container: HTMLDivElement, node: HTMLElement, block: "center" | "nearest") => {
const containerRect = container.getBoundingClientRect()
const nodeRect = node.getBoundingClientRect()
const top = nodeRect.top - containerRect.top + container.scrollTop
const bottom = top + nodeRect.height
const viewTop = container.scrollTop
const viewBottom = viewTop + container.clientHeight
const target =
block === "center"
? top - container.clientHeight / 2 + nodeRect.height / 2
: top < viewTop
? top
: bottom > viewBottom
? bottom - container.clientHeight
: viewTop
const max = Math.max(0, container.scrollHeight - container.clientHeight)
container.scrollTop = Math.max(0, Math.min(target, max))
}
const { filter, grouped, flat, active, setActive, onKeyDown, onInput } = useFilteredList<T>(props)
const searchProps = () => (typeof props.search === "object" ? props.search : {})
@@ -65,24 +84,31 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
)
createEffect(() => {
if (!scrollRef()) return
const scroll = scrollRef()
if (!scroll) return
if (!props.current) return
const key = props.key(props.current)
requestAnimationFrame(() => {
const element = scrollRef()?.querySelector(`[data-key="${CSS.escape(key)}"]`)
element?.scrollIntoView({ block: "center" })
const element = scroll.querySelector(`[data-key="${CSS.escape(key)}"]`)
if (!(element instanceof HTMLElement)) return
scrollIntoView(scroll, element, "center")
})
})
createEffect(() => {
const all = flat()
if (store.mouseActive || all.length === 0) return
const scroll = scrollRef()
if (!scroll) return
if (active() === props.key(all[0])) {
scrollRef()?.scrollTo(0, 0)
scroll.scrollTo(0, 0)
return
}
const element = scrollRef()?.querySelector(`[data-key="${CSS.escape(active()!)}"]`)
element?.scrollIntoView({ block: "center" })
const key = active()
if (!key) return
const element = scroll.querySelector(`[data-key="${CSS.escape(key)}"]`)
if (!(element instanceof HTMLElement)) return
scrollIntoView(scroll, element, "center")
})
createEffect(() => {
@@ -206,6 +232,7 @@ export function List<T>(props: ListProps<T> & { ref?: (ref: ListRef) => void })
setActive(props.key(item))
}}
onMouseLeave={() => {
if (!store.mouseActive) return
setActive(null)
}}
>
@@ -10,6 +10,10 @@
width: 240px;
gap: 4px;
}
&[data-size="compact"] {
width: 24px;
}
}
[data-slot="message-nav-item"] {
+19 -5
View File
@@ -9,9 +9,10 @@ export function MessageNav(
current?: UserMessage
size: "normal" | "compact"
onMessageSelect: (message: UserMessage) => void
getLabel?: (message: UserMessage) => string | undefined
},
) {
const [local, others] = splitProps(props, ["messages", "current", "size", "onMessageSelect"])
const [local, others] = splitProps(props, ["messages", "current", "size", "onMessageSelect", "getLabel"])
const content = () => (
<ul role="list" data-component="message-nav" data-size={local.size} {...others}>
@@ -19,23 +20,36 @@ export function MessageNav(
{(message) => {
const handleClick = () => local.onMessageSelect(message)
const handleKeyPress = (event: KeyboardEvent) => {
if (event.key !== "Enter" && event.key !== " ") return
event.preventDefault()
local.onMessageSelect(message)
}
return (
<li data-slot="message-nav-item">
<Switch>
<Match when={local.size === "compact"}>
<div data-slot="message-nav-tick-button" data-active={message.id === local.current?.id || undefined}>
<div
data-slot="message-nav-tick-button"
data-active={message.id === local.current?.id || undefined}
role="button"
tabindex={0}
onClick={handleClick}
onKeyDown={handleKeyPress}
>
<div data-slot="message-nav-tick-line" />
</div>
</Match>
<Match when={local.size === "normal"}>
<button data-slot="message-nav-message-button" onClick={handleClick}>
<button data-slot="message-nav-message-button" onClick={handleClick} onKeyDown={handleKeyPress}>
<DiffChanges changes={message.summary?.diffs ?? []} variant="bars" />
<div
data-slot="message-nav-title-preview"
data-active={message.id === local.current?.id || undefined}
>
<Show when={message.summary?.title} fallback="New message">
{message.summary?.title}
<Show when={local.getLabel?.(message) ?? message.summary?.title} fallback="New message">
{local.getLabel?.(message) ?? message.summary?.title}
</Show>
</div>
</button>
+33 -2
View File
@@ -46,6 +46,7 @@ import { checksum } from "@opencode-ai/util/encode"
import { Tooltip } from "./tooltip"
import { IconButton } from "./icon-button"
import { createAutoScroll } from "../hooks"
import { createResizeObserver } from "@solid-primitives/resize-observer"
interface Diagnostic {
range: {
@@ -297,6 +298,23 @@ export function AssistantMessageDisplay(props: { message: AssistantMessage; part
export function UserMessageDisplay(props: { message: UserMessage; parts: PartType[] }) {
const dialog = useDialog()
const [copied, setCopied] = createSignal(false)
const [expanded, setExpanded] = createSignal(false)
const [canExpand, setCanExpand] = createSignal(false)
let textRef: HTMLDivElement | undefined
const updateCanExpand = () => {
const el = textRef
if (!el) return
if (expanded()) return
setCanExpand(el.scrollHeight > el.clientHeight + 2)
}
createResizeObserver(
() => textRef,
() => {
updateCanExpand()
},
)
const textPart = createMemo(
() => props.parts?.find((p) => p.type === "text" && !(p as TextPart).synthetic) as TextPart | undefined,
@@ -304,6 +322,11 @@ export function UserMessageDisplay(props: { message: UserMessage; parts: PartTyp
const text = createMemo(() => textPart()?.text || "")
createEffect(() => {
text()
updateCanExpand()
})
const files = createMemo(() => (props.parts?.filter((p) => p.type === "file") as FilePart[]) ?? [])
const attachments = createMemo(() =>
@@ -335,7 +358,7 @@ export function UserMessageDisplay(props: { message: UserMessage; parts: PartTyp
}
return (
<div data-component="user-message">
<div data-component="user-message" data-expanded={expanded()} data-can-expand={canExpand()}>
<Show when={attachments().length > 0}>
<div data-slot="user-message-attachments">
<For each={attachments()}>
@@ -365,8 +388,16 @@ export function UserMessageDisplay(props: { message: UserMessage; parts: PartTyp
</div>
</Show>
<Show when={text()}>
<div data-slot="user-message-text">
<div data-slot="user-message-text" ref={(el) => (textRef = el)}>
<HighlightedText text={text()} references={inlineFiles()} agents={agents()} />
<button
data-slot="user-message-expand"
type="button"
aria-label={expanded() ? "Collapse message" : "Expand message"}
onClick={() => setExpanded((v) => !v)}
>
<Icon name="chevron-down" size="small" />
</button>
<div data-slot="user-message-copy-wrapper">
<Tooltip value={copied() ? "Copied!" : "Copy"} placement="top" gutter={8}>
<IconButton icon={copied() ? "check" : "copy"} variant="secondary" onClick={handleCopy} />
+3 -1
View File
@@ -15,6 +15,7 @@ export type SelectProps<T> = Omit<ComponentProps<typeof Kobalte<T>>, "value" | "
class?: ComponentProps<"div">["class"]
classList?: ComponentProps<"div">["classList"]
children?: (item: T | undefined) => JSX.Element
placement?: "bottom-start" | "bottom-end" | "top-start" | "top-end"
}
export function Select<T>(props: SelectProps<T> & ButtonProps) {
@@ -29,6 +30,7 @@ export function Select<T>(props: SelectProps<T> & ButtonProps) {
"groupBy",
"onSelect",
"children",
"placement",
])
const grouped = createMemo(() => {
const result = pipe(
@@ -46,7 +48,7 @@ export function Select<T>(props: SelectProps<T> & ButtonProps) {
<Kobalte<T, { category: string; options: T[] }>
{...others}
data-component="select"
placement="bottom-start"
placement={local.placement ?? "bottom-start"}
value={local.current}
options={grouped()}
optionValue={(x) => (local.value ? local.value(x) : (x as string))}
@@ -1,44 +0,0 @@
[data-component="session-message-rail"] {
display: contents;
}
[data-slot="session-message-rail-compact"],
[data-slot="session-message-rail-full"] {
position: absolute;
left: 1.5rem;
margin-top: 0.625rem;
top: 0;
bottom: 8rem;
overflow-y: auto;
}
[data-slot="session-message-rail-compact"] {
display: flex;
}
[data-slot="session-message-rail-full"] {
display: none;
}
@container (min-width: 88rem) {
[data-slot="session-message-rail-compact"] {
display: none;
}
[data-slot="session-message-rail-full"] {
display: flex;
}
}
[data-component="session-message-rail"] [data-slot="session-message-rail-full"] {
transform: none;
}
[data-component="session-message-rail"][data-wide] [data-slot="session-message-rail-full"] {
margin-top: 0.125rem;
left: calc(((100% - min(100%, 50rem)) / 2) - 1.5rem);
transform: translateX(-100%);
}
[data-component="session-message-rail"]:not([data-wide]) [data-slot="session-message-rail-full"] {
margin-top: 0.625rem;
}
@@ -1,46 +0,0 @@
import { UserMessage } from "@opencode-ai/sdk/v2"
import { ComponentProps, Show, splitProps } from "solid-js"
import { MessageNav } from "./message-nav"
import "./session-message-rail.css"
export interface SessionMessageRailProps extends ComponentProps<"div"> {
messages: UserMessage[]
current?: UserMessage
wide?: boolean
onMessageSelect: (message: UserMessage) => void
}
export function SessionMessageRail(props: SessionMessageRailProps) {
const [local, others] = splitProps(props, ["messages", "current", "wide", "onMessageSelect", "class", "classList"])
return (
<Show when={(local.messages?.length ?? 0) > 1}>
<div
{...others}
data-component="session-message-rail"
data-wide={local.wide ? "" : undefined}
classList={{
...(local.classList ?? {}),
[local.class ?? ""]: !!local.class,
}}
>
<div data-slot="session-message-rail-compact">
<MessageNav
messages={local.messages}
current={local.current}
onMessageSelect={local.onMessageSelect}
size="compact"
/>
</div>
<div data-slot="session-message-rail-full">
<MessageNav
messages={local.messages}
current={local.current}
onMessageSelect={local.onMessageSelect}
size={local.wide ? "normal" : "compact"}
/>
</div>
</div>
</Show>
)
}
+94 -32
View File
@@ -1,4 +1,6 @@
[data-component="session-turn"] {
--session-turn-sticky-height: 0px;
--sticky-header-height: calc(var(--session-title-height, 0px) + var(--session-turn-sticky-height, 0px) + 12px);
/* flex: 1; */
height: 100%;
min-height: 0;
@@ -29,23 +31,6 @@
gap: 28px;
overflow-anchor: none;
[data-slot="session-turn-user-badges"] {
position: absolute;
right: 0;
display: flex;
gap: 6px;
padding-left: 16px;
background: linear-gradient(to right, transparent, var(--background-stronger) 12px);
opacity: 0;
transition: opacity 0.15s ease;
pointer-events: none;
}
&:hover [data-slot="session-turn-user-badges"] {
opacity: 1;
pointer-events: auto;
}
[data-slot="session-turn-badge"] {
display: inline-flex;
align-items: center;
@@ -61,23 +46,39 @@
}
}
[data-slot="session-turn-sticky-title"] {
[data-slot="session-turn-attachments"] {
width: 100%;
min-width: 0;
align-self: stretch;
}
[data-slot="session-turn-sticky"] {
width: calc(100% + 9px);
position: sticky;
top: 0;
top: var(--session-title-height, 0px);
z-index: 20;
background-color: var(--background-stronger);
z-index: 21;
margin-left: -9px;
padding-left: 9px;
padding-bottom: 12px;
display: flex;
flex-direction: column;
gap: 12px;
&::before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: var(--background-stronger);
z-index: -1;
}
}
[data-slot="session-turn-response-trigger"] {
position: sticky;
top: 32px;
background-color: var(--background-stronger);
z-index: 20;
width: calc(100% + 9px);
margin-left: -9px;
padding-left: 9px;
padding-bottom: 8px;
width: fit-content;
}
[data-slot="session-turn-message-header"] {
@@ -88,10 +89,72 @@
}
[data-slot="session-turn-message-content"] {
margin-top: -18px;
margin-top: 0;
max-width: 100%;
}
[data-component="user-message"] [data-slot="user-message-text"] {
max-height: var(--user-message-collapsed-height, 64px);
}
[data-component="user-message"][data-expanded="true"] [data-slot="user-message-text"] {
max-height: none;
}
[data-component="user-message"][data-can-expand="true"] [data-slot="user-message-text"] {
padding-right: 36px;
padding-bottom: 28px;
}
[data-component="user-message"] [data-slot="user-message-text"] [data-slot="user-message-expand"] {
display: none;
position: absolute;
bottom: 6px;
right: 6px;
padding: 0;
}
[data-component="user-message"][data-can-expand="true"]
[data-slot="user-message-text"]
[data-slot="user-message-expand"],
[data-component="user-message"][data-expanded="true"]
[data-slot="user-message-text"]
[data-slot="user-message-expand"] {
display: inline-flex;
align-items: center;
justify-content: center;
height: 22px;
width: 22px;
border: none;
border-radius: 6px;
background: transparent;
cursor: pointer;
color: var(--text-weak);
[data-slot="icon-svg"] {
transition: transform 0.15s ease;
}
}
[data-component="user-message"][data-expanded="true"]
[data-slot="user-message-text"]
[data-slot="user-message-expand"]
[data-slot="icon-svg"] {
transform: rotate(180deg);
}
[data-component="user-message"] [data-slot="user-message-text"] [data-slot="user-message-expand"]:hover {
background: var(--surface-raised-base);
color: var(--text-base);
}
[data-slot="session-turn-user-badges"] {
display: flex;
align-items: center;
gap: 6px;
padding-left: 16px;
}
[data-slot="session-turn-message-title"] {
width: 100%;
font-size: var(--font-size-large);
@@ -276,10 +339,9 @@
}
[data-component="sticky-accordion-header"] {
top: var(--sticky-header-height, 40px);
top: var(--sticky-header-height, 0px);
&[data-expanded]::before {
top: calc(-1 * var(--sticky-header-height, 40px));
top: calc(-1 * var(--sticky-header-height, 0px));
}
}
+106 -101
View File
@@ -1,5 +1,6 @@
import {
AssistantMessage,
FilePart,
Message as MessageType,
Part as PartType,
type PermissionRequest,
@@ -13,17 +14,13 @@ import { getDirectory, getFilename } from "@opencode-ai/util/path"
import { Binary } from "@opencode-ai/util/binary"
import { createEffect, createMemo, createSignal, For, Match, on, onCleanup, ParentProps, Show, Switch } from "solid-js"
import { createResizeObserver } from "@solid-primitives/resize-observer"
import { DiffChanges } from "./diff-changes"
import { Typewriter } from "./typewriter"
import { Message, Part } from "./message-part"
import { Markdown } from "./markdown"
import { Accordion } from "./accordion"
import { StickyAccordionHeader } from "./sticky-accordion-header"
import { FileIcon } from "./file-icon"
import { Icon } from "./icon"
import { ProviderIcon } from "./provider-icon"
import type { IconName } from "./provider-icons/types"
import { IconButton } from "./icon-button"
import { Tooltip } from "./tooltip"
import { Card } from "./card"
@@ -33,6 +30,7 @@ import { Spinner } from "./spinner"
import { createStore } from "solid-js/store"
import { DateTime, DurationUnit, Interval } from "luxon"
import { createAutoScroll } from "../hooks"
import { createResizeObserver } from "@solid-primitives/resize-observer"
function computeStatusFromPart(part: PartType | undefined): string | undefined {
if (!part) return undefined
@@ -79,6 +77,12 @@ function same<T>(a: readonly T[], b: readonly T[]) {
return a.every((x, i) => x === b[i])
}
function isAttachment(part: PartType | undefined) {
if (part?.type !== "file") return false
const mime = (part as FilePart).mime ?? ""
return mime.startsWith("image/") || mime === "application/pdf"
}
function AssistantMessageItem(props: {
message: AssistantMessage
responsePartId: string | undefined
@@ -119,6 +123,7 @@ function AssistantMessageItem(props: {
export function SessionTurn(
props: ParentProps<{
sessionID: string
sessionTitle?: string
messageID: string
lastUserMessageID?: string
stepsExpanded?: boolean
@@ -136,6 +141,7 @@ export function SessionTurn(
const emptyMessages: MessageType[] = []
const emptyParts: PartType[] = []
const emptyFiles: FilePart[] = []
const emptyAssistant: AssistantMessage[] = []
const emptyPermissions: PermissionRequest[] = []
const emptyPermissionParts: { part: ToolPart; message: AssistantMessage }[] = []
@@ -183,6 +189,19 @@ export function SessionTurn(
return data.store.part[msg.id] ?? emptyParts
})
const attachmentParts = createMemo(() => {
const msgParts = parts()
if (msgParts.length === 0) return emptyFiles
return msgParts.filter((part) => isAttachment(part)) as FilePart[]
})
const stickyParts = createMemo(() => {
const msgParts = parts()
if (msgParts.length === 0) return emptyParts
if (attachmentParts().length === 0) return msgParts
return msgParts.filter((part) => !isAttachment(part))
})
const assistantMessages = createMemo(
() => {
const msg = message()
@@ -330,10 +349,19 @@ export function SessionTurn(
const response = createMemo(() => lastTextPart()?.text)
const responsePartId = createMemo(() => lastTextPart()?.id)
const hasDiffs = createMemo(() => message()?.summary?.diffs?.length)
const hasDiffs = createMemo(() => (data.store.session_diff?.[props.sessionID]?.length ?? 0) > 0)
const hideResponsePart = createMemo(() => !working() && !!responsePartId())
const [responseCopied, setResponseCopied] = createSignal(false)
const [rootRef, setRootRef] = createSignal<HTMLDivElement | undefined>()
const [stickyRef, setStickyRef] = createSignal<HTMLDivElement | undefined>()
const updateStickyHeight = (height: number) => {
const root = rootRef()
if (!root) return
const next = Math.ceil(height)
root.style.setProperty("--session-turn-sticky-height", `${next}px`)
}
const handleCopyResponse = async () => {
const content = response()
if (!content) return
@@ -364,13 +392,28 @@ export function SessionTurn(
onUserInteracted: props.onUserInteracted,
})
createResizeObserver(
() => stickyRef(),
({ height }) => {
updateStickyHeight(height)
},
)
createEffect(() => {
const root = rootRef()
if (!root) return
const sticky = stickyRef()
if (!sticky) {
root.style.setProperty("--session-turn-sticky-height", "0px")
return
}
updateStickyHeight(sticky.getBoundingClientRect().height)
})
const diffInit = 20
const diffBatch = 20
const [store, setStore] = createStore({
stickyTitleRef: undefined as HTMLDivElement | undefined,
stickyTriggerRef: undefined as HTMLDivElement | undefined,
stickyHeaderHeight: 0,
retrySeconds: 0,
diffsOpen: [] as string[],
diffLimit: diffInit,
@@ -404,22 +447,6 @@ export function SessionTurn(
onCleanup(() => clearInterval(timer))
})
createResizeObserver(
() => store.stickyTitleRef,
({ height }) => {
const triggerHeight = store.stickyTriggerRef?.offsetHeight ?? 0
setStore("stickyHeaderHeight", height + triggerHeight + 8)
},
)
createResizeObserver(
() => store.stickyTriggerRef,
({ height }) => {
const titleHeight = store.stickyTitleRef?.offsetHeight ?? 0
setStore("stickyHeaderHeight", titleHeight + height + 8)
},
)
createEffect(() => {
const timer = setInterval(() => {
setStore("duration", duration())
@@ -460,7 +487,7 @@ export function SessionTurn(
})
return (
<div data-component="session-turn" class={props.classes?.root}>
<div data-component="session-turn" class={props.classes?.root} ref={setRootRef}>
<div
ref={autoScroll.scrollRef}
onScroll={autoScroll.handleScroll}
@@ -475,86 +502,63 @@ export function SessionTurn(
data-message={msg().id}
data-slot="session-turn-message-container"
class={props.classes?.container}
style={{ "--sticky-header-height": `${store.stickyHeaderHeight}px` }}
>
<Switch>
<Match when={isShellMode()}>
<Part part={shellModePart()!} message={msg()} defaultOpen />
</Match>
<Match when={true}>
{/* Title (sticky) */}
<div ref={(el) => setStore("stickyTitleRef", el)} data-slot="session-turn-sticky-title">
<div data-slot="session-turn-message-header">
<div data-slot="session-turn-message-title">
<Switch>
<Match when={working()}>
<Typewriter as="h1" text={msg().summary?.title} data-slot="session-turn-typewriter" />
</Match>
<Match when={true}>
<h1>{msg().summary?.title}</h1>
</Match>
</Switch>
</div>
<div data-slot="session-turn-user-badges">
<Show when={(msg() as UserMessage).agent}>
<span data-slot="session-turn-badge">{(msg() as UserMessage).agent}</span>
</Show>
<Show when={(msg() as UserMessage).model?.modelID}>
<span data-slot="session-turn-badge" class="inline-flex items-center gap-1">
<ProviderIcon
id={(msg() as UserMessage).model!.providerID as IconName}
class="size-3.5 shrink-0"
/>
{(msg() as UserMessage).model?.modelID}
</span>
</Show>
<span data-slot="session-turn-badge">{(msg() as UserMessage).variant || "default"}</span>
</div>
</div>
</div>
{/* User Message */}
<div data-slot="session-turn-message-content">
<Message message={msg()} parts={parts()} />
</div>
{/* Trigger (sticky) */}
<Show when={working() || hasSteps()}>
<div ref={(el) => setStore("stickyTriggerRef", el)} data-slot="session-turn-response-trigger">
<Button
data-expandable={assistantMessages().length > 0}
data-slot="session-turn-collapsible-trigger-content"
variant="ghost"
size="small"
onClick={props.onStepsExpandedToggle ?? (() => {})}
>
<Show when={working()}>
<Spinner />
</Show>
<Switch>
<Match when={retry()}>
<span data-slot="session-turn-retry-message">
{(() => {
const r = retry()
if (!r) return ""
return r.message.length > 60 ? r.message.slice(0, 60) + "..." : r.message
})()}
</span>
<span data-slot="session-turn-retry-seconds">
· retrying {store.retrySeconds > 0 ? `in ${store.retrySeconds}s ` : ""}
</span>
<span data-slot="session-turn-retry-attempt">(#{retry()?.attempt})</span>
</Match>
<Match when={working()}>{store.status ?? "Considering next steps"}</Match>
<Match when={props.stepsExpanded}>Hide steps</Match>
<Match when={!props.stepsExpanded}>Show steps</Match>
</Switch>
<span>·</span>
<span>{store.duration}</span>
<Show when={assistantMessages().length > 0}>
<Icon name="chevron-grabber-vertical" size="small" />
</Show>
</Button>
<Show when={attachmentParts().length > 0}>
<div data-slot="session-turn-attachments">
<Message message={msg()} parts={attachmentParts()} />
</div>
</Show>
<div data-slot="session-turn-sticky" ref={setStickyRef}>
{/* User Message */}
<div data-slot="session-turn-message-content">
<Message message={msg()} parts={stickyParts()} />
</div>
{/* Trigger (sticky) */}
<Show when={working() || hasSteps()}>
<div data-slot="session-turn-response-trigger">
<Button
data-expandable={assistantMessages().length > 0}
data-slot="session-turn-collapsible-trigger-content"
variant="ghost"
size="small"
onClick={props.onStepsExpandedToggle ?? (() => {})}
>
<Show when={working()}>
<Spinner />
</Show>
<Switch>
<Match when={retry()}>
<span data-slot="session-turn-retry-message">
{(() => {
const r = retry()
if (!r) return ""
return r.message.length > 60 ? r.message.slice(0, 60) + "..." : r.message
})()}
</span>
<span data-slot="session-turn-retry-seconds">
· retrying {store.retrySeconds > 0 ? `in ${store.retrySeconds}s ` : ""}
</span>
<span data-slot="session-turn-retry-attempt">(#{retry()?.attempt})</span>
</Match>
<Match when={working()}>{store.status ?? "Considering next steps"}</Match>
<Match when={props.stepsExpanded}>Hide steps</Match>
<Match when={!props.stepsExpanded}>Show steps</Match>
</Switch>
<span>·</span>
<span>{store.duration}</span>
<Show when={assistantMessages().length > 0}>
<Icon name="chevron-grabber-vertical" size="small" />
</Show>
</Button>
</div>
</Show>
</div>
{/* Response */}
<Show when={props.stepsExpanded && assistantMessages().length > 0}>
<div data-slot="session-turn-collapsible-content-inner">
@@ -612,7 +616,7 @@ export function SessionTurn(
setStore("diffsOpen", value)
}}
>
<For each={(msg().summary?.diffs ?? []).slice(0, store.diffLimit)}>
<For each={(data.store.session_diff?.[props.sessionID] ?? []).slice(0, store.diffLimit)}>
{(diff) => (
<Accordion.Item value={diff.file}>
<StickyAccordionHeader>
@@ -658,13 +662,13 @@ export function SessionTurn(
)}
</For>
</Accordion>
<Show when={(msg().summary?.diffs?.length ?? 0) > store.diffLimit}>
<Show when={(data.store.session_diff?.[props.sessionID]?.length ?? 0) > store.diffLimit}>
<Button
data-slot="session-turn-accordion-more"
variant="ghost"
size="small"
onClick={() => {
const total = msg().summary?.diffs?.length ?? 0
const total = data.store.session_diff?.[props.sessionID]?.length ?? 0
setStore("diffLimit", (limit) => {
const next = limit + diffBatch
if (next > total) return total
@@ -672,7 +676,8 @@ export function SessionTurn(
})
}}
>
Show more changes ({(msg().summary?.diffs?.length ?? 0) - store.diffLimit})
Show more changes (
{(data.store.session_diff?.[props.sessionID]?.length ?? 0) - store.diffLimit})
</Button>
</Show>
</div>
@@ -52,6 +52,7 @@
background: var(--input-base);
&:focus-within {
border-color: transparent;
/* border/shadow-xs/select */
box-shadow:
0 0 0 3px var(--border-weak-selected),
+17 -10
View File
@@ -73,6 +73,13 @@
0 0 0 1px var(--border-base, rgba(11, 6, 0, 0.2)), 0 1px 2px -1px rgba(19, 16, 16, 0.25),
0 1px 2px 0 rgba(19, 16, 16, 0.08), 0 1px 3px 0 rgba(19, 16, 16, 0.12), 0 0 0 2px var(--background-weak, #f1f0f0),
0 0 0 3px var(--border-selected, rgba(0, 74, 255, 0.99));
--shadow-xs-border-interactive:
0 0 0 1px var(--border-selected, rgba(0, 74, 255, 0.99)), 0 1px 2px -1px rgba(19, 16, 16, 0.25),
0 1px 2px 0 rgba(19, 16, 16, 0.08), 0 1px 3px 0 rgba(19, 16, 16, 0.12);
--shadow-lg-border-base:
0 0 0 1px var(--border-weak-base, rgba(17, 0, 0, 0.12)), 0 36px 80px 0 rgba(0, 0, 0, 0.03),
0 13.141px 29.201px 0 rgba(0, 0, 0, 0.04), 0 6.38px 14.177px 0 rgba(0, 0, 0, 0.05),
0 3.127px 6.95px 0 rgba(0, 0, 0, 0.06), 0 1.237px 2.748px 0 rgba(0, 0, 0, 0.09);
color-scheme: light;
--text-mix-blend-mode: multiply;
@@ -364,10 +371,10 @@
--surface-raised-stronger-non-alpha: var(--smoke-dark-3);
--surface-brand-base: var(--yuzu-light-9);
--surface-brand-hover: var(--yuzu-light-10);
--surface-interactive-base: var(--cobalt-light-3);
--surface-interactive-hover: var(--cobalt-light-4);
--surface-interactive-weak: var(--cobalt-light-2);
--surface-interactive-weak-hover: var(--cobalt-light-3);
--surface-interactive-base: var(--cobalt-dark-3);
--surface-interactive-hover: var(--cobalt-dark-4);
--surface-interactive-weak: var(--cobalt-dark-2);
--surface-interactive-weak-hover: var(--cobalt-dark-3);
--surface-success-base: var(--apple-light-3);
--surface-success-weak: var(--apple-light-2);
--surface-success-strong: var(--apple-light-9);
@@ -454,12 +461,12 @@
--border-weak-selected: var(--cobalt-dark-alpha-6);
--border-weak-disabled: var(--smoke-dark-alpha-6);
--border-weak-focus: var(--smoke-dark-alpha-8);
--border-interactive-base: var(--cobalt-light-7);
--border-interactive-hover: var(--cobalt-light-8);
--border-interactive-active: var(--cobalt-light-9);
--border-interactive-selected: var(--cobalt-light-9);
--border-interactive-disabled: var(--smoke-light-8);
--border-interactive-focus: var(--cobalt-light-9);
--border-interactive-base: var(--cobalt-dark-7);
--border-interactive-hover: var(--cobalt-dark-8);
--border-interactive-active: var(--cobalt-dark-9);
--border-interactive-selected: var(--cobalt-dark-9);
--border-interactive-disabled: var(--smoke-dark-8);
--border-interactive-focus: var(--cobalt-dark-9);
--border-success-base: var(--apple-light-6);
--border-success-hover: var(--apple-light-7);
--border-success-selected: var(--apple-light-9);
+2 -2
View File
@@ -125,7 +125,7 @@ To use OpenCode as an ACP agent in [CodeCompanion.nvim](https://github.com/olimo
```lua
require("codecompanion").setup({
strategies = {
interactions = {
chat = {
adapter = {
name = "opencode",
@@ -138,7 +138,7 @@ require("codecompanion").setup({
This config sets up CodeCompanion to use OpenCode as the ACP agent for chat.
If you need to pass environment variables (like `OPENCODE_API_KEY`), refer to [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/configuration/adapters#environment-variables-setting-an-api-key) in the CodeCompanion.nvim documentation for full details.
If you need to pass environment variables (like `OPENCODE_API_KEY`), refer to [Configuring Adapters: Environment Variables](https://codecompanion.olimorris.dev/getting-started#setting-an-api-key) in the CodeCompanion.nvim documentation for full details.
## Support
+3 -3
View File
@@ -21,7 +21,7 @@ There are two types of agents in OpenCode; primary agents and subagents.
### Primary agents
Primary agents are the main assistants you interact with directly. You can cycle through them using the **Tab** key, or your configured `switch_agent` keybind. These agents handle your main conversation and can access all configured tools.
Primary agents are the main assistants you interact with directly. You can cycle through them using the **Tab** key, or your configured `switch_agent` keybind. These agents handle your main conversation. Tool access is configured via permissions — for example, Build has all tools enabled while Plan is restricted.
:::tip
You can use the **Tab** key to switch between primary agents during a session.
@@ -72,7 +72,7 @@ This agent is useful when you want the LLM to analyze code, suggest changes, or
_Mode_: `subagent`
A general-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. Use when searching for keywords or files and you're not confident you'll find the right match in the first few tries.
A general-purpose agent for researching complex questions and executing multi-step tasks. Has full tool access (except todo), so it can make file changes when needed. Use this to run multiple units of work in parallel.
---
@@ -80,7 +80,7 @@ A general-purpose agent for researching complex questions, searching for code, a
_Mode_: `subagent`
A fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns, search code for keywords, or answer questions about the codebase.
A fast, read-only agent for exploring codebases. Cannot modify files. Use this when you need to quickly find files by patterns, search code for keywords, or answer questions about the codebase.
---
+59 -3
View File
@@ -654,21 +654,77 @@ GitLab Duo provides AI-powered agentic chat with native tool calling capabilitie
- **duo-chat-sonnet-4-5** - Balanced performance for most workflows
- **duo-chat-opus-4-5** - Most capable for complex analysis
:::note
You can also specify 'GITLAB_TOKEN' environment variable if you don't want
to store token in opencode auth storage.
:::
##### Self-Hosted GitLab
:::note[compliance note]
OpenCode uses a small model for some AI tasks like generating the session title.
It is configured to use gpt-5-nano by default, hosted by Zen. To lock OpenCode
to only use your own GitLab-hosted instance, add the following to your
`opencode.json` file. It is also recommended to disable session sharing.
```json
{
"$schema": "https://opencode.ai/config.json",
"small_model": "gitlab/duo-chat-haiku-4-5",
"share": "disabled"
}
```
:::
For self-hosted GitLab instances:
```bash
GITLAB_INSTANCE_URL=https://gitlab.company.com GITLAB_TOKEN=glpat-xxxxxxxxxxxxxxxxxxxx opencode
export GITLAB_INSTANCE_URL=https://gitlab.company.com
export GITLAB_TOKEN=glpat-...
```
If your instance runs a custom AI Gateway:
```bash
GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com
```
Or add to your bash profile:
```bash title="~/.bash_profile"
export GITLAB_INSTANCE_URL=https://gitlab.company.com
export GITLAB_TOKEN=glpat-xxxxxxxxxxxxxxxxxxxx
export GITLAB_AI_GATEWAY_URL=https://ai-gateway.company.com
export GITLAB_TOKEN=glpat-...
```
:::note
Your GitLab administrator must enable the following:
1. [Duo Agent Platform](https://docs.gitlab.com/user/gitlab_duo/turn_on_off/) for the user, group, or instance
2. Feature flags (via Rails console):
- `agent_platform_claude_code`
- `third_party_agents_enabled`
:::
##### OAuth for Self-Hosted instances
In order to make Oauth working for your self-hosted instance, you need to create
a new application (Settings → Applications) with the
callback URL `http://127.0.0.1:8080/callback` and following scopes:
- api (Access the API on your behalf)
- read_user (Read your personal information)
- read_repository (Allows read-only access to the repository)
Then expose application ID as environment variable:
```bash
export GITLAB_OAUTH_CLIENT_ID=your_application_id_here
```
More documentation on [opencode-gitlab-auth](https://www.npmjs.com/package/@gitlab/opencode-gitlab-auth) homepage.
##### Configuration
Customize through `opencode.json`:
@@ -690,7 +746,7 @@ Customize through `opencode.json`:
}
```
##### GitLab API Tools (Optional)
##### GitLab API Tools (Optional, but highly recommended)
To access GitLab tools (merge requests, issues, pipelines, CI/CD, etc.):
+4
View File
@@ -9,6 +9,10 @@
"opencode#test": {
"dependsOn": ["^build"],
"outputs": []
},
"@opencode-ai/app#test": {
"dependsOn": ["^build"],
"outputs": []
}
}
}