Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4136680b77 | ||
|
|
0385713da4 | ||
|
|
0ce7e56e43 | ||
|
|
350d76ee14 | ||
|
|
6d7fe2eeb7 | ||
|
|
460d9c3eb9 | ||
|
|
cb8015a34d | ||
|
|
8f50ca8e2c | ||
|
|
4ceabac764 | ||
|
|
7a3f21e7ca | ||
|
|
9b9fe0d64b | ||
|
|
17b43960e8 | ||
|
|
e5c7ac5a8c | ||
|
|
a480f07241 | ||
|
|
1eb6fcea84 | ||
|
|
4ef361da73 | ||
|
|
c07ac592d8 | ||
|
|
d649ccf715 | ||
|
|
f54f4385e5 | ||
|
|
e25ce07cc2 | ||
|
|
532a1d891d | ||
|
|
9e2f7129e3 | ||
|
|
a4298f1ceb | ||
|
|
86c94b4852 | ||
|
|
69d9a659a3 | ||
|
|
9acf46a76d | ||
|
|
44b39fe2ec | ||
|
|
02903f2db8 | ||
|
|
22b7d8c524 | ||
|
|
fe2fde5172 | ||
|
|
7da6522fb8 | ||
|
|
08e6d4cfbf | ||
|
|
35822884d1 | ||
|
|
95038c1add | ||
|
|
664768bff5 | ||
|
|
4e38d93a8f | ||
|
|
dbebc387dd | ||
|
|
5cf83ffe8f | ||
|
|
ada410bccf | ||
|
|
00b5c3e1b3 | ||
|
|
188df6da07 | ||
|
|
0d55a42840 | ||
|
|
0ee302e24d | ||
|
|
d5b7690f95 | ||
|
|
8d1d699f88 | ||
|
|
b0b7b38da1 | ||
|
|
fd3b96b487 | ||
|
|
aa2d385a62 | ||
|
|
e25db3a572 | ||
|
|
b8305afa29 | ||
|
|
b7c89cf496 | ||
|
|
3a1daa87ac | ||
|
|
055897f0ea | ||
|
|
40b3a80034 | ||
|
|
f6978db605 | ||
|
|
de05b0c94e | ||
|
|
6d1505c9fb | ||
|
|
306ec4bb84 | ||
|
|
3b98fe3548 | ||
|
|
66c326b8c4 | ||
|
|
8dbcf92a0d | ||
|
|
37965da01d | ||
|
|
57b59b5bf2 | ||
|
|
20f346d8ef | ||
|
|
c83bc5d48a | ||
|
|
cace5784c3 | ||
|
|
1985d2c2ef | ||
|
|
3fe96f17b4 | ||
|
|
dc994a1fe4 | ||
|
|
932ec190ed | ||
|
|
034a8bcab3 | ||
|
|
97263c5db4 | ||
|
|
da6ea88331 | ||
|
|
d686613e34 | ||
|
|
12fc9b7a12 | ||
|
|
a22cb0548f | ||
|
|
9bebd283a5 | ||
|
|
493fbfab91 | ||
|
|
9df3c64021 | ||
|
|
8ac57f7944 | ||
|
|
29cb917ac4 | ||
|
|
9c64f12ea0 | ||
|
|
0f184c28b0 | ||
|
|
a3b1df5224 | ||
|
|
4e0c003e78 | ||
|
|
60387f67e9 | ||
|
|
ce94feeea1 | ||
|
|
39ca3ee858 | ||
|
|
52a6067802 | ||
|
|
721b6b4c6f | ||
|
|
40009735ee | ||
|
|
df9d34004f | ||
|
|
f297e30e4c | ||
|
|
a7a44d0662 | ||
|
|
d8d329691a | ||
|
|
54179c86b8 | ||
|
|
8dba2d6484 | ||
|
|
ed6b7fbf27 | ||
|
|
b991b9b9e6 | ||
|
|
505db9f696 | ||
|
|
2d87574e62 | ||
|
|
b2cca674df | ||
|
|
549043863a | ||
|
|
b7df3dfca0 | ||
|
|
6891c77d3e | ||
|
|
d90e15d1d7 | ||
|
|
e0117b271a | ||
|
|
188a40c315 | ||
|
|
7a08fcf2e8 | ||
|
|
19d47408a5 | ||
|
|
3e07f5a6a4 |
No files matched your search
@@ -0,0 +1 @@
|
||||
plans/
|
||||
@@ -2,15 +2,22 @@
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24",
|
||||
"nodeGypDependencies": true
|
||||
"version": "24.13.1"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.12"
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
|
||||
@@ -30,3 +30,6 @@ github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
@@ -9,7 +9,7 @@ on:
|
||||
jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -71,12 +71,39 @@ jobs:
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
mobile_native_static_analysis:
|
||||
name: Mobile Native Static Analysis
|
||||
runs-on: blacksmith-12vcpu-macos-26
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Install mobile native static analysis tools
|
||||
run: brew bundle install --file apps/mobile/Brewfile
|
||||
|
||||
- name: Lint mobile native sources
|
||||
run: node scripts/mobile-native-static-check.ts
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
|
||||
+199
-14
@@ -4,8 +4,9 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
- "!v*-nightly.*"
|
||||
schedule:
|
||||
- cron: "0 9 * * *"
|
||||
- cron: "0 */3 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
@@ -26,9 +27,46 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
|
||||
head_sha=$(git rev-parse HEAD)
|
||||
|
||||
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
|
||||
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
|
||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
needs: [check_changes]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
release_channel: ${{ steps.release_meta.outputs.release_channel }}
|
||||
@@ -134,6 +172,7 @@ jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -141,25 +180,30 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
# target: nsis
|
||||
# arch: arm64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -183,6 +227,23 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
@@ -272,6 +333,18 @@ jobs:
|
||||
done
|
||||
fi
|
||||
|
||||
# Enable if Windows arm64 builds are enabled.
|
||||
# Windows updater metadata is channel-specific (for example
|
||||
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
|
||||
# release job can merge matching arm64/x64 manifests back into one
|
||||
# canonical manifest per channel.
|
||||
# if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# shopt -s nullglob
|
||||
# for manifest in release-publish/*.yml; do
|
||||
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -282,7 +355,8 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -302,13 +376,16 @@ jobs:
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build web package
|
||||
run: bun --filter=@t3tools/web run build
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
run: bun --filter=t3 run build
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
@@ -316,19 +393,36 @@ jobs:
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -342,11 +436,40 @@ jobs:
|
||||
for x64_manifest in release-assets/*-mac-x64.yml; do
|
||||
arm64_manifest="${x64_manifest%-x64.yml}.yml"
|
||||
if [[ -f "$arm64_manifest" ]]; then
|
||||
node scripts/merge-mac-update-manifests.ts "$arm64_manifest" "$x64_manifest"
|
||||
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
|
||||
rm -f "$x64_manifest"
|
||||
fi
|
||||
done
|
||||
|
||||
# - name: Merge Windows updater manifests
|
||||
# run: |
|
||||
# shopt -s nullglob
|
||||
# found_windows_manifest=false
|
||||
# for x64_manifest in release-assets/*-win-x64.yml; do
|
||||
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
|
||||
# continue
|
||||
# fi
|
||||
|
||||
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
|
||||
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
|
||||
# if [[ ! -f "$arm64_manifest" ]]; then
|
||||
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
# found_windows_manifest=true
|
||||
# node scripts/merge-update-manifests.ts --platform win \
|
||||
# "$arm64_manifest" \
|
||||
# "$x64_manifest" \
|
||||
# "$output_manifest"
|
||||
# rm -f "$arm64_manifest" "$x64_manifest"
|
||||
# done
|
||||
|
||||
# if [[ "$found_windows_manifest" != true ]]; then
|
||||
# echo "No Windows updater manifests found to merge." >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
@@ -366,6 +489,7 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
@@ -385,12 +509,13 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: needs.preflight.outputs.release_channel == 'stable'
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
@@ -429,6 +554,9 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
@@ -437,7 +565,7 @@ jobs:
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -460,3 +588,60 @@ jobs:
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
|
||||
announce_discord:
|
||||
name: Announce release on Discord
|
||||
if: |
|
||||
always() && !cancelled() &&
|
||||
needs.preflight.result == 'success' &&
|
||||
needs.release.result == 'success' &&
|
||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
||||
needs: [preflight, release, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- name: Announce prerelease on Discord
|
||||
if: needs.preflight.outputs.is_prerelease == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts prerelease \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
|
||||
- name: Announce latest release on Discord
|
||||
if: needs.preflight.outputs.make_latest == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts latest \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
+9
-1
@@ -14,5 +14,13 @@
|
||||
"apps/mobile/uniwind-types.d.ts",
|
||||
"*.icon/**"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
"sortPackageJson": {},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [".devcontainer/devcontainer.json"],
|
||||
"options": {
|
||||
"trailingComma": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
# Version Control Phase 1: VCS Driver Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
|
||||
|
||||
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
|
||||
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
|
||||
- Add server services under `apps/server/src/vcs`:
|
||||
- `Services/VcsDriver.ts`
|
||||
- `Services/VcsRepositoryResolver.ts`
|
||||
- `Services/VcsProcess.ts`
|
||||
- `Layers/GitVcsDriver.ts`
|
||||
- `errors.ts`
|
||||
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
|
||||
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
|
||||
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
|
||||
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
|
||||
- No T3 Review implementation yet.
|
||||
- No broad UI redesign.
|
||||
|
||||
## Driver Model
|
||||
|
||||
Use provider-neutral nouns in new APIs:
|
||||
|
||||
- `VcsDriver`: local repository mechanics.
|
||||
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
|
||||
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
|
||||
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
|
||||
- `RefName`: branch, bookmark, tag, or provider-specific ref.
|
||||
|
||||
The initial driver capabilities should be explicit:
|
||||
|
||||
```ts
|
||||
export interface VcsDriverCapabilities {
|
||||
readonly kind: "git" | "jj" | "sapling" | "unknown";
|
||||
readonly supportsWorktrees: boolean;
|
||||
readonly supportsBookmarks: boolean;
|
||||
readonly supportsAtomicSnapshot: boolean;
|
||||
readonly supportsPushDefaultRemote: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
|
||||
|
||||
- `detectRepository(cwd)`
|
||||
- `status(cwd, options)`
|
||||
- `listRefs(cwd, query/pagination)`
|
||||
- `checkoutRef(cwd, ref)`
|
||||
- `createRef(cwd, ref, from?)`
|
||||
- `createWorkspace(cwd, ref, path?)`
|
||||
- `removeWorkspace(path)`
|
||||
- `prepareChangeContext(cwd, filePaths?)`
|
||||
- `createChange(cwd, message, options)`
|
||||
- `push(cwd, target?)`
|
||||
- `rangeContext(cwd, base, head)`
|
||||
- `listWorkspaceFiles(cwd, options)`
|
||||
|
||||
## Effect Process Layer
|
||||
|
||||
Create a small reusable `VcsProcess` service instead of using `runProcess`.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
|
||||
- Support scoped acquisition/release for long-running commands and interruption.
|
||||
- Support bounded stdout/stderr collection with truncation markers.
|
||||
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
|
||||
- Support stdin.
|
||||
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
|
||||
- Stream output lines to progress callbacks as Effects.
|
||||
- Return a typed `ProcessOutput` value for successful execution.
|
||||
- Fail with typed errors, not generic thrown exceptions.
|
||||
|
||||
Errors should be schema-backed tagged classes, for example:
|
||||
|
||||
- `VcsProcessSpawnError`
|
||||
- `VcsProcessExitError`
|
||||
- `VcsProcessTimeoutError`
|
||||
- `VcsOutputDecodeError`
|
||||
- `VcsRepositoryDetectionError`
|
||||
- `VcsUnsupportedOperationError`
|
||||
|
||||
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
|
||||
|
||||
## Git Driver Rewrite
|
||||
|
||||
Rewrite Git support against `VcsProcess`.
|
||||
|
||||
Carry forward current behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.test.ts`
|
||||
- current Git status/branch/worktree contracts
|
||||
|
||||
But split the implementation into smaller modules:
|
||||
|
||||
- command execution and hardening config
|
||||
- repository detection
|
||||
- status parsing
|
||||
- branch/ref parsing
|
||||
- worktree operations
|
||||
- commit/range context generation
|
||||
- push/pull operations
|
||||
|
||||
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
|
||||
|
||||
## Freshness and Local Caching
|
||||
|
||||
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
|
||||
|
||||
Treat these as live/local:
|
||||
|
||||
- repository detection for the active cwd
|
||||
- working copy dirty state
|
||||
- staged/unstaged/untracked file summaries
|
||||
- current branch/bookmark/change name
|
||||
- local branch/bookmark lists
|
||||
- local worktree/workspace lists
|
||||
|
||||
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
|
||||
|
||||
Treat these as cached or explicit-refresh only:
|
||||
|
||||
- remote tracking branch refreshes
|
||||
- ahead/behind counts that require network fetches
|
||||
- default branch discovery from a remote provider
|
||||
- remote branch lists beyond locally known refs
|
||||
|
||||
The VCS driver should expose freshness metadata with status results:
|
||||
|
||||
```ts
|
||||
export interface VcsFreshness {
|
||||
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
|
||||
|
||||
Use Effect `Cache` for repository identity and expensive local metadata:
|
||||
|
||||
- key by resolved repository root plus VCS kind
|
||||
- invalidate on cwd/root changes and workspace mutation operations
|
||||
- use short TTLs for local status caches when filesystem events are unavailable
|
||||
- never hide command failures behind stale values unless the caller explicitly accepts stale data
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
Prefer direct migration and deletion over compatibility wrappers.
|
||||
|
||||
Rules:
|
||||
|
||||
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
|
||||
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
|
||||
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
|
||||
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
|
||||
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
|
||||
- No new feature work may depend on transitional modules.
|
||||
|
||||
Expected transitional candidates:
|
||||
|
||||
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
|
||||
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
|
||||
|
||||
## Tests
|
||||
|
||||
Add integration-style tests with real temporary Git repositories for the new Git driver:
|
||||
|
||||
- non-repository detection
|
||||
- status for clean/dirty/untracked/staged states
|
||||
- branch/ref list with pagination
|
||||
- checkout/create branch
|
||||
- worktree create/remove
|
||||
- commit context generation with file filters
|
||||
- commit creation with hook progress events
|
||||
- push behavior against a local bare remote
|
||||
- status polling does not perform remote network refresh by default
|
||||
- concurrent duplicate status requests are coalesced
|
||||
- bounded output/truncation
|
||||
- timeout/interruption
|
||||
- typed error shape for command failure and missing executable
|
||||
|
||||
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `vcs` contracts and tagged errors.
|
||||
2. Add `VcsProcess` and unit tests around process execution semantics.
|
||||
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
|
||||
4. Implement `GitVcsDriver` with real Git command integration tests.
|
||||
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
|
||||
6. Move commit/range/push callers to the VCS service directly.
|
||||
7. Delete migrated `GitCore` internals and tests as each caller group moves.
|
||||
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
|
||||
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Current Git branch/status/worktree/commit behavior remains intact.
|
||||
- New Git implementation does not depend on `processRunner.ts`.
|
||||
- New errors are typed and inspectable by tests.
|
||||
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
|
||||
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Background status refresh is local-only by default and cannot hit provider rate limits.
|
||||
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -0,0 +1,268 @@
|
||||
# Version Control Phase 2: Source Control Provider Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
|
||||
|
||||
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
|
||||
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
|
||||
- Add server services under `apps/server/src/sourceControl`:
|
||||
- `Services/SourceControlProvider.ts`
|
||||
- `Services/SourceControlProviderRegistry.ts`
|
||||
- `Services/SourceControlProcess.ts`
|
||||
- `Layers/GitHubSourceControlProvider.ts`
|
||||
- `errors.ts`
|
||||
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
|
||||
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
|
||||
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
|
||||
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
|
||||
- No in-app review UI yet.
|
||||
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
|
||||
|
||||
## Provider Model
|
||||
|
||||
Use provider-neutral names:
|
||||
|
||||
- `SourceControlProvider`: hosted repository and change-request mechanics.
|
||||
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
|
||||
- `ChangeRequestThread`: review or discussion thread.
|
||||
- `ChangeRequestComment`: top-level or inline comment.
|
||||
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
|
||||
|
||||
Core provider operations:
|
||||
|
||||
- `detectRemote(remoteUrl)`
|
||||
- `checkAuth(cwd)`
|
||||
- `getRepository(cwd | remoteUrl)`
|
||||
- `getDefaultTargetRef(repository)`
|
||||
- `listChangeRequests(repository, filters)`
|
||||
- `getChangeRequest(repository, reference)`
|
||||
- `createChangeRequest(repository, input)`
|
||||
- `checkoutChangeRequest(cwd, changeRequest, options)`
|
||||
- `getCloneUrls(repository)`
|
||||
|
||||
Review-facing operations should be designed now, even if unimplemented:
|
||||
|
||||
- `listReviewThreads(changeRequest)`
|
||||
- `createReviewComment(changeRequest, input)`
|
||||
- `replyToReviewThread(thread, input)`
|
||||
- `resolveReviewThread(thread)`
|
||||
- `submitReview(changeRequest, input)`
|
||||
|
||||
Each operation should be guarded by capabilities:
|
||||
|
||||
```ts
|
||||
export interface SourceControlProviderCapabilities {
|
||||
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
|
||||
readonly supportsCreateChangeRequest: boolean;
|
||||
readonly supportsCheckoutChangeRequest: boolean;
|
||||
readonly supportsReviewThreads: boolean;
|
||||
readonly supportsInlineComments: boolean;
|
||||
readonly supportsDraftChangeRequests: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Provider Registry
|
||||
|
||||
Add a registry that resolves a provider from repository remotes and explicit user input.
|
||||
|
||||
Rules:
|
||||
|
||||
- Detection should be pure where possible and testable without spawning CLIs.
|
||||
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
|
||||
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
|
||||
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
|
||||
|
||||
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
|
||||
|
||||
## Rate Limits and Provider Caching
|
||||
|
||||
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
|
||||
|
||||
Default behavior:
|
||||
|
||||
- Pure URL/remote parsing is always live because it is local.
|
||||
- Provider detection from local remotes is live-local.
|
||||
- Authentication checks are cached.
|
||||
- Repository metadata is cached.
|
||||
- Default branch metadata is cached.
|
||||
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
|
||||
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
|
||||
- Create/update operations invalidate affected cache keys immediately after success.
|
||||
|
||||
The provider API should make freshness explicit:
|
||||
|
||||
```ts
|
||||
export interface SourceControlFreshness {
|
||||
readonly source: "live-local" | "cached-provider" | "live-provider";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
readonly stale?: boolean;
|
||||
}
|
||||
|
||||
export type ProviderRefreshPolicy =
|
||||
| "cache-first"
|
||||
| "stale-while-revalidate"
|
||||
| "force-refresh"
|
||||
| "local-only";
|
||||
```
|
||||
|
||||
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
|
||||
|
||||
Use Effect `Cache` for provider data:
|
||||
|
||||
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
|
||||
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
|
||||
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
|
||||
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
|
||||
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
|
||||
|
||||
Provider drivers should surface rate-limit signals when available:
|
||||
|
||||
- remaining quota
|
||||
- reset time
|
||||
- retry-after duration
|
||||
- whether the limit is primary, secondary/abuse, or unknown
|
||||
|
||||
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
|
||||
|
||||
Avoid rate-limit footguns:
|
||||
|
||||
- no provider calls from render loops or fast status polling
|
||||
- no listing all PRs/MRs across all repos to infer one branch state
|
||||
- no silent GitHub fallback for unknown providers
|
||||
- no unbounded cache cardinality for branch names or free-form search queries
|
||||
- no per-thread duplicate provider refresh when multiple views observe the same repository
|
||||
|
||||
## GitHub Provider Rewrite
|
||||
|
||||
Rewrite GitHub support as `GitHubSourceControlProvider`.
|
||||
|
||||
Carry forward behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitHubCli.ts`
|
||||
- `apps/server/src/git/Layers/GitHubCli.test.ts`
|
||||
- `apps/server/src/git/githubPullRequests.ts`
|
||||
- GitHub-specific `GitManager` PR paths
|
||||
|
||||
Implementation requirements:
|
||||
|
||||
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
|
||||
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
|
||||
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
|
||||
- Keep stdout/stderr bounded.
|
||||
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
|
||||
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
|
||||
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
|
||||
|
||||
## GitManager Cutover
|
||||
|
||||
Refactor `GitManager` so it coordinates three independent services:
|
||||
|
||||
- `VcsDriver` for local repository mechanics.
|
||||
- `SourceControlProviderRegistry` for hosted provider selection.
|
||||
- `TextGeneration` for message/body generation.
|
||||
|
||||
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
|
||||
|
||||
The Commit + PR flow should become:
|
||||
|
||||
1. Resolve VCS repository and local status.
|
||||
2. Resolve source-control provider from remotes.
|
||||
3. Generate commit content through the existing text generation service.
|
||||
4. Create local change through `VcsDriver`.
|
||||
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
|
||||
6. Generate change-request title/body.
|
||||
7. Create the change request through `SourceControlProvider`.
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
This phase should aggressively remove old GitHub-specific internals.
|
||||
|
||||
Rules:
|
||||
|
||||
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
|
||||
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
|
||||
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
|
||||
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
|
||||
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
|
||||
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
|
||||
|
||||
## GitLab and Azure Readiness
|
||||
|
||||
Use the triaged references as implementation inputs, not merge targets:
|
||||
|
||||
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
|
||||
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
|
||||
|
||||
The abstraction should let Phase 3 add:
|
||||
|
||||
- `GitLabSourceControlProvider` using `glab`.
|
||||
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
|
||||
|
||||
No provider should need to edit GitHub code to join the registry.
|
||||
|
||||
## T3 Review Design Constraint
|
||||
|
||||
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
|
||||
|
||||
That means contracts should include stable IDs and enough metadata for:
|
||||
|
||||
- file-level diffs
|
||||
- inline review threads
|
||||
- resolved/unresolved state
|
||||
- top-level discussion comments
|
||||
- pending review submission
|
||||
- provider URL back-links
|
||||
|
||||
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
|
||||
|
||||
## Tests
|
||||
|
||||
Add tests at three levels:
|
||||
|
||||
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
|
||||
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
|
||||
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
|
||||
|
||||
Required cases:
|
||||
|
||||
- GitHub PR URL, number, and branch-ish references.
|
||||
- GitLab MR URL/reference parsing.
|
||||
- Azure DevOps PR URL parsing for same-repo URLs.
|
||||
- unknown provider returns unsupported-operation errors.
|
||||
- missing CLI and auth failures produce distinct typed errors.
|
||||
- invalid CLI JSON fails at decode boundary with useful context.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `sourceControl` contracts and provider-neutral schemas.
|
||||
2. Add shared remote/reference parser helpers and tests.
|
||||
3. Add `SourceControlProcess` and provider errors.
|
||||
4. Add provider registry with GitHub-only registration.
|
||||
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
|
||||
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
|
||||
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
|
||||
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
|
||||
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Existing GitHub Commit + PR and PR checkout flows still work.
|
||||
- `GitManager` no longer imports or depends on `GitHubCli`.
|
||||
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
|
||||
- Unknown/unsupported providers fail explicitly and visibly.
|
||||
- GitHub command execution does not depend on `processRunner.ts`.
|
||||
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
|
||||
- Rate-limit responses become typed errors with retry/reset metadata where available.
|
||||
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -10,3 +10,5 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
Vendored
+1
-1
@@ -5,5 +5,5 @@
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib"
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
## Task Completion Requirements
|
||||
|
||||
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
|
||||
- If changing native mobile code, `bun lint:mobile` must also pass.
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
@@ -5,11 +5,12 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> T3 Code currently supports Codex, Claude, and OpenCode.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
|
||||
@@ -1,27 +1,29 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.17",
|
||||
"version": "0.0.21",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"dev:electron": "node scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"start": "node scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {
|
||||
}
|
||||
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"dist-electron/main.cjs",
|
||||
"dist-electron/preload.cjs",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
@@ -69,7 +69,7 @@ function startApp() {
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
@@ -20,7 +19,7 @@ import { fileURLToPath } from "node:url";
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
const LAUNCHER_VERSION = 2;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
@@ -121,40 +120,6 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
@@ -192,7 +157,6 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
@@ -206,5 +170,11 @@ export function resolveElectronPath() {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
// Dev launches do not need a renamed app bundle badly enough to risk breaking
|
||||
// Electron helper resource lookup on macOS.
|
||||
if (isDevelopment) {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding";
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
|
||||
|
||||
describe("resolveDesktopAppStageLabel", () => {
|
||||
it("uses Dev in desktop development", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
|
||||
|
||||
import { isNightlyDesktopVersion } from "./updateChannels";
|
||||
import { isNightlyDesktopVersion } from "./updateChannels.ts";
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveDesktopBackendPort } from "./backendPort";
|
||||
import { resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
|
||||
describe("resolveDesktopBackendPort", () => {
|
||||
it("returns the starting port when it is available", async () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
BackendReadinessAbortedError,
|
||||
isBackendReadinessAborted,
|
||||
waitForHttpReady,
|
||||
} from "./backendReadiness";
|
||||
} from "./backendReadiness.ts";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
|
||||
describe("waitForBackendStartupReady", () => {
|
||||
it("falls back to the HTTP probe when no listening signal exists", async () => {
|
||||
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
const cancelHttpWait = vi.fn();
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("http");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the listening signal and cancels the HTTP probe", async () => {
|
||||
let rejectHttpWait: ((error: unknown) => void) | null = null;
|
||||
const waitForHttpReady = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((_resolve, reject) => {
|
||||
rejectHttpWait = reject;
|
||||
}),
|
||||
);
|
||||
const cancelHttpWait = vi.fn(() => {
|
||||
rejectHttpWait?.(new BackendReadinessAbortedError());
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.resolve(),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("listening");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects when the listening signal fails before HTTP readiness", async () => {
|
||||
const error = new Error("backend exited");
|
||||
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.reject(error),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait: vi.fn(),
|
||||
}),
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { isBackendReadinessAborted } from "./backendReadiness.ts";
|
||||
|
||||
export interface WaitForBackendStartupReadyOptions {
|
||||
readonly listeningPromise?: Promise<void> | null;
|
||||
readonly waitForHttpReady: () => Promise<void>;
|
||||
readonly cancelHttpWait: () => void;
|
||||
}
|
||||
|
||||
export async function waitForBackendStartupReady(
|
||||
options: WaitForBackendStartupReadyOptions,
|
||||
): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = options.waitForHttpReady();
|
||||
const listeningPromise = options.listeningPromise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
options.cancelHttpWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence";
|
||||
} from "./clientPersistence.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
@@ -49,9 +49,16 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
||||
}
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
},
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { Predicate } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface ClientSettingsDocument {
|
||||
readonly settings: ClientSettings;
|
||||
@@ -83,7 +88,15 @@ function toPersistedSavedEnvironmentRecord(
|
||||
}
|
||||
|
||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
|
||||
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
|
||||
|
||||
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
|
||||
describe("showDesktopConfirmDialog", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
} from "./desktopSettings.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
|
||||
+95
-99
@@ -36,14 +36,14 @@ import { autoUpdater } from "electron-updater";
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings";
|
||||
} from "./desktopSettings.ts";
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
@@ -52,14 +52,15 @@ import {
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
} from "./clientPersistence";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
} from "./clientPersistence.ts";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure.ts";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -71,9 +72,10 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
import { resolveDesktopAppBranding } from "./appBranding";
|
||||
} from "./updateMachine.ts";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
import { bindFirstRevealTrigger, type RevealSubscription } from "./windowReveal.ts";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
@@ -160,6 +162,35 @@ const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linu
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
const normalizedItems: ContextMenuItem[] = [];
|
||||
|
||||
for (const sourceItem of source) {
|
||||
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedItem: ContextMenuItem = {
|
||||
id: sourceItem.id,
|
||||
label: sourceItem.label,
|
||||
destructive: sourceItem.destructive === true,
|
||||
disabled: sourceItem.disabled === true,
|
||||
};
|
||||
|
||||
if (sourceItem.children) {
|
||||
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
|
||||
if (normalizedChildren.length === 0) {
|
||||
continue;
|
||||
}
|
||||
normalizedItem.children = normalizedChildren;
|
||||
}
|
||||
|
||||
normalizedItems.push(normalizedItem);
|
||||
}
|
||||
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
@@ -430,51 +461,13 @@ function cancelBackendReadinessWait(): void {
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
return await waitForBackendStartupReady({
|
||||
listeningPromise: backendListeningDetector?.promise ?? null,
|
||||
waitForHttpReady: () =>
|
||||
waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
}),
|
||||
cancelHttpWait: cancelBackendReadinessWait,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1715,14 +1708,7 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
|
||||
const normalizedItems = items
|
||||
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
const normalizedItems = normalizeContextMenuItems(items);
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -1743,28 +1729,37 @@ function registerIpcHandlers(): void {
|
||||
if (!window) return null;
|
||||
|
||||
return new Promise<string | null>((resolve) => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of normalizedItems) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
): MenuItemConstructorOptions[] => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children);
|
||||
} else {
|
||||
itemOption.click = () => resolve(item.id);
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
}
|
||||
}
|
||||
template.push(itemOption);
|
||||
}
|
||||
template.push(itemOption);
|
||||
}
|
||||
return template;
|
||||
};
|
||||
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
|
||||
menu.popup({
|
||||
window,
|
||||
...popupPosition,
|
||||
@@ -1936,7 +1931,7 @@ function createWindow(): BrowserWindow {
|
||||
title: APP_DISPLAY_NAME,
|
||||
...getWindowTitleBarOptions(),
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
preload: Path.join(__dirname, "preload.cjs"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -2004,16 +1999,17 @@ function createWindow(): BrowserWindow {
|
||||
emitUpdateState();
|
||||
});
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
// On Linux/Wayland with `show: false`, Electron's `ready-to-show` only
|
||||
// fires after `show()` is called, deadlocking the standard "wait for
|
||||
// ready, then show" pattern. Add `did-finish-load` as a Linux-only
|
||||
// fallback so the window still surfaces once the renderer has loaded
|
||||
// the page. Other platforms keep the no-flash `ready-to-show` path,
|
||||
// since `did-finish-load` typically fires before the first paint there.
|
||||
const revealSubscribers: RevealSubscription[] = [(fire) => window.once("ready-to-show", fire)];
|
||||
if (process.platform === "linux") {
|
||||
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
|
||||
}
|
||||
bindFirstRevealTrigger(revealSubscribers, () => revealWindow(window));
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
@@ -2088,9 +2084,9 @@ async function bootstrap(): Promise<void> {
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
void waitForBackendHttpReady(backendHttpUrl)
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
void waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
|
||||
describe("resolveDesktopRuntimeInfo", () => {
|
||||
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
|
||||
describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
@@ -148,7 +148,7 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
it("does nothing on unsupported platforms", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
@@ -160,7 +160,7 @@ describe("syncShellEnvironment", () => {
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
platform: "freebsd",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
@@ -168,4 +168,122 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(() => ({
|
||||
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
|
||||
}));
|
||||
const isWindowsCommandAvailable = vi.fn(() => true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("loads the PowerShell profile on Windows when node is not available", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
|
||||
options?.loadProfile
|
||||
? {
|
||||
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
|
||||
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
|
||||
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
}
|
||||
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Profile\\Node",
|
||||
"C:\\Windows\\System32",
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
|
||||
expect(env.FNM_MULTISHELL_PATH).toBe(
|
||||
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
);
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
|
||||
{ loadProfile: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves baseline Windows env when the profile probe fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
|
||||
if (options?.loadProfile) {
|
||||
throw new Error("profile load failed");
|
||||
}
|
||||
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
|
||||
},
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn(() => false);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.SSH_AUTH_SOCK).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,18 @@ import {
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
resolveWindowsEnvironment,
|
||||
} from "@t3tools/shared/shell";
|
||||
import type {
|
||||
CommandAvailabilityOptions,
|
||||
ShellEnvironmentReader,
|
||||
WindowsShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
type WindowsCommandAvailabilityChecker = (
|
||||
command: string,
|
||||
options?: CommandAvailabilityOptions,
|
||||
) => boolean;
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
@@ -25,19 +35,39 @@ export function syncShellEnvironment(
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readWindowsEnvironment?: WindowsShellEnvironmentReader;
|
||||
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
|
||||
try {
|
||||
if (platform === "win32") {
|
||||
const repairedEnvironment = resolveWindowsEnvironment(env, {
|
||||
...(options.readWindowsEnvironment
|
||||
? { readEnvironment: options.readWindowsEnvironment }
|
||||
: {}),
|
||||
...(options.isWindowsCommandAvailable
|
||||
? { commandAvailable: options.isWindowsCommandAvailable }
|
||||
: {}),
|
||||
});
|
||||
for (const [key, value] of Object.entries(repairedEnvironment)) {
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
doesVersionMatchDesktopUpdateChannel,
|
||||
isNightlyDesktopVersion,
|
||||
resolveDefaultDesktopUpdateChannel,
|
||||
} from "./updateChannels";
|
||||
} from "./updateChannels.ts";
|
||||
|
||||
describe("isNightlyDesktopVersion", () => {
|
||||
it("detects packaged nightly versions", () => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
} from "./updateMachine.ts";
|
||||
|
||||
const runtimeInfo = {
|
||||
hostArch: "x64",
|
||||
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
|
||||
|
||||
export function createInitialDesktopUpdateState(
|
||||
currentVersion: string,
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
} from "./updateState.ts";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { bindFirstRevealTrigger } from "./windowReveal.ts";
|
||||
|
||||
describe("bindFirstRevealTrigger", () => {
|
||||
it("reveals when the first trigger fires", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("only reveals once when multiple triggers fire", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("subscribers using `once` ignore re-emitted events after reveal", () => {
|
||||
const window = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
export type RevealSubscription = (listener: () => void) => void;
|
||||
|
||||
/**
|
||||
* Wire a reveal callback to fire exactly once, on whichever of the provided
|
||||
* event subscribers fires first. Each subscriber is responsible for binding
|
||||
* its own event source.
|
||||
*
|
||||
* Used by the desktop main window's first-paint reveal logic. The standard
|
||||
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
|
||||
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
|
||||
* `show()` is called, deadlocking that pattern. Subscribing to both
|
||||
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
|
||||
* signal) lets the window surface reliably across platforms.
|
||||
*/
|
||||
export function bindFirstRevealTrigger(
|
||||
subscribers: readonly RevealSubscription[],
|
||||
reveal: () => void,
|
||||
): void {
|
||||
let revealed = false;
|
||||
const fire = () => {
|
||||
if (revealed) return;
|
||||
revealed = true;
|
||||
reveal();
|
||||
};
|
||||
for (const subscribe of subscribers) {
|
||||
subscribe(fire);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ES2023", "DOM", "esnext.disposable"]
|
||||
"lib": ["ESNext", "DOM", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
root = false
|
||||
|
||||
[*.{kt,kts}]
|
||||
indent_size = 2
|
||||
ktlint_code_style = android_studio
|
||||
ktlint_standard_blank-line-between-when-conditions = disabled
|
||||
ktlint_standard_class-signature = disabled
|
||||
ktlint_standard_function-signature = disabled
|
||||
ktlint_standard_import-ordering = disabled
|
||||
ktlint_standard_multiline-expression-wrapping = disabled
|
||||
ktlint_standard_trailing-comma-on-call-site = disabled
|
||||
ktlint_standard_when-entry-bracing = disabled
|
||||
@@ -0,0 +1,58 @@
|
||||
included:
|
||||
- ios/T3Code
|
||||
- modules/t3-terminal/ios
|
||||
- modules/t3-review-diff/ios
|
||||
|
||||
excluded:
|
||||
- ios/Pods
|
||||
- ios/build
|
||||
- modules/t3-terminal/Vendor
|
||||
|
||||
reporter: xcode
|
||||
|
||||
disabled_rules:
|
||||
- file_length
|
||||
- function_body_length
|
||||
- identifier_name
|
||||
- line_length
|
||||
- lower_acl_than_parent
|
||||
- modifier_order
|
||||
- trailing_comma
|
||||
- type_body_length
|
||||
|
||||
opt_in_rules:
|
||||
- array_init
|
||||
- closure_end_indentation
|
||||
- closure_spacing
|
||||
- collection_alignment
|
||||
- contains_over_filter_count
|
||||
- contains_over_filter_is_empty
|
||||
- contains_over_first_not_nil
|
||||
- contains_over_range_nil_comparison
|
||||
- empty_collection_literal
|
||||
- empty_count
|
||||
- empty_string
|
||||
- enum_case_associated_values_count
|
||||
- fallthrough
|
||||
- fatal_error_message
|
||||
- first_where
|
||||
- flatmap_over_map_reduce
|
||||
- force_unwrapping
|
||||
- implicitly_unwrapped_optional
|
||||
- last_where
|
||||
- legacy_multiple
|
||||
- legacy_random
|
||||
- operator_usage_whitespace
|
||||
- overridden_super_call
|
||||
- prefer_self_type_over_type_of_self
|
||||
- private_action
|
||||
- private_outlet
|
||||
- prohibited_super_call
|
||||
- reduce_into
|
||||
- redundant_nil_coalescing
|
||||
- sorted_first_last
|
||||
- static_operator
|
||||
- toggle_bool
|
||||
- unneeded_parentheses_in_closure_argument
|
||||
- vertical_parameter_alignment_on_call
|
||||
- yoda_condition
|
||||
@@ -0,0 +1,3 @@
|
||||
brew "swiftlint"
|
||||
brew "ktlint"
|
||||
brew "detekt"
|
||||
@@ -51,6 +51,14 @@ bun run config:dev
|
||||
bun run config:preview
|
||||
```
|
||||
|
||||
Run static checks for mobile native code:
|
||||
|
||||
```bash
|
||||
node ../../scripts/mobile-native-static-check.ts
|
||||
```
|
||||
|
||||
The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin. Missing native tools are reported as warnings and skipped locally. CI installs the default toolset from `apps/mobile/Brewfile` before running the native checks.
|
||||
|
||||
## EAS Builds
|
||||
|
||||
Create a cloud dev-client build:
|
||||
|
||||
@@ -77,11 +77,9 @@ const config: ExpoConfig = {
|
||||
supportsTablet: true,
|
||||
bundleIdentifier: variant.iosBundleIdentifier,
|
||||
infoPlist: {
|
||||
...(APP_VARIANT !== "production" && {
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
},
|
||||
}),
|
||||
NSAppTransportSecurity: {
|
||||
NSAllowsArbitraryLoads: true,
|
||||
},
|
||||
ITSAppUsesNonExemptEncryption: false,
|
||||
},
|
||||
},
|
||||
@@ -130,7 +128,7 @@ const config: ExpoConfig = {
|
||||
],
|
||||
"expo-secure-store",
|
||||
"expo-router",
|
||||
...(APP_VARIANT !== "production" ? ["./plugins/withAndroidCleartextTraffic.cjs"] : []),
|
||||
"./plugins/withAndroidCleartextTraffic.cjs",
|
||||
],
|
||||
extra: {
|
||||
appVariant: APP_VARIANT,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
config:
|
||||
validation: true
|
||||
|
||||
build:
|
||||
maxIssues: 0
|
||||
|
||||
complexity:
|
||||
LongMethod:
|
||||
active: true
|
||||
threshold: 80
|
||||
TooManyFunctions:
|
||||
active: false
|
||||
|
||||
style:
|
||||
MagicNumber:
|
||||
active: false
|
||||
MaxLineLength:
|
||||
active: true
|
||||
maxLineLength: 120
|
||||
@@ -0,0 +1,80 @@
|
||||
# Review Screen Profiling
|
||||
|
||||
Use this when the mobile review screen is slow or crashes while opening large diffs.
|
||||
|
||||
## Preferred Capture: React Native DevTools Performance
|
||||
|
||||
This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.
|
||||
|
||||
1. Start the development client:
|
||||
|
||||
```sh
|
||||
cd apps/mobile
|
||||
bun dev:client
|
||||
```
|
||||
|
||||
2. Open the app in the iOS Simulator or on the device using the development client.
|
||||
|
||||
3. In the terminal running Expo, press `j` to open React Native DevTools.
|
||||
|
||||
4. In DevTools, open the `Performance` panel.
|
||||
|
||||
5. Start recording.
|
||||
|
||||
6. In the app, reproduce the slow path:
|
||||
- Navigate to the thread.
|
||||
- Open `Files Changed`.
|
||||
- Select the largest review source.
|
||||
- Expand a few large files or tap `Load diff`.
|
||||
- Scroll until the app is clearly slow or until just before it crashes.
|
||||
|
||||
7. Stop recording.
|
||||
|
||||
8. Export or save the Performance recording as a JSON trace.
|
||||
|
||||
Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.
|
||||
|
||||
## Android Fallback: Hermes Sampling Profile
|
||||
|
||||
Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.
|
||||
|
||||
1. Run Android dev client:
|
||||
|
||||
```sh
|
||||
cd apps/mobile
|
||||
bun android:dev
|
||||
bun dev:client
|
||||
```
|
||||
|
||||
2. Open the developer menu from the Expo terminal with `d`.
|
||||
|
||||
3. Select `Enable Sampling Profiler`.
|
||||
|
||||
4. Reproduce the review-screen slowdown.
|
||||
|
||||
5. Open the developer menu again with `d`.
|
||||
|
||||
6. Select `Disable Sampling Profiler`.
|
||||
|
||||
7. Pull and convert the Hermes profile:
|
||||
|
||||
```sh
|
||||
cd apps/mobile
|
||||
mkdir -p profiles/review
|
||||
bunx react-native profile-hermes profiles/review
|
||||
```
|
||||
|
||||
8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.
|
||||
|
||||
For the development app variant, the Android package is `com.t3tools.t3code.dev`.
|
||||
|
||||
## What To Capture
|
||||
|
||||
For the first trace, do not optimize the repro. We want the slowest realistic case:
|
||||
|
||||
- A diff with many files and large line counts.
|
||||
- At least one `Load diff` action for a suppressed large diff.
|
||||
- One vertical scroll pass after the content appears.
|
||||
- One horizontal scroll of a long file, if that is part of the slowdown.
|
||||
|
||||
If the app crashes, note the last visible action before the crash and attach device logs if available.
|
||||
@@ -0,0 +1,19 @@
|
||||
require 'json'
|
||||
|
||||
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
|
||||
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'T3ReviewDiffNative'
|
||||
s.version = package['version']
|
||||
s.summary = 'Native review diff debug surface for T3 Code mobile.'
|
||||
s.description = 'Native iOS review diff renderer used to prototype fast mobile review scrolling.'
|
||||
s.homepage = 'https://t3tools.com'
|
||||
s.license = { :type => 'UNLICENSED' }
|
||||
s.author = { 'T3 Tools' => '[email protected]' }
|
||||
s.platforms = { :ios => '16.1' }
|
||||
s.source = { :path => '.' }
|
||||
s.source_files = 'ios/**/*.{h,m,mm,swift}'
|
||||
s.frameworks = 'CoreGraphics', 'UIKit'
|
||||
s.swift_version = '5.9'
|
||||
s.dependency 'ExpoModulesCore'
|
||||
end
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"platforms": ["apple"],
|
||||
"apple": {
|
||||
"modules": ["T3ReviewDiffModule"],
|
||||
"podspecPath": "T3ReviewDiffNative.podspec"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import ExpoModulesCore
|
||||
|
||||
public class T3ReviewDiffModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("T3ReviewDiffSurface")
|
||||
|
||||
View(T3ReviewDiffView.self) {
|
||||
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
|
||||
view.setRowsJson(rowsJson)
|
||||
}
|
||||
|
||||
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
|
||||
view.setTokensJson(tokensJson)
|
||||
}
|
||||
|
||||
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
|
||||
view.setTokensPatchJson(tokensPatchJson)
|
||||
}
|
||||
|
||||
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
|
||||
view.setTokensResetKey(tokensResetKey)
|
||||
}
|
||||
|
||||
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
|
||||
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
|
||||
}
|
||||
|
||||
Prop("viewedFileIdsJson") { (view: T3ReviewDiffView, viewedFileIdsJson: String) in
|
||||
view.setViewedFileIdsJson(viewedFileIdsJson)
|
||||
}
|
||||
|
||||
Prop("appearanceScheme") { (view: T3ReviewDiffView, appearanceScheme: String) in
|
||||
view.setAppearanceScheme(appearanceScheme)
|
||||
}
|
||||
|
||||
Prop("themeJson") { (view: T3ReviewDiffView, themeJson: String) in
|
||||
view.setThemeJson(themeJson)
|
||||
}
|
||||
|
||||
Prop("styleJson") { (view: T3ReviewDiffView, styleJson: String) in
|
||||
view.setStyleJson(styleJson)
|
||||
}
|
||||
|
||||
Prop("rowHeight") { (view: T3ReviewDiffView, rowHeight: Double) in
|
||||
view.setRowHeight(CGFloat(rowHeight))
|
||||
}
|
||||
|
||||
Prop("contentWidth") { (view: T3ReviewDiffView, contentWidth: Double) in
|
||||
view.setContentWidth(CGFloat(contentWidth))
|
||||
}
|
||||
|
||||
Events("onDebug", "onToggleFile", "onToggleViewedFile")
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@t3tools/mobile-review-diff-native",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"expo-module": {
|
||||
"ios": {
|
||||
"modules": [
|
||||
"T3ReviewDiffModule"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -47,10 +47,11 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
|
||||
}
|
||||
}
|
||||
|
||||
var fontSize: Float = 12f
|
||||
var fontSize: Float = 10f
|
||||
set(value) {
|
||||
field = value
|
||||
textView.textSize = value
|
||||
inputView.textSize = max(value, 13f)
|
||||
emitResize()
|
||||
}
|
||||
|
||||
|
||||
@@ -100,23 +100,26 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
var fontSize: CGFloat = 12 {
|
||||
var fontSize: CGFloat = 10 {
|
||||
didSet {
|
||||
guard oldValue != fontSize else { return }
|
||||
inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular)
|
||||
resetSurface()
|
||||
refreshSurface()
|
||||
}
|
||||
}
|
||||
|
||||
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
|
||||
didSet {
|
||||
guard oldValue != appearanceScheme else { return }
|
||||
appearance = TerminalAppearanceScheme(value: appearanceScheme)
|
||||
updateGhosttyTheme()
|
||||
refreshSurface()
|
||||
}
|
||||
}
|
||||
|
||||
var themeConfig: String = "" {
|
||||
didSet {
|
||||
updateGhosttyTheme()
|
||||
guard oldValue != themeConfig else { return }
|
||||
refreshSurface()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,6 +356,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
private func refreshSurface() {
|
||||
resetSurface()
|
||||
createSurfaceIfPossible()
|
||||
}
|
||||
|
||||
private func destroySurface() {
|
||||
if let surface {
|
||||
ghostty_surface_set_write_callback(surface, nil, nil)
|
||||
@@ -525,19 +533,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
terminalViewport.backgroundColor = backgroundColorValue
|
||||
}
|
||||
|
||||
private func updateGhosttyTheme() {
|
||||
guard let app, let surface else { return }
|
||||
guard let config = ghostty_config_new() else { return }
|
||||
loadThemeConfig(into: config)
|
||||
ghostty_config_finalize(config)
|
||||
ghostty_app_update_config(app, config)
|
||||
ghostty_surface_update_config(surface, config)
|
||||
ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme)
|
||||
ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme)
|
||||
ghostty_config_free(config)
|
||||
redrawSurface()
|
||||
}
|
||||
|
||||
private func loadThemeConfig(into config: ghostty_config_t) {
|
||||
guard let path = writeThemeConfigFile() else { return }
|
||||
path.withCString { cString in
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
"config:dev": "APP_VARIANT=development expo config",
|
||||
"config:preview": "APP_VARIANT=preview expo config",
|
||||
"config:prod": "APP_VARIANT=production expo config",
|
||||
"profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
@@ -46,6 +47,7 @@
|
||||
"@shikijs/themes": "3.23.0",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/mobile-review-diff-native": "file:./modules/t3-review-diff",
|
||||
"@t3tools/mobile-terminal-native": "file:./modules/t3-terminal",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"clsx": "^2.1.1",
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
import Stack from "expo-router/stack";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
type LayoutChangeEvent,
|
||||
StyleSheet,
|
||||
Text as NativeText,
|
||||
type NativeSyntheticEvent,
|
||||
useColorScheme,
|
||||
View,
|
||||
} from "react-native";
|
||||
import {
|
||||
debugReviewDiffFixtures,
|
||||
type DebugReviewDiffFixtureId,
|
||||
} from "../../features/debug/fixtures/reviewDiffFixtures";
|
||||
import {
|
||||
getResolvedNativeReviewDiffModuleName,
|
||||
type NativeReviewDiffStyle,
|
||||
type NativeReviewDiffTheme,
|
||||
resolveNativeReviewDiffView,
|
||||
} from "../../features/debug/native-review-diff/nativeReviewDiffModule";
|
||||
import {
|
||||
highlightNativeReviewDiffVisibleRows,
|
||||
streamNativeReviewDiffTokens,
|
||||
type NativeReviewDiffHighlightEngine,
|
||||
} from "../../features/debug/native-review-diff/nativeReviewDiffHighlighter";
|
||||
import {
|
||||
getNativeReviewDiffFixture,
|
||||
parseNativeReviewDiffFixture,
|
||||
} from "../../features/debug/native-review-diff/nativeReviewDiffParser";
|
||||
import {
|
||||
getPierreTerminalTheme,
|
||||
type TerminalAppearanceScheme,
|
||||
} from "../../features/terminal/terminalTheme";
|
||||
|
||||
const NATIVE_DEBUG_ROW_HEIGHT = 20;
|
||||
const NATIVE_DEBUG_CONTENT_WIDTH = 2800;
|
||||
const NATIVE_DEBUG_STYLE = {
|
||||
rowHeight: NATIVE_DEBUG_ROW_HEIGHT,
|
||||
contentWidth: NATIVE_DEBUG_CONTENT_WIDTH,
|
||||
changeBarWidth: 4,
|
||||
gutterWidth: 46,
|
||||
codePadding: 7,
|
||||
textVerticalInset: 2,
|
||||
fileHeaderHeight: 56,
|
||||
fileHeaderHorizontalMargin: 8,
|
||||
fileHeaderVerticalMargin: 6,
|
||||
fileHeaderCornerRadius: 10,
|
||||
fileHeaderHorizontalPadding: 10,
|
||||
fileHeaderPathRightPadding: 118,
|
||||
fileHeaderCountColumnWidth: 38,
|
||||
fileHeaderCountGap: 5,
|
||||
codeFontSize: 11,
|
||||
codeFontWeight: "regular",
|
||||
lineNumberFontSize: 10,
|
||||
lineNumberFontWeight: "regular",
|
||||
hunkFontSize: 11,
|
||||
hunkFontWeight: "medium",
|
||||
fileHeaderFontSize: 11,
|
||||
fileHeaderFontWeight: "semibold",
|
||||
fileHeaderMetaFontSize: 10,
|
||||
fileHeaderMetaFontWeight: "semibold",
|
||||
fileHeaderSubtextFontSize: 11,
|
||||
fileHeaderSubtextFontWeight: "medium",
|
||||
emptyStateFontSize: 12,
|
||||
emptyStateFontWeight: "medium",
|
||||
} satisfies NativeReviewDiffStyle;
|
||||
|
||||
function createNativeReviewDiffTheme(scheme: TerminalAppearanceScheme): NativeReviewDiffTheme {
|
||||
const terminalTheme = getPierreTerminalTheme(scheme);
|
||||
const [, terminalRed, , , terminalBlue] = terminalTheme.palette;
|
||||
|
||||
if (scheme === "dark") {
|
||||
return {
|
||||
background: terminalTheme.background,
|
||||
text: terminalTheme.foreground,
|
||||
mutedText: terminalTheme.mutedForeground,
|
||||
headerBackground: terminalTheme.background,
|
||||
border: terminalTheme.border,
|
||||
hunkBackground: "#071f28",
|
||||
hunkText: terminalBlue ?? "#009fff",
|
||||
addBackground: "#0d2f28",
|
||||
deleteBackground: "#391415",
|
||||
addBar: "#00cab1",
|
||||
deleteBar: terminalRed ?? "#ff2e3f",
|
||||
addText: "#5ECC71",
|
||||
deleteText: "#FF6762",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
background: "#ffffff",
|
||||
text: "#070707",
|
||||
mutedText: terminalTheme.mutedForeground,
|
||||
headerBackground: "#ffffff",
|
||||
border: terminalTheme.border,
|
||||
hunkBackground: "#e0f2ff",
|
||||
hunkText: terminalBlue ?? "#009fff",
|
||||
addBackground: "#e5f8f5",
|
||||
deleteBackground: "#ffe6e7",
|
||||
addBar: "#00cab1",
|
||||
deleteBar: terminalRed ?? "#ff2e3f",
|
||||
addText: "#199F43",
|
||||
deleteText: "#D52C36",
|
||||
};
|
||||
}
|
||||
|
||||
export default function NativeReviewDiffDebugRoute() {
|
||||
const colorScheme = useColorScheme() === "dark" ? "dark" : "light";
|
||||
const [fixtureId, setFixtureId] = useState<DebugReviewDiffFixtureId>("large");
|
||||
const [highlightEngine, setHighlightEngine] = useState<NativeReviewDiffHighlightEngine>("native");
|
||||
const [collapsedFileIds, setCollapsedFileIds] = useState<ReadonlyArray<string>>([]);
|
||||
const [viewedFileIds, setViewedFileIds] = useState<ReadonlyArray<string>>([]);
|
||||
const fixture = getNativeReviewDiffFixture(fixtureId);
|
||||
const parsed = useMemo(() => parseNativeReviewDiffFixture(fixture), [fixture]);
|
||||
const effectiveHighlightEngine: NativeReviewDiffHighlightEngine =
|
||||
fixtureId === "xl" && highlightEngine === "native" ? "javascript" : highlightEngine;
|
||||
const useVisibleOnlyHighlighting = fixtureId === "xl";
|
||||
const debugTheme = useMemo(() => createNativeReviewDiffTheme(colorScheme), [colorScheme]);
|
||||
const rowsJson = useMemo(() => JSON.stringify(parsed.rows), [parsed.rows]);
|
||||
const collapsedFileIdsJson = useMemo(() => JSON.stringify(collapsedFileIds), [collapsedFileIds]);
|
||||
const viewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
|
||||
const themeJson = useMemo(() => JSON.stringify(debugTheme), [debugTheme]);
|
||||
const styleJson = useMemo(() => JSON.stringify(NATIVE_DEBUG_STYLE), []);
|
||||
const tokensResetKey = `${fixtureId}:${colorScheme}:${effectiveHighlightEngine}`;
|
||||
const [tokensPatchJson, setTokensPatchJson] = useState(
|
||||
JSON.stringify({ resetKey: "", tokensByRowId: {} }),
|
||||
);
|
||||
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
|
||||
const visibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 });
|
||||
const visibleChunkIndexRef = useRef(0);
|
||||
const useVisibleOnlyHighlightingRef = useRef(useVisibleOnlyHighlighting);
|
||||
const [visibleHighlightRequest, setVisibleHighlightRequest] = useState(0);
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView();
|
||||
const handleSelectFixture = useCallback((nextFixtureId: DebugReviewDiffFixtureId) => {
|
||||
setFixtureId(nextFixtureId);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
useVisibleOnlyHighlightingRef.current = useVisibleOnlyHighlighting;
|
||||
}, [useVisibleOnlyHighlighting]);
|
||||
useEffect(() => {
|
||||
setCollapsedFileIds([]);
|
||||
setViewedFileIds([]);
|
||||
}, [fixtureId]);
|
||||
useEffect(() => {
|
||||
const abortController = new AbortController();
|
||||
highlightedRowIdsRef.current = new Set();
|
||||
visibleChunkIndexRef.current = 0;
|
||||
setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, tokensByRowId: {} }));
|
||||
if (useVisibleOnlyHighlighting) {
|
||||
setVisibleHighlightRequest((request) => request + 1);
|
||||
console.log("[debug-native-diff] visible-only highlight start", {
|
||||
fixture: fixtureId,
|
||||
files: parsed.files.length,
|
||||
rows: parsed.rows.length,
|
||||
scheme: colorScheme,
|
||||
effectiveEngine: effectiveHighlightEngine,
|
||||
requestedEngine: highlightEngine,
|
||||
});
|
||||
return () => abortController.abort();
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
const startedAt = performance.now();
|
||||
console.log("[debug-native-diff] highlight start", {
|
||||
fixture: fixtureId,
|
||||
files: parsed.files.length,
|
||||
rows: parsed.rows.length,
|
||||
scheme: colorScheme,
|
||||
effectiveEngine: effectiveHighlightEngine,
|
||||
requestedEngine: highlightEngine,
|
||||
});
|
||||
|
||||
try {
|
||||
const engine = await streamNativeReviewDiffTokens({
|
||||
files: parsed.files,
|
||||
rows: parsed.rows,
|
||||
scheme: colorScheme,
|
||||
engine: effectiveHighlightEngine,
|
||||
signal: abortController.signal,
|
||||
onChunk: (chunk) => {
|
||||
if (abortController.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTokensPatchJson(JSON.stringify({ resetKey: tokensResetKey, ...chunk }));
|
||||
if (chunk.chunkIndex < 5 || chunk.chunkIndex % 10 === 0) {
|
||||
console.log("[debug-native-diff] highlight chunk", {
|
||||
chunkIndex: chunk.chunkIndex,
|
||||
durationMs: chunk.durationMs,
|
||||
filePath: chunk.filePath,
|
||||
lineCount: chunk.lineCount,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (!abortController.signal.aborted) {
|
||||
console.log("[debug-native-diff] highlight complete", {
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
engine,
|
||||
fixture: fixtureId,
|
||||
effectiveEngine: effectiveHighlightEngine,
|
||||
requestedEngine: highlightEngine,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
console.warn("[debug-native-diff] highlight failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [
|
||||
colorScheme,
|
||||
effectiveHighlightEngine,
|
||||
fixtureId,
|
||||
highlightEngine,
|
||||
parsed.files,
|
||||
parsed.rows,
|
||||
tokensResetKey,
|
||||
useVisibleOnlyHighlighting,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!useVisibleOnlyHighlighting) {
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
const requestRange = visibleRangeRef.current;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await highlightNativeReviewDiffVisibleRows({
|
||||
files: parsed.files,
|
||||
rows: parsed.rows,
|
||||
scheme: colorScheme,
|
||||
engine: effectiveHighlightEngine,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
alreadyHighlightedRowIds: highlightedRowIdsRef.current,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (abortController.signal.aborted || result.rowCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const rowId of Object.keys(result.tokensByRowId)) {
|
||||
highlightedRowIdsRef.current.add(rowId);
|
||||
}
|
||||
|
||||
const chunkIndex = visibleChunkIndexRef.current;
|
||||
visibleChunkIndexRef.current += 1;
|
||||
setTokensPatchJson(
|
||||
JSON.stringify({
|
||||
resetKey: tokensResetKey,
|
||||
chunkIndex,
|
||||
fileId: "visible",
|
||||
filePath: "visible rows",
|
||||
language: "diff",
|
||||
lineCount: result.rowCount,
|
||||
durationMs: result.durationMs,
|
||||
tokensByRowId: result.tokensByRowId,
|
||||
}),
|
||||
);
|
||||
if (chunkIndex < 2 || chunkIndex % 10 === 0) {
|
||||
console.log("[debug-native-diff] visible highlight chunk", {
|
||||
chunkIndex,
|
||||
durationMs: result.durationMs,
|
||||
highlightedRows: result.rowCount,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
console.warn("[debug-native-diff] visible highlight failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [
|
||||
colorScheme,
|
||||
effectiveHighlightEngine,
|
||||
parsed.files,
|
||||
parsed.rows,
|
||||
tokensResetKey,
|
||||
useVisibleOnlyHighlighting,
|
||||
visibleHighlightRequest,
|
||||
]);
|
||||
useEffect(() => {
|
||||
console.log("[debug-native-diff] native view availability", {
|
||||
available: NativeReviewDiffView != null,
|
||||
moduleName: getResolvedNativeReviewDiffModuleName(),
|
||||
rowsJsonLength: rowsJson.length,
|
||||
});
|
||||
}, [NativeReviewDiffView, rowsJson.length]);
|
||||
const handleNativeContainerLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { height, width } = event.nativeEvent.layout;
|
||||
console.log("[debug-native-diff] native container layout", {
|
||||
height: Math.round(height),
|
||||
width: Math.round(width),
|
||||
});
|
||||
}, []);
|
||||
const handleNativeLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const { height, width } = event.nativeEvent.layout;
|
||||
console.log("[debug-native-diff] native view layout", {
|
||||
height: Math.round(height),
|
||||
width: Math.round(width),
|
||||
});
|
||||
}, []);
|
||||
const handleNativeDebug = useCallback((event: NativeSyntheticEvent<Record<string, unknown>>) => {
|
||||
const payload = event.nativeEvent;
|
||||
const message = payload.message;
|
||||
|
||||
if (
|
||||
useVisibleOnlyHighlightingRef.current &&
|
||||
(message === "draw-metrics" || message === "visible-range") &&
|
||||
typeof payload.firstRowIndex === "number" &&
|
||||
typeof payload.lastRowIndex === "number"
|
||||
) {
|
||||
const previousRange = visibleRangeRef.current;
|
||||
const nextRange = {
|
||||
firstRowIndex: payload.firstRowIndex,
|
||||
lastRowIndex: payload.lastRowIndex,
|
||||
};
|
||||
const movedRows =
|
||||
Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
|
||||
Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
|
||||
|
||||
visibleRangeRef.current = nextRange;
|
||||
if (movedRows >= 20) {
|
||||
setVisibleHighlightRequest((request) => request + 1);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
const handleToggleFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
if (!fileId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setCollapsedFileIds((current) =>
|
||||
current.includes(fileId) ? current.filter((id) => id !== fileId) : [...current, fileId],
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleToggleViewedFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
if (!fileId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setViewedFileIds((current) => {
|
||||
if (current.includes(fileId)) {
|
||||
return current.filter((id) => id !== fileId);
|
||||
}
|
||||
|
||||
setCollapsedFileIds((collapsed) =>
|
||||
collapsed.includes(fileId) ? collapsed : [...collapsed, fileId],
|
||||
);
|
||||
return [...current, fileId];
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: debugTheme.background },
|
||||
headerTintColor: debugTheme.text,
|
||||
headerTitleAlign: "center",
|
||||
title: "",
|
||||
headerTitle: () => (
|
||||
<View style={{ alignItems: "center", maxWidth: 240 }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: debugTheme.text,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 13,
|
||||
lineHeight: 16,
|
||||
}}
|
||||
>
|
||||
Native review diff
|
||||
</NativeText>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: debugTheme.mutedText,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 11,
|
||||
lineHeight: 14,
|
||||
}}
|
||||
>
|
||||
{parsed.files.length} files · {parsed.rows.length} rows · +{parsed.additions} -
|
||||
{parsed.deletions} · {effectiveHighlightEngine === "native" ? "native" : "JS"}
|
||||
{fixtureId === "xl" && highlightEngine === "native" ? " fallback" : ""}
|
||||
</NativeText>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu
|
||||
icon="line.3.horizontal.decrease.circle"
|
||||
title="Diff debug options"
|
||||
separateBackground
|
||||
>
|
||||
<Stack.Toolbar.Menu icon="sparkles" inline title="Highlighter engine">
|
||||
<Stack.Toolbar.Label>Highlighter engine</Stack.Toolbar.Label>
|
||||
{(["native", "javascript"] as const).map((engine) => {
|
||||
const isSelected = engine === highlightEngine;
|
||||
return (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={engine}
|
||||
icon="circle"
|
||||
isOn={isSelected}
|
||||
onPress={() => setHighlightEngine(engine)}
|
||||
subtitle={
|
||||
engine === "native" && fixtureId === "xl"
|
||||
? "XL currently falls back after native engine crash"
|
||||
: engine === "native"
|
||||
? "react-native-shiki-engine"
|
||||
: "JavaScript regex engine"
|
||||
}
|
||||
>
|
||||
<Stack.Toolbar.Label>
|
||||
{engine === "native" ? "Native" : "JavaScript"}
|
||||
</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
);
|
||||
})}
|
||||
</Stack.Toolbar.Menu>
|
||||
|
||||
<Stack.Toolbar.Menu icon="doc.text" inline title="Fixture">
|
||||
<Stack.Toolbar.Label>Fixture</Stack.Toolbar.Label>
|
||||
{debugReviewDiffFixtures.map((candidate) => {
|
||||
const isSelected = candidate.id === fixtureId;
|
||||
return (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={candidate.id}
|
||||
icon="doc.text"
|
||||
isOn={isSelected}
|
||||
onPress={() => handleSelectFixture(candidate.id)}
|
||||
subtitle={`${candidate.lineCount} patch lines`}
|
||||
>
|
||||
<Stack.Toolbar.Label>{candidate.label}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
);
|
||||
})}
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View
|
||||
className="relative flex-1"
|
||||
style={{ backgroundColor: debugTheme.background }}
|
||||
collapsable={false}
|
||||
onLayout={handleNativeContainerLayout}
|
||||
>
|
||||
{NativeReviewDiffView ? (
|
||||
<NativeReviewDiffView
|
||||
key={fixtureId}
|
||||
collapsable={false}
|
||||
testID="native-review-diff-view"
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={colorScheme}
|
||||
contentWidth={NATIVE_DEBUG_CONTENT_WIDTH}
|
||||
collapsedFileIdsJson={collapsedFileIdsJson}
|
||||
rowHeight={NATIVE_DEBUG_ROW_HEIGHT}
|
||||
rowsJson={rowsJson}
|
||||
styleJson={styleJson}
|
||||
themeJson={themeJson}
|
||||
tokensResetKey={tokensResetKey}
|
||||
tokensPatchJson={tokensPatchJson}
|
||||
viewedFileIdsJson={viewedFileIdsJson}
|
||||
onDebug={handleNativeDebug}
|
||||
onLayout={handleNativeLayout}
|
||||
onToggleFile={handleToggleFile}
|
||||
onToggleViewedFile={handleToggleViewedFile}
|
||||
/>
|
||||
) : (
|
||||
<View className="flex-1 items-center justify-center px-8">
|
||||
<NativeText
|
||||
style={{
|
||||
color: debugTheme.text,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 14,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Native review diff view is not available in this build.
|
||||
</NativeText>
|
||||
<NativeText
|
||||
style={{
|
||||
color: debugTheme.mutedText,
|
||||
fontFamily: "DMSans_400Regular",
|
||||
fontSize: 12,
|
||||
marginTop: 8,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
Expected native view manager: T3ReviewDiffSurface. Rebuild the current iOS development
|
||||
client with `bun ios` after native module changes.
|
||||
</NativeText>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,36 +1,23 @@
|
||||
import { Stack, useRouter } from "expo-router";
|
||||
import { useState } from "react";
|
||||
import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
|
||||
import { buildThreadRoutePath } from "../lib/routes";
|
||||
import { ConnectionStatusDot } from "../features/connection/ConnectionStatusDot";
|
||||
import { useRemoteCatalog } from "../state/use-remote-catalog";
|
||||
import { useRemoteEnvironmentState } from "../state/use-remote-environment-registry";
|
||||
import { HomeScreen } from "../features/home/HomeScreen";
|
||||
import { EnvironmentConnectionState } from "@t3tools/client-runtime";
|
||||
|
||||
/* ─── Connection pill label ──────────────────────────────────────────── */
|
||||
|
||||
const CONNECTION_LABEL: Record<EnvironmentConnectionState, string> = {
|
||||
ready: "Connected",
|
||||
connecting: "Connecting",
|
||||
reconnecting: "Reconnecting",
|
||||
disconnected: "Offline",
|
||||
idle: "No backends",
|
||||
};
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
export default function HomeRouteScreen() {
|
||||
const { connectionState, hasRemoteActivity, projects, threads } = useRemoteCatalog();
|
||||
const { projects, threads } = useRemoteCatalog();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const router = useRouter();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
const isDark = useColorScheme() === "dark";
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
const secondaryFg = isDark ? "#a3a3a3" : "#525252";
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -42,30 +29,6 @@ export default function HomeRouteScreen() {
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
onPress={() => router.push("/connections")}
|
||||
hitSlop={8}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
}}
|
||||
>
|
||||
<ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
color: secondaryFg,
|
||||
}}
|
||||
>
|
||||
{CONNECTION_LABEL[connectionState]}
|
||||
</RNText>
|
||||
</Pressable>
|
||||
),
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
onChangeText: (event) => {
|
||||
@@ -114,6 +77,19 @@ export default function HomeRouteScreen() {
|
||||
</Stack.Toolbar.View>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Button
|
||||
icon="ladybug"
|
||||
onPress={() => router.push("/debug/native-review-diff")}
|
||||
separateBackground
|
||||
/>
|
||||
<Stack.Toolbar.Button
|
||||
icon="network"
|
||||
onPress={() => router.push("/connections")}
|
||||
separateBackground
|
||||
/>
|
||||
</Stack.Toolbar>
|
||||
|
||||
{/* Bottom toolbar: search + compose, visually split like iMessage */}
|
||||
<Stack.Toolbar placement="bottom">
|
||||
<Stack.Toolbar.SearchBarSlot />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReviewCommentComposerSheet } from "../../../../features/threads/review/ReviewCommentComposerSheet";
|
||||
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
|
||||
|
||||
export default function ReviewCommentRoute() {
|
||||
return <ReviewCommentComposerSheet />;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ReviewSheet } from "../../../../features/threads/review/ReviewSheet";
|
||||
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
return <ReviewSheet />;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ThreadTerminalRouteScreen } from "../../../../features/threads/ThreadTerminalRouteScreen";
|
||||
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
|
||||
|
||||
export default function ThreadTerminalRoute() {
|
||||
return <ThreadTerminalRouteScreen />;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";
|
||||
@@ -12,10 +13,10 @@ export function ConnectionEnvironmentRow(props: {
|
||||
readonly environment: ConnectedEnvironmentSummary;
|
||||
readonly expanded: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly onReconnect: (environmentId: string) => void;
|
||||
readonly onRemove: (environmentId: string) => void;
|
||||
readonly onReconnect: (environmentId: EnvironmentId) => void;
|
||||
readonly onRemove: (environmentId: EnvironmentId) => void;
|
||||
readonly onUpdate: (
|
||||
environmentId: string,
|
||||
environmentId: EnvironmentId,
|
||||
updates: { readonly label: string; readonly displayUrl: string },
|
||||
) => void;
|
||||
}) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Debug Fixtures
|
||||
|
||||
These patch fixtures snapshot review-rendering worktree diffs used to develop
|
||||
the scratch review renderer. Keep them deterministic so the debug route can test
|
||||
parsing, chunked syntax highlighting, and virtualization without depending on
|
||||
the current repo state.
|
||||
|
||||
- `review-small.diff`: 155 lines, narrow model/rendering changes.
|
||||
- `review-medium.diff`: 1,955 lines, review screen and highlighter changes.
|
||||
- `review-large.diff`: 3,208 lines, broad current worktree snapshot excluding
|
||||
this fixture directory.
|
||||
- `current-working-review.diff`: alias of `review-large.diff` for quick loading
|
||||
while iterating.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
index d61924a62..3f2ae0160 100644
|
||||
--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
+export const REVIEW_DIFF_LINE_HEIGHT = 26;
|
||||
+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
|
||||
+
|
||||
export function renderVisibleWhitespace(value: string): string {
|
||||
const expandedTabs = value.replace(/\t/g, " ");
|
||||
return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
|
||||
@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
|
||||
export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
|
||||
if (props.change === "delete") {
|
||||
return (
|
||||
- <View className="w-[5px] self-stretch overflow-hidden">
|
||||
- <View className="flex-1 justify-between">
|
||||
- {Array.from({ length: 6 }, (_, index) => (
|
||||
- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />
|
||||
+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
+ <View>
|
||||
+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
|
||||
+ <View key={index}>
|
||||
+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
|
||||
+ <View style={{ height: 1 }} />
|
||||
+ </View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
|
||||
}
|
||||
|
||||
return (
|
||||
- <View className="w-[5px] self-stretch overflow-hidden">
|
||||
+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
|
||||
</View>
|
||||
);
|
||||
@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
|
||||
if (!props.tokens || props.tokens.length === 0) {
|
||||
return (
|
||||
<NativeText
|
||||
+ numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
+ numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
index a24a99ceb..69a6e7261 100644
|
||||
--- a/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
+++ b/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
|
||||
});
|
||||
});
|
||||
|
||||
- it("flattens expanded files into virtualizable review items", () => {
|
||||
+ it("flattens expanded file rows into virtualized review items", () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/a.ts",
|
||||
rows: [
|
||||
@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
|
||||
|
||||
expect(items).toEqual([
|
||||
expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
|
||||
- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
|
||||
- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
|
||||
+ expect.objectContaining({
|
||||
+ kind: "hunk",
|
||||
+ fileId: file.id,
|
||||
+ file,
|
||||
+ row: file.rows[0],
|
||||
+ }),
|
||||
+ expect.objectContaining({
|
||||
+ kind: "line",
|
||||
+ fileId: file.id,
|
||||
+ file,
|
||||
+ row: file.rows[1],
|
||||
+ lineIndex: 0,
|
||||
+ }),
|
||||
]);
|
||||
});
|
||||
|
||||
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
|
||||
index 27e6d7ae4..1cfbf358c 100644
|
||||
--- a/apps/mobile/src/features/review/reviewModel.ts
|
||||
+++ b/apps/mobile/src/features/review/reviewModel.ts
|
||||
@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
|
||||
readonly kind: "hunk";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
+ readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableHunkRow;
|
||||
}
|
||||
|
||||
@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
|
||||
readonly kind: "line";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
+ readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableLineRow;
|
||||
+ readonly lineIndex: number;
|
||||
}
|
||||
|
||||
export type ReviewListItem =
|
||||
@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
|
||||
}
|
||||
|
||||
// The flattened review list item model is inspired by pierre/diffs' iterator-first
|
||||
-// virtualization architecture, adapted here for React Native and LegendList.
|
||||
+// virtualization architecture, adapted here for React Native virtualization.
|
||||
// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
|
||||
// Reference files:
|
||||
// - src/utils/iterateOverDiff.ts
|
||||
@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
|
||||
}
|
||||
}
|
||||
|
||||
- file.rows.forEach((row) => {
|
||||
+ let lineIndex = 0;
|
||||
+ file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
items.push({
|
||||
kind: "hunk",
|
||||
- id: row.id,
|
||||
+ id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
+ file,
|
||||
row,
|
||||
});
|
||||
return;
|
||||
@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
|
||||
|
||||
items.push({
|
||||
kind: "line",
|
||||
- id: row.id,
|
||||
+ id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
+ file,
|
||||
row,
|
||||
+ lineIndex,
|
||||
});
|
||||
+ lineIndex += 1;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { DEBUG_REVIEW_XL_DIFF } from "./reviewDiffXlFixture";
|
||||
|
||||
export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "xl" | "current" | "states";
|
||||
|
||||
export interface DebugReviewDiffFixture {
|
||||
readonly id: DebugReviewDiffFixtureId;
|
||||
readonly label: string;
|
||||
readonly filename: string;
|
||||
readonly lineCount: number;
|
||||
readonly diff: string;
|
||||
}
|
||||
|
||||
const DEBUG_REVIEW_STATES_DIFF = `diff --git a/apps/demo/src/main.ts b/apps/demo/src/main.ts
|
||||
index 78f5eaa12..c2874ad31 100644
|
||||
--- a/apps/demo/src/main.ts
|
||||
+++ b/apps/demo/src/main.ts
|
||||
@@ -1,18 +1,24 @@
|
||||
import { createServer } from "./server";
|
||||
import { createLogger } from "./logger";
|
||||
|
||||
-const retryLimit = 2;
|
||||
-const greeting = "Hi You, {name}! Welcome to our application.";
|
||||
+const retryLimit = 4;
|
||||
+const greeting = "Hello There, {name}! Welcome to the updated application.";
|
||||
const logger = createLogger("demo");
|
||||
|
||||
export async function boot() {
|
||||
const server = createServer({
|
||||
- port: 3000,
|
||||
- timeoutMs: 1200,
|
||||
+ port: 3030,
|
||||
+ timeoutMs: 2500,
|
||||
retryLimit,
|
||||
});
|
||||
|
||||
- logger.info("starting server");
|
||||
+ logger.info("starting review fixture server");
|
||||
+ logger.debug({ retryLimit }, "configured retry policy");
|
||||
await server.start();
|
||||
- logger.info(greeting.replace("{name}", "reviewer"));
|
||||
+ logger.info(greeting.replace("{name}", "native reviewer"));
|
||||
+
|
||||
+ if (process.env.DEMO_FIXTURE_VERBOSE === "1") {
|
||||
+ logger.debug("verbose review fixture mode enabled");
|
||||
+ }
|
||||
}
|
||||
|
||||
void boot();
|
||||
diff --git a/apps/demo/src/utils/format.ts b/apps/demo/src/utils/stringFormat.ts
|
||||
similarity index 100%
|
||||
rename from apps/demo/src/utils/format.ts
|
||||
rename to apps/demo/src/utils/stringFormat.ts
|
||||
diff --git a/apps/demo/src/oldClient.ts b/apps/demo/src/apiClient.ts
|
||||
similarity index 62%
|
||||
rename from apps/demo/src/oldClient.ts
|
||||
rename to apps/demo/src/apiClient.ts
|
||||
index 18518fca1..87e0e2bea 100644
|
||||
--- a/apps/demo/src/oldClient.ts
|
||||
+++ b/apps/demo/src/apiClient.ts
|
||||
@@ -1,15 +1,22 @@
|
||||
-export interface ClientOptions {
|
||||
- readonly baseUrl: string;
|
||||
- readonly timeoutMs: number;
|
||||
-}
|
||||
-
|
||||
-export function request(path: string, options: ClientOptions) {
|
||||
- return fetch(options.baseUrl + path, {
|
||||
- signal: AbortSignal.timeout(options.timeoutMs),
|
||||
- });
|
||||
+export interface ApiClientOptions {
|
||||
+ readonly baseUrl: string;
|
||||
+ readonly token: string;
|
||||
+ readonly timeoutMs: number;
|
||||
+}
|
||||
+
|
||||
+export async function request(path: string, options: ApiClientOptions) {
|
||||
+ const response = await fetch(options.baseUrl + "/v2" + path, {
|
||||
+ headers: {
|
||||
+ Authorization: "Bearer " + options.token,
|
||||
+ "X-Client": "native-review-debug",
|
||||
+ },
|
||||
+ signal: AbortSignal.timeout(options.timeoutMs),
|
||||
+ });
|
||||
+
|
||||
+ if (!response.ok) {
|
||||
+ throw new Error("Request failed: " + response.status);
|
||||
+ }
|
||||
+
|
||||
+ return response.json();
|
||||
}
|
||||
-
|
||||
-export function requestJson(path: string, options: ClientOptions) {
|
||||
- return request(path, options).then((response) => response.json());
|
||||
-}
|
||||
diff --git a/apps/demo/src/features/flags.ts b/apps/demo/src/features/flags.ts
|
||||
new file mode 100644
|
||||
index 000000000..755df9762
|
||||
--- /dev/null
|
||||
+++ b/apps/demo/src/features/flags.ts
|
||||
@@ -0,0 +1,29 @@
|
||||
+export type FeatureState = "enabled" | "disabled" | "preview";
|
||||
+
|
||||
+export interface FeatureFlag {
|
||||
+ readonly key: string;
|
||||
+ readonly label: string;
|
||||
+ readonly state: FeatureState;
|
||||
+}
|
||||
+
|
||||
+export const reviewFixtureFlags: ReadonlyArray<FeatureFlag> = [
|
||||
+ {
|
||||
+ key: "native-file-headers",
|
||||
+ label: "Native file headers",
|
||||
+ state: "preview",
|
||||
+ },
|
||||
+ {
|
||||
+ key: "word-diff-highlights",
|
||||
+ label: "Word diff highlights",
|
||||
+ state: "enabled",
|
||||
+ },
|
||||
+ {
|
||||
+ key: "deleted-file-markers",
|
||||
+ label: "Deleted file markers",
|
||||
+ state: "enabled",
|
||||
+ },
|
||||
+];
|
||||
+
|
||||
+export function isEnabled(flag: FeatureFlag): boolean {
|
||||
+ return flag.state !== "disabled";
|
||||
+}
|
||||
diff --git a/apps/demo/src/legacyReview.ts b/apps/demo/src/legacyReview.ts
|
||||
deleted file mode 100644
|
||||
index 9cf2f63dc..000000000
|
||||
--- a/apps/demo/src/legacyReview.ts
|
||||
+++ /dev/null
|
||||
@@ -1,22 +0,0 @@
|
||||
-export const legacyReviewMode = true;
|
||||
-
|
||||
-export function createLegacyRows(lines: ReadonlyArray<string>) {
|
||||
- return lines.map((line, index) => ({
|
||||
- id: "legacy-" + index,
|
||||
- lineNumber: index + 1,
|
||||
- text: line,
|
||||
- }));
|
||||
-}
|
||||
-
|
||||
-export function renderLegacyHeader(path: string) {
|
||||
- return {
|
||||
- title: path,
|
||||
- subtitle: "legacy renderer",
|
||||
- icon: "blue-dot",
|
||||
- };
|
||||
-}
|
||||
-
|
||||
-export function shouldUseLegacyReview() {
|
||||
- return legacyReviewMode;
|
||||
-}
|
||||
diff --git a/apps/demo/src/wordChanges.zig b/apps/demo/src/wordChanges.zig
|
||||
index 6bfcc7e37..af359829c 100644
|
||||
--- a/apps/demo/src/wordChanges.zig
|
||||
+++ b/apps/demo/src/wordChanges.zig
|
||||
@@ -1,18 +1,23 @@
|
||||
const std = @import("std");
|
||||
-const Allocator = std.heap.page_allocator;
|
||||
+const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;
|
||||
const ArrayList = std.ArrayList;
|
||||
|
||||
pub fn main() !void {
|
||||
+ var gpa = GeneralPurposeAllocator(.{}){};
|
||||
+ defer _ = gpa.deinit();
|
||||
+ const allocator = gpa.allocator();
|
||||
+
|
||||
const stdout_writer_instance = std.io.getStdOut().writer();
|
||||
- try stdout_writer_instance.print("Hi You, {s}! Welcome to our application.", .{"Reviewer"});
|
||||
+ try stdout_writer_instance.print("Hello There, {s}! Welcome to the updated application.", .{"Reviewer"});
|
||||
|
||||
- var list = ArrayList(i32).init(Allocator);
|
||||
+ var list = ArrayList(i32).init(allocator);
|
||||
defer list.deinit();
|
||||
+ try list.append(42);
|
||||
|
||||
- const configuration_options = .{ .enable_logging = true, .max_buffer_size = 1024 };
|
||||
+ const configuration_options = .{ .enable_logging = true, .max_buffer_size = 2048 };
|
||||
_ = configuration_options;
|
||||
}
|
||||
diff --git a/apps/demo/assets/review-logo.png b/apps/demo/assets/review-logo.png
|
||||
new file mode 100644
|
||||
index 000000000..4628f44da
|
||||
--- /dev/null
|
||||
+++ b/apps/demo/assets/review-logo.png
|
||||
Binary files /dev/null and b/apps/demo/assets/review-logo.png differ
|
||||
diff --git a/apps/demo/scripts/review-fixture.sh b/apps/demo/scripts/review-fixture.sh
|
||||
old mode 100644
|
||||
new mode 100755`;
|
||||
|
||||
export const debugReviewDiffFixtures: ReadonlyArray<DebugReviewDiffFixture> = [
|
||||
{
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "review-states.diff",
|
||||
lineCount: DEBUG_REVIEW_STATES_DIFF.split("\n").length,
|
||||
diff: DEBUG_REVIEW_STATES_DIFF,
|
||||
},
|
||||
{
|
||||
id: "xl",
|
||||
label: "XL",
|
||||
filename: "08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch",
|
||||
lineCount: DEBUG_REVIEW_XL_DIFF.split("\n").length,
|
||||
diff: DEBUG_REVIEW_XL_DIFF,
|
||||
},
|
||||
{
|
||||
id: "small",
|
||||
label: "Small",
|
||||
filename: "review-small.diff",
|
||||
lineCount: 155,
|
||||
diff: 'diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n- <View className="flex-1 justify-between">\n- {Array.from({ length: 6 }, (_, index) => (\n- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n+ <View>\n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ <View key={index}>\n+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />\n+ <View style={{ height: 1 }} />\n+ </View>\n ))}\n </View>\n </View>\n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />\n </View>\n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n@@ -74,6 +81,7 @@ export function DiffTokenText(props: {\n \n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here f
Line truncated
|
||||
},
|
||||
{
|
||||
id: "medium",
|
||||
label: "Medium",
|
||||
filename: "review-medium.diff",
|
||||
lineCount: 1955,
|
||||
diff: 'diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set<string>();\n \n+function waitForReviewDelay(durationMs: number): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno\n }\n \n function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {\n- readonly rail: string;\n readonly dot: string;\n } {\n switch (changeType) {\n case "new":\n return {\n- rail: "bg-emerald-400",\n dot: "bg-emerald-400",\n };\n case "deleted":\n return {\n- rail: "bg-rose-400",\n dot: "bg-rose-400",\n };\n case "rename-pure":\n return {\n- rail: "bg-amber-400",\n dot: "bg-amber-400",\n };\n case "rename-changed":\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n default:\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n }\n@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {\n };\n }\n \n-function computeReviewListContentWidth(\Line truncated
|
||||
},
|
||||
{
|
||||
id: "large",
|
||||
label: "Large",
|
||||
filename: "review-large.diff",
|
||||
lineCount: 3208,
|
||||
diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "reactLine truncated
|
||||
},
|
||||
{
|
||||
id: "current",
|
||||
label: "Current Working",
|
||||
filename: "current-working-review.diff",
|
||||
lineCount: 3208,
|
||||
diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "reactLine truncated
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,4 @@
|
||||
// Generated from https://github.com/pingdotgg/t3code/commit/08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f.patch
|
||||
// Keep this split from reviewDiffFixtures.ts so the fixture registry stays readable.
|
||||
export const DEBUG_REVIEW_XL_DIFF =
|
||||
'From 08e6d4cfbfe55af83fe5fb6b9e75364f42f1f22f Mon Sep 17 00:00:00 2001\nFrom: Julius Marminge <julius0216@outlook.com>\nDate: Wed, 29 Apr 2026 16:13:55 -0700\nSubject: [PATCH] feat: Multi-Provider support (#2277)\n\nCo-authored-by: Claude Opus 4.7 <noreply@anthropic.com>\nCo-authored-by: codex <codex@users.noreply.github.com>\n---\n apps/desktop/src/clientPersistence.test.ts | 1 +\n .../OrchestrationEngineHarness.integration.ts | 44 +-\n .../TestProviderAdapter.integration.ts | 17 +-\n .../integration/fixtures/providerRuntime.ts | 4 +-\n .../orchestrationEngine.integration.test.ts | 178 +-\n .../providerService.integration.test.ts | 37 +-\n .../git/Layers/ClaudeTextGeneration.test.ts | 311 +--\n .../src/git/Layers/ClaudeTextGeneration.ts | 55 +-\n .../git/Layers/CodexTextGeneration.test.ts | 528 +++--\n .../src/git/Layers/CodexTextGeneration.ts | 97 +-\n .../git/Layers/CursorTextGeneration.test.ts | 311 ++-\n .../src/git/Layers/CursorTextGeneration.ts | 56 +-\n .../git/Layers/OpenCodeTextGeneration.test.ts | 354 ++--\n .../src/git/Layers/OpenCodeTextGeneration.ts | 77 +-\n .../src/git/Layers/RoutingTextGeneration.ts | 104 -\n .../src/git/Layers/TextGenerationLive.test.ts | 117 ++\n .../src/git/Layers/TextGenerationLive.ts | 101 +\n apps/server/src/observability/Metrics.test.ts | 10 +-\n .../Layers/CheckpointReactor.test.ts | 60 +-\n .../Layers/OrchestrationEngine.test.ts | 51 +-\n .../Layers/ProjectionPipeline.test.ts | 33 +-\n .../Layers/ProjectionPipeline.ts | 1 +\n .../Layers/ProjectionSnapshotQuery.test.ts | 18 +-\n .../Layers/ProjectionSnapshotQuery.ts | 6 +\n .../Layers/ProviderCommandReactor.test.ts | 438 +++-\n .../Layers/ProviderCommandReactor.ts | 183 +-\n .../Layers/ProviderRuntimeIngestion.test.ts | 229 ++-\n .../Layers/ProviderRuntimeIngestion.ts | 6 +\n .../orchestration/commandInvariants.test.ts | 13 +-\n .../src/orchestration/decider.delete.test.ts | 5 +-\n .../decider.projectScripts.test.ts | 11 +-\n .../src/orchestration/projector.test.ts | 21 +-\n .../Layers/ProjectionRepositories.test.ts | 14 +-\n .../Layers/ProjectionThreadSessions.ts | 4 +\n .../Layers/ProviderSessionRuntime.ts | 5 +\n apps/server/src/persistence/Migrations.ts | 4 +\n .../027_028_ProviderInstanceIdColumns.test.ts | 74 +\n .../027_ProviderSessionRuntimeInstanceId.ts | 38 +\n .../028_ProjectionThreadSessionInstanceId.ts | 21 +\n .../Services/ProjectionThreadSessions.ts | 2 +\n .../Services/ProviderSessionRuntime.ts | 9 +\n .../src/provider/Drivers/ClaudeDriver.ts | 157 ++\n .../src/provider/Drivers/ClaudeHome.test.ts | 52 +\n .../server/src/provider/Drivers/ClaudeHome.ts | 43 +\n .../src/provider/Drivers/CodexDriver.ts | 171 ++\n .../provider/Drivers/CodexHomeLayout.test.ts | 209 ++\n .../src/provider/Drivers/CodexHomeLayout.ts | 263 +++\n .../src/provider/Drivers/CursorDriver.ts | 148 ++\n .../src/provider/Drivers/OpenCodeDriver.ts | 135 ++\n apps/server/src/provider/Errors.ts | 41 +\n .../src/provider/Layers/ClaudeAdapter.test.ts | 339 ++--\n .../src/provider/Layers/ClaudeAdapter.ts | 63 +-\n .../src/provider/Layers/ClaudeProvider.ts | 484 ++---\n .../src/provider/Layers/CodexAdapter.test.ts | 186 +-\n .../src/provider/Layers/CodexAdapter.ts | 65 +-\n .../src/provider/Layers/CodexProvider.ts | 99 +-\n .../provider/Layers/CodexSessionRuntime.ts | 61 +-\n .../src/provider/Layers/CursorAdapter.test.ts | 213 +-\n .../src/provider/Layers/CursorAdapter.ts | 73 +-\n .../provider/Layers/CursorProvider.test.ts | 159 +-\n .../src/provider/Layers/CursorProvider.ts | 665 ++++---\n .../provider/Layers/OpenCodeAdapter.test.ts | 286 ++-\n .../src/provider/Layers/OpenCodeAdapter.ts | 1770 +++++++++--------\n .../provider/Layers/OpenCodeProvider.test.ts | 119 +-\n .../src/provider/Layers/OpenCodeProvider.ts | 378 ++--\n .../Layers/ProviderAdapterRegistry.test.ts | 148 +-\n .../Layers/ProviderAdapterRegistry.ts | 133 +-\n .../provider/Layers/ProviderEventLoggers.ts | 83 +\n .../ProviderInstanceRegistryHydration.ts | 176 ++\n .../ProviderInstanceRegistryLive.test.ts | 357 ++++\n .../Layers/ProviderInstanceRegistryLive.ts | 434 ++++\n .../provider/Layers/ProviderRegistry.test.ts | 850 ++++++--\n .../src/provider/Layers/ProviderRegistry.ts | 546 +++--\n .../provider/Layers/ProviderService.test.ts | 583 ++++--\n .../src/provider/Layers/ProviderService.ts | 418 +++-\n .../Layers/ProviderSessionDirectory.test.ts | 25 +-\n .../Layers/ProviderSessionDirectory.ts | 24 +-\n .../Layers/ProviderSessionReaper.test.ts | 31 +-\n .../Layers/scopedSafeTeardown.test.ts | 94 +\n .../src/provider/Layers/scopedSafeTeardoLine truncated
|
||||
@@ -0,0 +1,405 @@
|
||||
import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
|
||||
import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
|
||||
import bashLanguage from "@shikijs/langs/bash";
|
||||
import diffLanguage from "@shikijs/langs/diff";
|
||||
import javascriptLanguage from "@shikijs/langs/javascript";
|
||||
import jsonLanguage from "@shikijs/langs/json";
|
||||
import jsxLanguage from "@shikijs/langs/jsx";
|
||||
import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
|
||||
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffModule";
|
||||
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffParser";
|
||||
|
||||
export type NativeReviewDiffHighlightScheme = "light" | "dark";
|
||||
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
|
||||
|
||||
export interface NativeReviewDiffHighlighterHandle {
|
||||
readonly engine: NativeReviewDiffHighlightEngine;
|
||||
readonly tokenize: (
|
||||
code: string,
|
||||
options: { readonly lang: NativeReviewDiffLanguage; readonly theme: string },
|
||||
) => ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>>;
|
||||
}
|
||||
|
||||
interface NativeReviewDiffLineRow extends NativeReviewDiffRow {
|
||||
readonly kind: "line";
|
||||
readonly fileId: string;
|
||||
readonly content: string;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffTokenChunk {
|
||||
readonly chunkIndex: number;
|
||||
readonly fileId: string;
|
||||
readonly filePath: string;
|
||||
readonly language: NativeReviewDiffLanguage;
|
||||
readonly lineCount: number;
|
||||
readonly durationMs: number;
|
||||
readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
|
||||
}
|
||||
|
||||
export interface StreamNativeReviewDiffTokenInput {
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly scheme: NativeReviewDiffHighlightScheme;
|
||||
readonly engine?: NativeReviewDiffHighlightEngine;
|
||||
readonly chunkSize?: number;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly onChunk: (chunk: NativeReviewDiffTokenChunk) => void;
|
||||
}
|
||||
|
||||
export interface HighlightNativeReviewDiffVisibleRowsInput {
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly scheme: NativeReviewDiffHighlightScheme;
|
||||
readonly engine?: NativeReviewDiffHighlightEngine;
|
||||
readonly firstRowIndex: number;
|
||||
readonly lastRowIndex: number;
|
||||
readonly overscanRows?: number;
|
||||
readonly maxRows?: number;
|
||||
readonly alreadyHighlightedRowIds?: ReadonlySet<string>;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
const NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE = 500;
|
||||
const NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS = 160;
|
||||
const NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS = 360;
|
||||
|
||||
const NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME = {
|
||||
dark: "t3-pierre-dark",
|
||||
light: "t3-pierre-light",
|
||||
} as const;
|
||||
|
||||
const PIERRE_LIGHT_SHIKI_THEME = {
|
||||
name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.light,
|
||||
type: "light" as const,
|
||||
fg: "#070707",
|
||||
bg: "#ffffff",
|
||||
settings: [
|
||||
{ settings: { foreground: "#070707", background: "#ffffff" } },
|
||||
{ scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
|
||||
{
|
||||
scope: "keyword, storage, storage.type, keyword.operator.expression",
|
||||
settings: { foreground: "#FC2B73" },
|
||||
},
|
||||
{
|
||||
scope: "entity.name.function, support.function, meta.function-call",
|
||||
settings: { foreground: "#7B43F8" },
|
||||
},
|
||||
{
|
||||
scope: "entity.name.type, support.type, support.class",
|
||||
settings: { foreground: "#C635E4" },
|
||||
},
|
||||
{
|
||||
scope: "string, constant.character, punctuation.definition.string",
|
||||
settings: { foreground: "#199F43" },
|
||||
},
|
||||
{
|
||||
scope: "constant.numeric, constant.language, constant.other",
|
||||
settings: { foreground: "#1CA1C7" },
|
||||
},
|
||||
{
|
||||
scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
|
||||
settings: { foreground: "#D47628" },
|
||||
},
|
||||
{
|
||||
scope: "entity.name.tag, support.class.component",
|
||||
settings: { foreground: "#199F43" },
|
||||
},
|
||||
{
|
||||
scope: "punctuation, meta.brace, meta.delimiter",
|
||||
settings: { foreground: "#79797F" },
|
||||
},
|
||||
{ scope: "invalid", settings: { foreground: "#D52C36" } },
|
||||
],
|
||||
};
|
||||
|
||||
const PIERRE_DARK_SHIKI_THEME = {
|
||||
name: NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME.dark,
|
||||
type: "dark" as const,
|
||||
fg: "#adadb1",
|
||||
bg: "#0a0a0a",
|
||||
settings: [
|
||||
{ settings: { foreground: "#adadb1", background: "#0a0a0a" } },
|
||||
{ scope: "comment, punctuation.definition.comment", settings: { foreground: "#84848A" } },
|
||||
{
|
||||
scope: "keyword, storage, storage.type, keyword.operator.expression",
|
||||
settings: { foreground: "#FF678D" },
|
||||
},
|
||||
{
|
||||
scope: "entity.name.function, support.function, meta.function-call",
|
||||
settings: { foreground: "#9D6AFB" },
|
||||
},
|
||||
{
|
||||
scope: "entity.name.type, support.type, support.class",
|
||||
settings: { foreground: "#D568EA" },
|
||||
},
|
||||
{
|
||||
scope: "string, constant.character, punctuation.definition.string",
|
||||
settings: { foreground: "#5ECC71" },
|
||||
},
|
||||
{
|
||||
scope: "constant.numeric, constant.language, constant.other",
|
||||
settings: { foreground: "#68CDF2" },
|
||||
},
|
||||
{
|
||||
scope: "variable.parameter, variable.other.readwrite, meta.object-literal.key",
|
||||
settings: { foreground: "#FFA359" },
|
||||
},
|
||||
{
|
||||
scope: "entity.name.tag, support.class.component",
|
||||
settings: { foreground: "#5ECC71" },
|
||||
},
|
||||
{
|
||||
scope: "punctuation, meta.brace, meta.delimiter",
|
||||
settings: { foreground: "#79797F" },
|
||||
},
|
||||
{ scope: "invalid", settings: { foreground: "#FF6762" } },
|
||||
],
|
||||
};
|
||||
|
||||
const NATIVE_REVIEW_DIFF_SHIKI_THEMES = [
|
||||
PIERRE_LIGHT_SHIKI_THEME,
|
||||
PIERRE_DARK_SHIKI_THEME,
|
||||
] satisfies Parameters<typeof createHighlighterCore>[0]["themes"];
|
||||
|
||||
const NATIVE_REVIEW_DIFF_LANGUAGES = [
|
||||
bashLanguage,
|
||||
diffLanguage,
|
||||
javascriptLanguage,
|
||||
jsonLanguage,
|
||||
jsxLanguage,
|
||||
tsxLanguage,
|
||||
typescriptLanguage,
|
||||
yamlLanguage,
|
||||
] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
|
||||
|
||||
let nativeHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
|
||||
let javascriptHighlighterPromise: Promise<NativeReviewDiffHighlighterHandle> | null = null;
|
||||
|
||||
function waitForNextFrame(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function normalizeTokens(
|
||||
tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
|
||||
): ReadonlyArray<ReadonlyArray<NativeReviewDiffToken>> {
|
||||
return tokenLines.map((line) =>
|
||||
line.map((token) => ({
|
||||
content: token.content,
|
||||
color: token.color ?? null,
|
||||
fontStyle: token.fontStyle ?? null,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
const nativeEngineModule = await import("react-native-shiki-engine");
|
||||
if (!nativeEngineModule.isNativeEngineAvailable()) {
|
||||
throw new Error("Native Shiki engine is not available in this build.");
|
||||
}
|
||||
|
||||
const highlighter = await createHighlighterCore({
|
||||
langs: NATIVE_REVIEW_DIFF_LANGUAGES,
|
||||
themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
|
||||
engine: nativeEngineModule.createNativeEngine(),
|
||||
});
|
||||
|
||||
return {
|
||||
engine: "native",
|
||||
tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
|
||||
};
|
||||
}
|
||||
|
||||
async function createJavascriptReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
const highlighter: HighlighterCore = await createHighlighterCore({
|
||||
langs: NATIVE_REVIEW_DIFF_LANGUAGES,
|
||||
themes: NATIVE_REVIEW_DIFF_SHIKI_THEMES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
|
||||
return {
|
||||
engine: "javascript",
|
||||
tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getNativeReviewDiffHighlighter(
|
||||
engine: NativeReviewDiffHighlightEngine = "native",
|
||||
): Promise<NativeReviewDiffHighlighterHandle> {
|
||||
if (engine === "javascript") {
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
}
|
||||
|
||||
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
|
||||
console.warn("[debug-native-diff] native highlighter unavailable", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
});
|
||||
return nativeHighlighterPromise;
|
||||
}
|
||||
|
||||
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
|
||||
return row.kind === "line" && typeof row.fileId === "string" && typeof row.content === "string";
|
||||
}
|
||||
|
||||
function groupLineRowsByFileId(rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
const rowsByFileId = new Map<string, NativeReviewDiffLineRow[]>();
|
||||
for (const row of rows) {
|
||||
if (!isHighlightableLineRow(row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileRows = rowsByFileId.get(row.fileId) ?? [];
|
||||
fileRows.push(row);
|
||||
rowsByFileId.set(row.fileId, fileRows);
|
||||
}
|
||||
return rowsByFileId;
|
||||
}
|
||||
|
||||
function createFileMap(files: ReadonlyArray<NativeReviewDiffFile>) {
|
||||
return new Map(files.map((file) => [file.id, file]));
|
||||
}
|
||||
|
||||
function clampRowIndex(index: number, rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
if (rows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.min(rows.length - 1, Math.max(0, Math.floor(index)));
|
||||
}
|
||||
|
||||
function makePlainTokenFallback(
|
||||
row: NativeReviewDiffLineRow,
|
||||
): ReadonlyArray<NativeReviewDiffToken> {
|
||||
return [{ content: row.content || " ", color: null, fontStyle: null }];
|
||||
}
|
||||
|
||||
export async function highlightNativeReviewDiffVisibleRows(
|
||||
input: HighlightNativeReviewDiffVisibleRowsInput,
|
||||
): Promise<{
|
||||
readonly engine: NativeReviewDiffHighlightEngine;
|
||||
readonly tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>>;
|
||||
readonly rowCount: number;
|
||||
readonly durationMs: number;
|
||||
}> {
|
||||
const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
|
||||
if (input.signal?.aborted) {
|
||||
return { engine: highlighter.engine, tokensByRowId: {}, rowCount: 0, durationMs: 0 };
|
||||
}
|
||||
|
||||
const startedAt = performance.now();
|
||||
const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
|
||||
const fileMap = createFileMap(input.files);
|
||||
const overscanRows = input.overscanRows ?? NATIVE_REVIEW_DIFF_VISIBLE_OVERSCAN_ROWS;
|
||||
const maxRows = input.maxRows ?? NATIVE_REVIEW_DIFF_VISIBLE_MAX_ROWS;
|
||||
const startIndex = clampRowIndex(input.firstRowIndex - overscanRows, input.rows);
|
||||
const endIndex = clampRowIndex(input.lastRowIndex + overscanRows, input.rows);
|
||||
const selectedRows: NativeReviewDiffLineRow[] = [];
|
||||
|
||||
for (
|
||||
let rowIndex = startIndex;
|
||||
rowIndex <= endIndex && selectedRows.length < maxRows;
|
||||
rowIndex += 1
|
||||
) {
|
||||
const row = input.rows[rowIndex];
|
||||
if (
|
||||
row &&
|
||||
isHighlightableLineRow(row) &&
|
||||
!input.alreadyHighlightedRowIds?.has(row.id) &&
|
||||
fileMap.has(row.fileId)
|
||||
) {
|
||||
selectedRows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
|
||||
let segmentRows: NativeReviewDiffLineRow[] = [];
|
||||
let segmentFile: NativeReviewDiffFile | undefined;
|
||||
|
||||
const flushSegment = () => {
|
||||
if (!segmentFile || segmentRows.length === 0 || input.signal?.aborted) {
|
||||
segmentRows = [];
|
||||
segmentFile = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
const code = segmentRows.map((row) => row.content).join("\n");
|
||||
const tokenLines = highlighter.tokenize(code, { lang: segmentFile.language, theme });
|
||||
segmentRows.forEach((row, rowIndex) => {
|
||||
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
|
||||
});
|
||||
segmentRows = [];
|
||||
segmentFile = undefined;
|
||||
};
|
||||
|
||||
for (const row of selectedRows) {
|
||||
const file = fileMap.get(row.fileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segmentFile && segmentFile.id !== file.id) {
|
||||
flushSegment();
|
||||
}
|
||||
|
||||
segmentFile = file;
|
||||
segmentRows.push(row);
|
||||
}
|
||||
flushSegment();
|
||||
|
||||
return {
|
||||
engine: highlighter.engine,
|
||||
tokensByRowId,
|
||||
rowCount: selectedRows.length,
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
};
|
||||
}
|
||||
|
||||
export async function streamNativeReviewDiffTokens(
|
||||
input: StreamNativeReviewDiffTokenInput,
|
||||
): Promise<NativeReviewDiffHighlightEngine> {
|
||||
const highlighter = await getNativeReviewDiffHighlighter(input.engine ?? "native");
|
||||
const rowsByFileId = groupLineRowsByFileId(input.rows);
|
||||
const theme = NATIVE_REVIEW_DIFF_THEME_NAME_BY_SCHEME[input.scheme];
|
||||
const chunkSize = input.chunkSize ?? NATIVE_REVIEW_DIFF_HIGHLIGHT_CHUNK_SIZE;
|
||||
let chunkIndex = 0;
|
||||
|
||||
for (const file of input.files) {
|
||||
const fileRows = rowsByFileId.get(file.id) ?? [];
|
||||
for (let startIndex = 0; startIndex < fileRows.length; startIndex += chunkSize) {
|
||||
if (input.signal?.aborted) {
|
||||
return highlighter.engine;
|
||||
}
|
||||
|
||||
const startedAt = performance.now();
|
||||
const chunkRows = fileRows.slice(startIndex, startIndex + chunkSize);
|
||||
const code = chunkRows.map((row) => row.content).join("\n");
|
||||
const tokenLines = highlighter.tokenize(code, { lang: file.language, theme });
|
||||
const tokensByRowId: Record<string, ReadonlyArray<NativeReviewDiffToken>> = {};
|
||||
|
||||
chunkRows.forEach((row, rowIndex) => {
|
||||
tokensByRowId[row.id] = tokenLines[rowIndex] ?? makePlainTokenFallback(row);
|
||||
});
|
||||
|
||||
input.onChunk({
|
||||
chunkIndex,
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
language: file.language,
|
||||
lineCount: chunkRows.length,
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
tokensByRowId,
|
||||
});
|
||||
|
||||
chunkIndex += 1;
|
||||
await waitForNextFrame();
|
||||
}
|
||||
}
|
||||
|
||||
return highlighter.engine;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const expoModulesCoreMocks = vi.hoisted(() => ({
|
||||
requireNativeViewManager: vi.fn(),
|
||||
}));
|
||||
const nativeView = () => null;
|
||||
const originalExpo = globalThis.expo;
|
||||
|
||||
function setExpoViewConfigAvailable() {
|
||||
globalThis.expo = {
|
||||
getViewConfig: vi.fn().mockReturnValue({ validAttributes: {}, directEventTypes: {} }),
|
||||
} as unknown as typeof globalThis.expo;
|
||||
}
|
||||
|
||||
vi.mock("expo-modules-core", () => ({
|
||||
requireNativeViewManager: expoModulesCoreMocks.requireNativeViewManager,
|
||||
}));
|
||||
|
||||
describe("resolveNativeReviewDiffView", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
globalThis.expo = undefined as unknown as typeof globalThis.expo;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.expo = originalExpo;
|
||||
});
|
||||
|
||||
it("returns null when the native review diff view config is unavailable", async () => {
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the native review diff view when the view config is installed", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
expect(resolveNativeReviewDiffView()).toBe(nativeView);
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).toHaveBeenCalledWith(
|
||||
"T3ReviewDiffSurface",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not fall back to stale legacy native review diff view names", async () => {
|
||||
globalThis.expo = {
|
||||
getViewConfig: vi.fn().mockImplementation((moduleName: string) => {
|
||||
if (moduleName === "T3ReviewDiffView") {
|
||||
return { validAttributes: {}, directEventTypes: {} };
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
} as unknown as typeof globalThis.expo;
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockReturnValue(nativeView);
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
expect(expoModulesCoreMocks.requireNativeViewManager).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns null when the view manager cannot be required", async () => {
|
||||
setExpoViewConfigAvailable();
|
||||
expoModulesCoreMocks.requireNativeViewManager.mockImplementation(() => {
|
||||
throw new Error("boom");
|
||||
});
|
||||
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffModule");
|
||||
expect(resolveNativeReviewDiffView()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type { NativeSyntheticEvent, ViewProps } from "react-native";
|
||||
import { requireNativeViewManager } from "expo-modules-core";
|
||||
|
||||
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
|
||||
|
||||
interface ExpoGlobalWithViewConfig {
|
||||
readonly expo?: {
|
||||
getViewConfig?: (moduleName: string, viewName?: string) => unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffRow {
|
||||
readonly kind: "file" | "hunk" | "line" | "notice";
|
||||
readonly id: string;
|
||||
readonly fileId?: string;
|
||||
readonly filePath?: string;
|
||||
readonly previousPath?: string | null;
|
||||
readonly changeType?:
|
||||
| "modified"
|
||||
| "new"
|
||||
| "deleted"
|
||||
| "renamed"
|
||||
| "rename-pure"
|
||||
| "rename-changed";
|
||||
readonly additions?: number;
|
||||
readonly deletions?: number;
|
||||
readonly text?: string;
|
||||
readonly content?: string;
|
||||
readonly change?: "context" | "add" | "delete";
|
||||
readonly oldLineNumber?: number | null;
|
||||
readonly newLineNumber?: number | null;
|
||||
readonly wordDiffRanges?: ReadonlyArray<NativeReviewDiffWordDiffRange>;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffWordDiffRange {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffToken {
|
||||
readonly content: string;
|
||||
readonly color: string | null;
|
||||
readonly fontStyle: number | null;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffTheme {
|
||||
readonly background: string;
|
||||
readonly text: string;
|
||||
readonly mutedText: string;
|
||||
readonly headerBackground: string;
|
||||
readonly border: string;
|
||||
readonly hunkBackground: string;
|
||||
readonly hunkText: string;
|
||||
readonly addBackground: string;
|
||||
readonly deleteBackground: string;
|
||||
readonly addBar: string;
|
||||
readonly deleteBar: string;
|
||||
readonly addText: string;
|
||||
readonly deleteText: string;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffStyle {
|
||||
readonly rowHeight?: number;
|
||||
readonly contentWidth?: number;
|
||||
readonly changeBarWidth?: number;
|
||||
readonly gutterWidth?: number;
|
||||
readonly codePadding?: number;
|
||||
readonly textVerticalInset?: number;
|
||||
readonly fileHeaderHeight?: number;
|
||||
readonly fileHeaderHorizontalMargin?: number;
|
||||
readonly fileHeaderVerticalMargin?: number;
|
||||
readonly fileHeaderCornerRadius?: number;
|
||||
readonly fileHeaderHorizontalPadding?: number;
|
||||
readonly fileHeaderPathRightPadding?: number;
|
||||
readonly fileHeaderCountColumnWidth?: number;
|
||||
readonly fileHeaderCountGap?: number;
|
||||
readonly codeFontSize?: number;
|
||||
readonly codeFontWeight?: string;
|
||||
readonly lineNumberFontSize?: number;
|
||||
readonly lineNumberFontWeight?: string;
|
||||
readonly hunkFontSize?: number;
|
||||
readonly hunkFontWeight?: string;
|
||||
readonly fileHeaderFontSize?: number;
|
||||
readonly fileHeaderFontWeight?: string;
|
||||
readonly fileHeaderMetaFontSize?: number;
|
||||
readonly fileHeaderMetaFontWeight?: string;
|
||||
readonly fileHeaderSubtextFontSize?: number;
|
||||
readonly fileHeaderSubtextFontWeight?: string;
|
||||
readonly emptyStateFontSize?: number;
|
||||
readonly emptyStateFontWeight?: string;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffViewProps extends ViewProps {
|
||||
readonly rowsJson: string;
|
||||
readonly tokensJson?: string;
|
||||
readonly tokensPatchJson?: string;
|
||||
readonly tokensResetKey?: string;
|
||||
readonly collapsedFileIdsJson?: string;
|
||||
readonly viewedFileIdsJson?: string;
|
||||
readonly appearanceScheme: "light" | "dark";
|
||||
readonly themeJson: string;
|
||||
readonly styleJson?: string;
|
||||
readonly rowHeight: number;
|
||||
readonly contentWidth: number;
|
||||
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
|
||||
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
|
||||
}
|
||||
|
||||
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
|
||||
let cachedNativeReviewDiffModuleName: typeof NATIVE_REVIEW_DIFF_MODULE_NAME | undefined;
|
||||
|
||||
function getExpoViewConfig(moduleName: string) {
|
||||
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
|
||||
moduleName,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
|
||||
if (cachedNativeReviewDiffView) {
|
||||
return cachedNativeReviewDiffView;
|
||||
}
|
||||
|
||||
if (getExpoViewConfig(NATIVE_REVIEW_DIFF_MODULE_NAME) == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
cachedNativeReviewDiffView = requireNativeViewManager<NativeReviewDiffViewProps>(
|
||||
NATIVE_REVIEW_DIFF_MODULE_NAME,
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
cachedNativeReviewDiffModuleName = NATIVE_REVIEW_DIFF_MODULE_NAME;
|
||||
return cachedNativeReviewDiffView ?? null;
|
||||
}
|
||||
|
||||
export function getResolvedNativeReviewDiffModuleName() {
|
||||
return cachedNativeReviewDiffModuleName ?? null;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseNativeReviewDiffFixture } from "./nativeReviewDiffParser";
|
||||
|
||||
describe("parseNativeReviewDiffFixture", () => {
|
||||
it("adds word diff ranges to paired changed lines", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 9,
|
||||
diff: [
|
||||
"diff --git a/main.ts b/main.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.ts",
|
||||
"+++ b/main.ts",
|
||||
"@@ -1,3 +1,3 @@",
|
||||
" const stable = true;",
|
||||
'-const label = "Before value";',
|
||||
'+const label = "After value";',
|
||||
" const done = true;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const deletion = parsed.rows.find((row) => row.change === "delete");
|
||||
const addition = parsed.rows.find((row) => row.change === "add");
|
||||
|
||||
expect(deletion?.wordDiffRanges).toEqual([{ start: 15, end: 21 }]);
|
||||
expect(addition?.wordDiffRanges).toEqual([{ start: 15, end: 20 }]);
|
||||
});
|
||||
|
||||
it("does not add word diff ranges to unpaired created lines", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 9,
|
||||
diff: [
|
||||
"diff --git a/new.ts b/new.ts",
|
||||
"new file mode 100644",
|
||||
"index 0000000..2222222",
|
||||
"--- /dev/null",
|
||||
"+++ b/new.ts",
|
||||
"@@ -0,0 +1,2 @@",
|
||||
'+const label = "After value";',
|
||||
"+export default label;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
expect(parsed.rows.filter((row) => row.kind === "line")).toHaveLength(2);
|
||||
expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("trims whitespace from word diff range edges", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 8,
|
||||
diff: [
|
||||
"diff --git a/main.tsx b/main.tsx",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.tsx",
|
||||
"+++ b/main.tsx",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"- const status = disabled;",
|
||||
"+ const status = enabled;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const deletion = parsed.rows.find((row) => row.change === "delete");
|
||||
const addition = parsed.rows.find((row) => row.change === "add");
|
||||
|
||||
expect(deletion?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
|
||||
expect(addition?.wordDiffRanges?.[0]?.start).toBeGreaterThanOrEqual(4);
|
||||
});
|
||||
|
||||
it("keeps word diff ranges aligned to exact replacement columns", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 12,
|
||||
diff: [
|
||||
"diff --git a/main.ts b/main.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.ts",
|
||||
"+++ b/main.ts",
|
||||
"@@ -1,5 +1,5 @@",
|
||||
"-const retryLimit = 2;",
|
||||
"+const retryLimit = 4;",
|
||||
'-const greeting = greeting.replace("{name}", "reviewer");',
|
||||
'+const greeting = greeting.replace("{name}", "native reviewer");',
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const changedRows = parsed.rows.filter((row) => row.kind === "line");
|
||||
|
||||
expect(changedRows[0]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
|
||||
expect(changedRows[1]?.wordDiffRanges).toEqual([{ start: 19, end: 20 }]);
|
||||
expect(changedRows[2]?.wordDiffRanges).toBeUndefined();
|
||||
expect(changedRows[3]?.wordDiffRanges).toEqual([{ start: 45, end: 51 }]);
|
||||
});
|
||||
|
||||
it("suppresses noisy word diff ranges for unrelated replacement lines", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 8,
|
||||
diff: [
|
||||
"diff --git a/main.tsx b/main.tsx",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/main.tsx",
|
||||
"+++ b/main.tsx",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
'- case "file-header":',
|
||||
"+ const status = enabled;",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
expect(parsed.rows.every((row) => row.wordDiffRanges === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("adds notice rows for pure renames and metadata-only changes", () => {
|
||||
const parsed = parseNativeReviewDiffFixture({
|
||||
id: "states",
|
||||
label: "States",
|
||||
filename: "states.diff",
|
||||
lineCount: 16,
|
||||
diff: [
|
||||
"diff --git a/src/oldName.ts b/src/newName.ts",
|
||||
"similarity index 100%",
|
||||
"rename from src/oldName.ts",
|
||||
"rename to src/newName.ts",
|
||||
"diff --git a/scripts/run.sh b/scripts/run.sh",
|
||||
"old mode 100644",
|
||||
"new mode 100755",
|
||||
"diff --git a/assets/logo.png b/assets/logo.png",
|
||||
"new file mode 100644",
|
||||
"index 000000000..4628f44da",
|
||||
"--- /dev/null",
|
||||
"+++ b/assets/logo.png",
|
||||
"Binary files /dev/null and b/assets/logo.png differ",
|
||||
].join("\n"),
|
||||
});
|
||||
|
||||
const noticeTexts = parsed.rows.filter((row) => row.kind === "notice").map((row) => row.text);
|
||||
|
||||
expect(noticeTexts).toEqual([
|
||||
"This file was renamed without modifications.",
|
||||
"File mode changed from 100644 to 100755.",
|
||||
"Unsupported binary format. Diff contents are not available.",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,549 @@
|
||||
import {
|
||||
debugReviewDiffFixtures,
|
||||
type DebugReviewDiffFixture,
|
||||
type DebugReviewDiffFixtureId,
|
||||
} from "../fixtures/reviewDiffFixtures";
|
||||
import { computeWordAltDiffRanges } from "../../review/reviewWordDiffs";
|
||||
import type { NativeReviewDiffRow } from "./nativeReviewDiffModule";
|
||||
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
|
||||
|
||||
export type NativeReviewDiffLanguage =
|
||||
| "bash"
|
||||
| "diff"
|
||||
| "javascript"
|
||||
| "json"
|
||||
| "jsx"
|
||||
| "tsx"
|
||||
| "typescript"
|
||||
| "yaml";
|
||||
|
||||
export interface NativeReviewDiffFile {
|
||||
readonly id: string;
|
||||
readonly path: string;
|
||||
readonly language: NativeReviewDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
export interface NativeReviewDiffParsedFixture {
|
||||
readonly fixtureId: DebugReviewDiffFixtureId;
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
interface NativeReviewDiffFileParseState {
|
||||
readonly path: string;
|
||||
readonly language: NativeReviewDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
readonly hasRenderableRows: boolean;
|
||||
readonly isBinary: boolean;
|
||||
readonly oldMode: string | null;
|
||||
readonly newMode: string | null;
|
||||
}
|
||||
|
||||
function getDiffPathFromHeader(line: string): string {
|
||||
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
||||
return match?.[2] ?? line.replace(/^diff --git /, "");
|
||||
}
|
||||
|
||||
function getDiffPreviousPathFromHeader(line: string): string | null {
|
||||
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null {
|
||||
if (!line.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawPath = line.slice(prefix.length).trim();
|
||||
if (rawPath === "/dev/null") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return rawPath.replace(/^[ab]\//, "");
|
||||
}
|
||||
|
||||
function resolveChangeType(input: {
|
||||
readonly previousPath: string | null;
|
||||
readonly nextPath: string | null;
|
||||
}): NativeReviewDiffRow["changeType"] {
|
||||
if (!input.previousPath && input.nextPath) {
|
||||
return "new";
|
||||
}
|
||||
if (input.previousPath && !input.nextPath) {
|
||||
return "deleted";
|
||||
}
|
||||
if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
|
||||
return "renamed";
|
||||
}
|
||||
return "modified";
|
||||
}
|
||||
|
||||
function resolveFileHeaderChangeType(input: {
|
||||
readonly previousPath: string | null | undefined;
|
||||
readonly nextPath: string | null | undefined;
|
||||
readonly currentChangeType: NativeReviewDiffRow["changeType"];
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}): NativeReviewDiffRow["changeType"] {
|
||||
if (input.currentChangeType === "new" || input.currentChangeType === "deleted") {
|
||||
return input.currentChangeType;
|
||||
}
|
||||
|
||||
if (input.previousPath && input.nextPath && input.previousPath !== input.nextPath) {
|
||||
return input.additions + input.deletions === 0 ? "rename-pure" : "rename-changed";
|
||||
}
|
||||
|
||||
return resolveChangeType({
|
||||
nextPath: input.nextPath ?? null,
|
||||
previousPath: input.previousPath ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
function getLanguageForPath(filePath: string): NativeReviewDiffLanguage {
|
||||
const normalizedPath = filePath.toLowerCase();
|
||||
if (normalizedPath.endsWith(".tsx")) return "tsx";
|
||||
if (normalizedPath.endsWith(".ts")) return "typescript";
|
||||
if (normalizedPath.endsWith(".jsx")) return "jsx";
|
||||
if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
|
||||
if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
|
||||
if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
|
||||
if (
|
||||
normalizedPath.endsWith(".sh") ||
|
||||
normalizedPath.includes("/bin/") ||
|
||||
normalizedPath.includes("shell")
|
||||
) {
|
||||
return "bash";
|
||||
}
|
||||
return "diff";
|
||||
}
|
||||
|
||||
function parseHunkLineNumbers(line: string): { oldLine: number; newLine: number } | null {
|
||||
const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
oldLine: Number(match[1]),
|
||||
newLine: Number(match[2]),
|
||||
};
|
||||
}
|
||||
|
||||
function parseFileModeLine(line: string, prefix: "old mode " | "new mode "): string | null {
|
||||
if (!line.startsWith(prefix)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return line.slice(prefix.length).trim() || null;
|
||||
}
|
||||
|
||||
function createNoticeRow(input: {
|
||||
readonly fileId: string;
|
||||
readonly message: string;
|
||||
readonly suffix: string;
|
||||
}): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "notice",
|
||||
id: `${input.fileId}:notice:${input.suffix}`,
|
||||
fileId: input.fileId,
|
||||
text: input.message,
|
||||
};
|
||||
}
|
||||
|
||||
function getNoticeRowForFile(input: {
|
||||
readonly row: NativeReviewDiffRow;
|
||||
readonly file: NativeReviewDiffFileParseState | undefined;
|
||||
}): NativeReviewDiffRow | null {
|
||||
const { file, row } = input;
|
||||
if (!file || row.kind !== "file" || !row.fileId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (file.isBinary) {
|
||||
return createNoticeRow({
|
||||
fileId: row.fileId,
|
||||
message: "Unsupported binary format. Diff contents are not available.",
|
||||
suffix: "binary",
|
||||
});
|
||||
}
|
||||
|
||||
if (file.oldMode && file.newMode && file.oldMode !== file.newMode && !file.hasRenderableRows) {
|
||||
return createNoticeRow({
|
||||
fileId: row.fileId,
|
||||
message: `File mode changed from ${file.oldMode} to ${file.newMode}.`,
|
||||
suffix: "mode",
|
||||
});
|
||||
}
|
||||
|
||||
if (row.changeType === "rename-pure" && !file.hasRenderableRows) {
|
||||
return createNoticeRow({
|
||||
fileId: row.fileId,
|
||||
message: "This file was renamed without modifications.",
|
||||
suffix: "rename",
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isChangedLine(row: NativeReviewDiffRow | undefined, change: "add" | "delete") {
|
||||
return row?.kind === "line" && row.change === change && typeof row.content === "string";
|
||||
}
|
||||
|
||||
function trimWordDiffRanges(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
|
||||
return ranges.flatMap((range) => {
|
||||
let start = Math.max(0, range.start);
|
||||
let end = Math.min(content.length, range.end);
|
||||
|
||||
while (start < end && /\s/.test(content[start] ?? "")) {
|
||||
start += 1;
|
||||
}
|
||||
|
||||
while (end > start && /\s/.test(content[end - 1] ?? "")) {
|
||||
end -= 1;
|
||||
}
|
||||
|
||||
return end > start ? [{ start, end }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonWhitespaceLength(value: string) {
|
||||
return value.replace(/\s/g, "").length;
|
||||
}
|
||||
|
||||
function getRangeCoverage(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
) {
|
||||
const meaningfulLength = nonWhitespaceLength(content);
|
||||
if (meaningfulLength === 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const highlightedLength = ranges.reduce(
|
||||
(total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
|
||||
0,
|
||||
);
|
||||
return highlightedLength / meaningfulLength;
|
||||
}
|
||||
|
||||
function shouldUseWordDiffRanges(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
) {
|
||||
if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getRangeCoverage(content, ranges) <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
|
||||
}
|
||||
|
||||
function addNativeWordDiffRanges(rows: ReadonlyArray<NativeReviewDiffRow>) {
|
||||
const nextRows = [...rows];
|
||||
let index = 0;
|
||||
|
||||
while (index < nextRows.length) {
|
||||
const deletedRowIndexes: number[] = [];
|
||||
const addedRowIndexes: number[] = [];
|
||||
const fileId = nextRows[index]?.fileId;
|
||||
|
||||
while (isChangedLine(nextRows[index], "delete") && nextRows[index]?.fileId === fileId) {
|
||||
deletedRowIndexes.push(index);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
if (deletedRowIndexes.length === 0) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
while (isChangedLine(nextRows[index], "add") && nextRows[index]?.fileId === fileId) {
|
||||
addedRowIndexes.push(index);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
if (addedRowIndexes.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pairCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
|
||||
for (let pairIndex = 0; pairIndex < pairCount; pairIndex += 1) {
|
||||
const deletedRowIndex = deletedRowIndexes[pairIndex];
|
||||
const addedRowIndex = addedRowIndexes[pairIndex];
|
||||
const deletedRow = nextRows[deletedRowIndex];
|
||||
const addedRow = nextRows[addedRowIndex];
|
||||
if (!deletedRow?.content || !addedRow?.content) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const ranges = computeWordAltDiffRanges({
|
||||
deletionLine: deletedRow.content,
|
||||
additionLine: addedRow.content,
|
||||
});
|
||||
|
||||
const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
|
||||
const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
|
||||
|
||||
if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
|
||||
nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
|
||||
}
|
||||
|
||||
if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
|
||||
nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nextRows;
|
||||
}
|
||||
|
||||
export function parseNativeReviewDiffFixture(
|
||||
fixture: DebugReviewDiffFixture,
|
||||
): NativeReviewDiffParsedFixture {
|
||||
const startedAt = performance.now();
|
||||
let rows: NativeReviewDiffRow[] = [];
|
||||
const files = new Map<string, NativeReviewDiffFileParseState>();
|
||||
const rawLines = fixture.diff.split(/\r?\n/);
|
||||
|
||||
let currentFileId: string | null = null;
|
||||
let currentOldLine: number | null = null;
|
||||
let currentNewLine: number | null = null;
|
||||
|
||||
function ensureCurrentFile(filePath: string, previousPath: string | null): string {
|
||||
const fileId = `file:${files.size}:${filePath}`;
|
||||
const language = getLanguageForPath(filePath);
|
||||
files.set(fileId, {
|
||||
path: filePath,
|
||||
language,
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
hasRenderableRows: false,
|
||||
isBinary: false,
|
||||
oldMode: null,
|
||||
newMode: null,
|
||||
});
|
||||
rows.push({
|
||||
kind: "file",
|
||||
id: `${fileId}:header`,
|
||||
fileId,
|
||||
filePath,
|
||||
previousPath,
|
||||
changeType: resolveChangeType({ nextPath: filePath, previousPath }),
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
});
|
||||
return fileId;
|
||||
}
|
||||
|
||||
for (let index = 0; index < rawLines.length; index += 1) {
|
||||
const rawLine = rawLines[index] ?? "";
|
||||
|
||||
if (rawLine.startsWith("diff --git ")) {
|
||||
currentFileId = ensureCurrentFile(
|
||||
getDiffPathFromHeader(rawLine),
|
||||
getDiffPreviousPathFromHeader(rawLine),
|
||||
);
|
||||
currentOldLine = null;
|
||||
currentNewLine = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!currentFileId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const previousPath = parseDiffPath(rawLine, "--- ");
|
||||
if (previousPath !== null || rawLine === "--- /dev/null") {
|
||||
rows = rows.map((row) =>
|
||||
row.id === `${currentFileId}:header`
|
||||
? {
|
||||
...row,
|
||||
previousPath,
|
||||
changeType: resolveChangeType({
|
||||
nextPath: row.filePath ?? null,
|
||||
previousPath,
|
||||
}),
|
||||
}
|
||||
: row,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const nextPath = parseDiffPath(rawLine, "+++ ");
|
||||
if (nextPath !== null || rawLine === "+++ /dev/null") {
|
||||
rows = rows.map((row) =>
|
||||
row.id === `${currentFileId}:header`
|
||||
? {
|
||||
...row,
|
||||
filePath: nextPath ?? row.filePath,
|
||||
changeType: resolveChangeType({
|
||||
nextPath,
|
||||
previousPath: row.previousPath ?? null,
|
||||
}),
|
||||
}
|
||||
: row,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const oldMode = parseFileModeLine(rawLine, "old mode ");
|
||||
if (oldMode !== null) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, oldMode });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const newMode = parseFileModeLine(rawLine, "new mode ");
|
||||
if (newMode !== null) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, newMode });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rawLine.startsWith("Binary files ")) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, isBinary: true });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rawLine.startsWith("@@ ")) {
|
||||
const file = files.get(currentFileId);
|
||||
if (file) {
|
||||
files.set(currentFileId, { ...file, hasRenderableRows: true });
|
||||
}
|
||||
const parsedLineNumbers = parseHunkLineNumbers(rawLine);
|
||||
currentOldLine = parsedLineNumbers?.oldLine ?? null;
|
||||
currentNewLine = parsedLineNumbers?.newLine ?? null;
|
||||
rows.push({
|
||||
kind: "hunk",
|
||||
id: `${currentFileId}:hunk:${index}`,
|
||||
fileId: currentFileId,
|
||||
text: rawLine,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const marker = rawLine[0];
|
||||
if (marker !== " " && marker !== "+" && marker !== "-") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file = files.get(currentFileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const change = marker === "+" ? "add" : marker === "-" ? "delete" : "context";
|
||||
rows.push({
|
||||
kind: "line",
|
||||
id: `${currentFileId}:line:${index}`,
|
||||
fileId: currentFileId,
|
||||
change,
|
||||
oldLineNumber: change === "add" ? null : currentOldLine,
|
||||
newLineNumber: change === "delete" ? null : currentNewLine,
|
||||
content: rawLine.slice(1),
|
||||
});
|
||||
|
||||
if (change === "add") {
|
||||
files.set(currentFileId, { ...file, additions: file.additions + 1 });
|
||||
currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (change === "delete") {
|
||||
files.set(currentFileId, { ...file, deletions: file.deletions + 1 });
|
||||
currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
|
||||
currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
|
||||
}
|
||||
|
||||
rows = addNativeWordDiffRanges(rows);
|
||||
|
||||
const fileSummaries = Array.from(files, ([id, file]) => ({
|
||||
id,
|
||||
path: file.path,
|
||||
language: file.language,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}));
|
||||
const fileSummaryByPath = new Map(fileSummaries.map((file) => [file.path, file]));
|
||||
const rowsWithFileStats = rows.map((row): NativeReviewDiffRow => {
|
||||
if (row.kind !== "file" || !row.filePath) {
|
||||
return row;
|
||||
}
|
||||
const file = fileSummaryByPath.get(row.filePath);
|
||||
const additions = file?.additions ?? row.additions ?? 0;
|
||||
const deletions = file?.deletions ?? row.deletions ?? 0;
|
||||
return {
|
||||
kind: row.kind,
|
||||
id: row.id,
|
||||
fileId: row.fileId,
|
||||
filePath: row.filePath,
|
||||
previousPath: row.previousPath,
|
||||
changeType: resolveFileHeaderChangeType({
|
||||
previousPath: row.previousPath,
|
||||
nextPath: row.filePath,
|
||||
currentChangeType: row.changeType ?? "modified",
|
||||
additions,
|
||||
deletions,
|
||||
}),
|
||||
additions,
|
||||
deletions,
|
||||
text: row.text,
|
||||
content: row.content,
|
||||
change: row.change,
|
||||
oldLineNumber: row.oldLineNumber,
|
||||
newLineNumber: row.newLineNumber,
|
||||
wordDiffRanges: row.wordDiffRanges,
|
||||
};
|
||||
});
|
||||
const rowsWithFileNotices = rowsWithFileStats.flatMap((row): NativeReviewDiffRow[] => {
|
||||
const noticeRow = getNoticeRowForFile({
|
||||
row,
|
||||
file: row.fileId ? files.get(row.fileId) : undefined,
|
||||
});
|
||||
return noticeRow ? [row, noticeRow] : [row];
|
||||
});
|
||||
|
||||
const parsed = {
|
||||
fixtureId: fixture.id,
|
||||
rows: rowsWithFileNotices,
|
||||
files: fileSummaries,
|
||||
additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
|
||||
deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0),
|
||||
};
|
||||
|
||||
console.log("[debug-native-diff] parse", {
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
files: parsed.files.length,
|
||||
fixture: fixture.id,
|
||||
rows: parsed.rows.length,
|
||||
});
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function getNativeReviewDiffFixture(fixtureId: DebugReviewDiffFixtureId) {
|
||||
return (
|
||||
debugReviewDiffFixtures.find((fixture) => fixture.id === fixtureId) ??
|
||||
debugReviewDiffFixtures[0]
|
||||
);
|
||||
}
|
||||
+52
-57
@@ -2,28 +2,21 @@ import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
View,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
} from "react-native";
|
||||
import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill } from "../../../components/ControlPill";
|
||||
import { cn } from "../../../lib/cn";
|
||||
import type { DraftComposerImageAttachment } from "../../../lib/composerImages";
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../../lib/composerImages";
|
||||
import { useThemeColor } from "../../../lib/useThemeColor";
|
||||
import { useNativePaste } from "../../../hooks/useNativePaste";
|
||||
import { setPendingConnectionError } from "../../../state/use-remote-environment-registry";
|
||||
import { appendReviewCommentToDraft } from "../use-thread-composer-state";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useNativePaste } from "../../lib/useNativePaste";
|
||||
import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
|
||||
import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state";
|
||||
import {
|
||||
clearReviewCommentTarget,
|
||||
formatReviewCommentContext,
|
||||
@@ -34,6 +27,7 @@ import {
|
||||
import {
|
||||
changeTone,
|
||||
DiffTokenText,
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_MONO_FONT_FAMILY,
|
||||
ReviewChangeBar,
|
||||
} from "./reviewDiffRendering";
|
||||
@@ -44,7 +38,6 @@ import {
|
||||
} from "./shikiReviewHighlighter";
|
||||
|
||||
const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
|
||||
const REVIEW_COMMENT_LINE_HEIGHT = 26;
|
||||
|
||||
export function ReviewCommentComposerSheet() {
|
||||
const router = useRouter();
|
||||
@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {
|
||||
? `Lines ${firstNumber}-${lastNumber}`
|
||||
: `${selectedLines.length} lines selected`;
|
||||
const previewHeight = Math.max(
|
||||
Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,
|
||||
REVIEW_COMMENT_LINE_HEIGHT,
|
||||
Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
);
|
||||
const previewViewportWidth = Math.max(width - 40, 280);
|
||||
const handleNativePaste = useNativePaste((uris) => {
|
||||
@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {
|
||||
}
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 12 : 0}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 82,
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-center justify-between py-2">
|
||||
@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {
|
||||
<View
|
||||
key={line.id}
|
||||
className={cn("flex-row items-start", changeTone(line.change))}
|
||||
style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}
|
||||
style={{ height: REVIEW_DIFF_LINE_HEIGHT }}
|
||||
>
|
||||
<ReviewChangeBar change={line.change} />
|
||||
<Text
|
||||
@@ -228,7 +217,7 @@ export function ReviewCommentComposerSheet() {
|
||||
>
|
||||
{lineNumber ?? ""}
|
||||
</Text>
|
||||
<View className="min-w-0 flex-1 flex-shrink-0 px-1 py-1">
|
||||
<View className="min-w-0 flex-1 shrink-0 px-1 py-1">
|
||||
<DiffTokenText
|
||||
fallback={line.content}
|
||||
tokens={highlightedLinesById[line.id] ?? null}
|
||||
@@ -280,35 +269,41 @@ export function ReviewCommentComposerSheet() {
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="flex-row items-center gap-3 pt-1">
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<View className="flex-1" />
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label="Comment"
|
||||
variant="primary"
|
||||
disabled={!canSubmit}
|
||||
onPress={() => {
|
||||
if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
appendReviewCommentToDraft({
|
||||
environmentId,
|
||||
threadId,
|
||||
text: formatReviewCommentContext(target, commentText),
|
||||
attachments,
|
||||
});
|
||||
setAttachments([]);
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
{target ? (
|
||||
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-sheet px-5 pt-3"
|
||||
style={{ paddingBottom: Math.max(insets.bottom, 18) }}
|
||||
>
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<View className="flex-1" />
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label="Comment"
|
||||
variant="primary"
|
||||
disabled={!canSubmit}
|
||||
onPress={() => {
|
||||
if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
appendReviewCommentToDraft({
|
||||
environmentId,
|
||||
threadId,
|
||||
text: formatReviewCommentContext(target, commentText),
|
||||
attachments,
|
||||
});
|
||||
setAttachments([]);
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
imageIndex={0}
|
||||
@@ -317,6 +312,6 @@ export function ReviewCommentComposerSheet() {
|
||||
swipeToCloseEnabled
|
||||
doubleTapToZoomEnabled
|
||||
/>
|
||||
</KeyboardAvoidingView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
getActiveReviewHighlighterEngine,
|
||||
prepareReviewHighlighter,
|
||||
prepareReviewHighlighterLanguages,
|
||||
type ReviewHighlighterEngine,
|
||||
} from "./shikiReviewHighlighter";
|
||||
|
||||
type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
|
||||
|
||||
interface ReviewHighlighterContextValue {
|
||||
readonly engine: ReviewHighlighterEngine | null;
|
||||
readonly error: string | null;
|
||||
readonly status: ReviewHighlighterStatus;
|
||||
}
|
||||
|
||||
const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
const REVIEW_INITIAL_LANGUAGES = [
|
||||
"typescript",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"jsx",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
] as const;
|
||||
|
||||
function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewHighlighterProviderDiagnostic(
|
||||
message: string,
|
||||
details?: Record<string, unknown>,
|
||||
): void {
|
||||
if (!isReviewHighlighterProviderDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-highlighter-provider] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-highlighter-provider] ${message}`);
|
||||
}
|
||||
|
||||
export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {
|
||||
const [value, setValue] = useState<ReviewHighlighterContextValue>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
setValue({ engine: null, error: null, status: "initializing" });
|
||||
|
||||
void (async () => {
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
await prepareReviewHighlighter();
|
||||
await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);
|
||||
const engine = await getActiveReviewHighlighterEngine();
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
setValue({ engine, error: null, status: "ready" });
|
||||
} catch (error) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
|
||||
setValue({ engine: null, error: message, status: "error" });
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const contextValue = useMemo(() => value, [value]);
|
||||
|
||||
return (
|
||||
<ReviewHighlighterContext.Provider value={contextValue}>
|
||||
{props.children}
|
||||
</ReviewHighlighterContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {
|
||||
return useContext(ReviewHighlighterContext);
|
||||
}
|
||||
@@ -0,0 +1,918 @@
|
||||
import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";
|
||||
import { useLocalSearchParams } from "expo-router";
|
||||
import Stack from "expo-router/stack";
|
||||
import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
ScrollView,
|
||||
type NativeSyntheticEvent,
|
||||
Text as NativeText,
|
||||
StyleSheet,
|
||||
useColorScheme,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import {
|
||||
getCachedReviewParsedDiff,
|
||||
setReviewGitSections,
|
||||
setReviewSelectedSectionId,
|
||||
setReviewTurnDiff,
|
||||
updateReviewExpandedFileIds,
|
||||
updateReviewViewedFileIds,
|
||||
useReviewCacheForThread,
|
||||
} from "./reviewState";
|
||||
import {
|
||||
getReadyReviewCheckpoints,
|
||||
buildReviewSectionItems,
|
||||
getDefaultReviewSectionId,
|
||||
getReviewSectionIdForCheckpoint,
|
||||
type ReviewParsedDiff,
|
||||
type ReviewRenderableFile,
|
||||
} from "./reviewModel";
|
||||
import { countReviewCommentContexts } from "./reviewCommentSelection";
|
||||
import { markReviewEvent, measureReviewWork } from "./reviewPerf";
|
||||
import {
|
||||
highlightNativeReviewDiffVisibleRows,
|
||||
type NativeReviewDiffHighlightEngine,
|
||||
} from "../debug/native-review-diff/nativeReviewDiffHighlighter";
|
||||
import { resolveNativeReviewDiffView } from "../debug/native-review-diff/nativeReviewDiffModule";
|
||||
import {
|
||||
buildNativeReviewDiffData,
|
||||
createNativeReviewDiffTheme,
|
||||
NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
|
||||
NATIVE_REVIEW_DIFF_ROW_HEIGHT,
|
||||
NATIVE_REVIEW_DIFF_STYLE,
|
||||
} from "./nativeReviewDiffAdapter";
|
||||
|
||||
const IOS_NAV_BAR_HEIGHT = 44;
|
||||
const REVIEW_HEADER_SPACING = 0;
|
||||
|
||||
function isReviewDiffDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewDiffDiagnostic(message: string, details?: Record<string, unknown>): void {
|
||||
if (!isReviewDiffDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-sheet] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-sheet] ${message}`);
|
||||
}
|
||||
|
||||
function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {
|
||||
readonly additions: string | null;
|
||||
readonly deletions: string | null;
|
||||
} {
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return { additions: null, deletions: null };
|
||||
}
|
||||
|
||||
return {
|
||||
additions: `+${parsedDiff.additions}`,
|
||||
deletions: `-${parsedDiff.deletions}`,
|
||||
};
|
||||
}
|
||||
|
||||
function hashReviewDiffKey(diff: string | null | undefined): string {
|
||||
if (!diff) {
|
||||
return "empty";
|
||||
}
|
||||
|
||||
let hash = 5381;
|
||||
for (let index = 0; index < diff.length; index += 1) {
|
||||
hash = (hash * 33) ^ diff.charCodeAt(index);
|
||||
}
|
||||
|
||||
return `${diff.length}:${(hash >>> 0).toString(36)}`;
|
||||
}
|
||||
|
||||
function getDefaultExpandedFileIds(
|
||||
files: ReadonlyArray<ReviewRenderableFile>,
|
||||
): ReadonlyArray<string> {
|
||||
return files.map((file) => file.id);
|
||||
}
|
||||
|
||||
function getValidReviewExpandedFileIds(
|
||||
files: ReadonlyArray<ReviewRenderableFile>,
|
||||
cachedExpandedFileIds: ReadonlyArray<string> | undefined,
|
||||
): ReadonlyArray<string> {
|
||||
if (cachedExpandedFileIds === undefined) {
|
||||
return getDefaultExpandedFileIds(files);
|
||||
}
|
||||
|
||||
const fileIdSet = new Set(files.map((file) => file.id));
|
||||
return cachedExpandedFileIds.filter((id) => fileIdSet.has(id));
|
||||
}
|
||||
|
||||
const ReviewNotice = memo(function ReviewNotice(props: { readonly notice: string }) {
|
||||
return (
|
||||
<View className="border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/60 dark:bg-amber-950/40">
|
||||
<Text className="text-[12px] font-t3-bold uppercase text-amber-700 dark:text-amber-300">
|
||||
Partial diff
|
||||
</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-amber-800 dark:text-amber-200">
|
||||
{props.notice}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
export function ReviewSheet() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const colorScheme = useColorScheme();
|
||||
const headerForeground = String(useThemeColor("--color-foreground"));
|
||||
const headerMuted = String(useThemeColor("--color-foreground-muted"));
|
||||
const headerIcon = String(useThemeColor("--color-icon"));
|
||||
const { environmentId, threadId } = useLocalSearchParams<{
|
||||
environmentId: EnvironmentId;
|
||||
threadId: ThreadId;
|
||||
}>();
|
||||
const { draftMessage } = useThreadDraftForThread({ environmentId, threadId });
|
||||
const reviewCache = useReviewCacheForThread({ environmentId, threadId });
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const [loadingTurnIds, setLoadingTurnIds] = useState<Record<string, boolean>>({});
|
||||
const [loadingGitDiffs, setLoadingGitDiffs] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [localExpandedFileIdsBySection, setLocalExpandedFileIdsBySection] = useState<
|
||||
Record<string, ReadonlyArray<string>>
|
||||
>({});
|
||||
const [localViewedFileIdsBySection, setLocalViewedFileIdsBySection] = useState<
|
||||
Record<string, ReadonlyArray<string>>
|
||||
>({});
|
||||
const [nativeTokensPatchJson, setNativeTokensPatchJson] = useState(
|
||||
JSON.stringify({ resetKey: "", tokensByRowId: {} }),
|
||||
);
|
||||
const selectedTheme = colorScheme === "dark" ? "dark" : "light";
|
||||
const nativeHighlightedRowIdsRef = useRef<Set<string>>(new Set());
|
||||
const nativeVisibleRangeRef = useRef({ firstRowIndex: 0, lastRowIndex: 80 });
|
||||
const nativeVisibleChunkIndexRef = useRef(0);
|
||||
const [nativeVisibleHighlightRequest, setNativeVisibleHighlightRequest] = useState(0);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
|
||||
const cwd = selectedThreadCwd;
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
);
|
||||
|
||||
const checkpointBySectionId = useMemo(() => {
|
||||
return Object.fromEntries(
|
||||
readyCheckpoints.map((checkpoint) => [
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, OrchestrationCheckpointSummary>;
|
||||
}, [readyCheckpoints]);
|
||||
|
||||
const reviewSections = useMemo(
|
||||
() =>
|
||||
buildReviewSectionItems({
|
||||
checkpoints: readyCheckpoints,
|
||||
gitSections: reviewCache.gitSections,
|
||||
turnDiffById: reviewCache.turnDiffById,
|
||||
loadingTurnIds,
|
||||
}),
|
||||
[loadingTurnIds, readyCheckpoints, reviewCache.gitSections, reviewCache.turnDiffById],
|
||||
);
|
||||
|
||||
const selectedSection =
|
||||
reviewSections.find((section) => section.id === reviewCache.selectedSectionId) ??
|
||||
reviewSections[0] ??
|
||||
null;
|
||||
const topContentInset = insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const parsedDiff = useMemo(
|
||||
() =>
|
||||
measureReviewWork("parse-diff", () =>
|
||||
getCachedReviewParsedDiff({
|
||||
threadKey: reviewCache.threadKey,
|
||||
sectionId: selectedSection?.id ?? null,
|
||||
diff: selectedSection?.diff,
|
||||
}),
|
||||
),
|
||||
[reviewCache.threadKey, selectedSection?.diff, selectedSection?.id],
|
||||
);
|
||||
const headerDiffSummary = useMemo(() => formatHeaderDiffSummary(parsedDiff), [parsedDiff]);
|
||||
const NativeReviewDiffView = resolveNativeReviewDiffView()!;
|
||||
const nativeReviewDiffData = useMemo(
|
||||
() => measureReviewWork("build-native-diff-data", () => buildNativeReviewDiffData(parsedDiff)),
|
||||
[parsedDiff],
|
||||
);
|
||||
const nativeReviewDiffTheme = useMemo(
|
||||
() => createNativeReviewDiffTheme(selectedTheme),
|
||||
[selectedTheme],
|
||||
);
|
||||
const nativeRowsJson = useMemo(
|
||||
() => JSON.stringify(nativeReviewDiffData.rows),
|
||||
[nativeReviewDiffData.rows],
|
||||
);
|
||||
const nativeThemeJson = useMemo(
|
||||
() => JSON.stringify(nativeReviewDiffTheme),
|
||||
[nativeReviewDiffTheme],
|
||||
);
|
||||
const nativeStyleJson = useMemo(() => JSON.stringify(NATIVE_REVIEW_DIFF_STYLE), []);
|
||||
const nativeTokensResetKey = useMemo(
|
||||
() =>
|
||||
[
|
||||
reviewCache.threadKey,
|
||||
selectedSection?.id ?? "none",
|
||||
selectedTheme,
|
||||
hashReviewDiffKey(selectedSection?.diff),
|
||||
nativeReviewDiffData.files.length,
|
||||
nativeReviewDiffData.rows.length,
|
||||
].join(":"),
|
||||
[
|
||||
nativeReviewDiffData.files.length,
|
||||
nativeReviewDiffData.rows.length,
|
||||
reviewCache.threadKey,
|
||||
selectedSection?.diff,
|
||||
selectedSection?.id,
|
||||
selectedTheme,
|
||||
],
|
||||
);
|
||||
const pendingReviewCommentCount = useMemo(
|
||||
() => countReviewCommentContexts(draftMessage),
|
||||
[draftMessage],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!selectedSection?.id || parsedDiff.kind !== "files") {
|
||||
return;
|
||||
}
|
||||
|
||||
setLocalExpandedFileIdsBySection((current) => {
|
||||
if (current[selectedSection.id] !== undefined) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
[selectedSection.id]: getValidReviewExpandedFileIds(
|
||||
parsedDiff.files,
|
||||
reviewCache.expandedFileIdsBySection[selectedSection.id],
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
setLocalViewedFileIdsBySection((current) => {
|
||||
if (current[selectedSection.id] !== undefined) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
[selectedSection.id]: reviewCache.viewedFileIdsBySection[selectedSection.id] ?? [],
|
||||
};
|
||||
});
|
||||
}, [
|
||||
parsedDiff,
|
||||
reviewCache.expandedFileIdsBySection,
|
||||
reviewCache.viewedFileIdsBySection,
|
||||
selectedSection?.id,
|
||||
]);
|
||||
|
||||
const expandedFileIds = useMemo(
|
||||
() =>
|
||||
selectedSection?.id && parsedDiff.kind === "files"
|
||||
? getValidReviewExpandedFileIds(
|
||||
parsedDiff.files,
|
||||
localExpandedFileIdsBySection[selectedSection.id],
|
||||
)
|
||||
: [],
|
||||
[localExpandedFileIdsBySection, parsedDiff, selectedSection?.id],
|
||||
);
|
||||
const viewedFileIds = useMemo(
|
||||
() => (selectedSection?.id ? (localViewedFileIdsBySection[selectedSection.id] ?? []) : []),
|
||||
[localViewedFileIdsBySection, selectedSection?.id],
|
||||
);
|
||||
const nativeCollapsedFileIds = useMemo(() => {
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const expandedFileIdSet = new Set(expandedFileIds);
|
||||
return parsedDiff.files
|
||||
.filter((file) => !expandedFileIdSet.has(file.id))
|
||||
.map((file) => file.id);
|
||||
}, [expandedFileIds, parsedDiff]);
|
||||
const nativeCollapsedFileIdsJson = useMemo(
|
||||
() => JSON.stringify(nativeCollapsedFileIds),
|
||||
[nativeCollapsedFileIds],
|
||||
);
|
||||
const nativeViewedFileIdsJson = useMemo(() => JSON.stringify(viewedFileIds), [viewedFileIds]);
|
||||
const loadGitDiffs = useCallback(async () => {
|
||||
if (!cwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
setError("Remote connection is not ready.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingGitDiffs(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await client.git.getReviewDiffs({ cwd });
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewGitSections(reviewCache.threadKey, result.sections);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Failed to load review diffs.");
|
||||
} finally {
|
||||
setLoadingGitDiffs(false);
|
||||
}
|
||||
}, [cwd, environmentId, reviewCache.threadKey]);
|
||||
|
||||
const loadTurnDiff = useCallback(
|
||||
async (checkpoint: OrchestrationCheckpointSummary, force = false) => {
|
||||
if (!threadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sectionId = getReviewSectionIdForCheckpoint(checkpoint);
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewSelectedSectionId(reviewCache.threadKey, sectionId);
|
||||
}
|
||||
|
||||
if (!force && reviewCache.turnDiffById[sectionId] !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(environmentId);
|
||||
if (!client) {
|
||||
setError("Remote connection is not ready.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingTurnIds((current) => ({ ...current, [sectionId]: true }));
|
||||
setError(null);
|
||||
try {
|
||||
const result = await client.orchestration.getTurnDiff({
|
||||
threadId: ThreadId.make(threadId),
|
||||
fromTurnCount: Math.max(0, checkpoint.checkpointTurnCount - 1),
|
||||
toTurnCount: checkpoint.checkpointTurnCount,
|
||||
});
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewTurnDiff(reviewCache.threadKey, sectionId, result.diff);
|
||||
}
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "Failed to load turn diff.");
|
||||
} finally {
|
||||
setLoadingTurnIds((current) => {
|
||||
const next = { ...current };
|
||||
delete next[sectionId];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[environmentId, reviewCache.threadKey, reviewCache.turnDiffById, threadId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void loadGitDiffs();
|
||||
}, [loadGitDiffs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (reviewSections.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fallbackId = getDefaultReviewSectionId(reviewSections);
|
||||
if (
|
||||
reviewCache.threadKey &&
|
||||
(!reviewCache.selectedSectionId ||
|
||||
!reviewSections.some((section) => section.id === reviewCache.selectedSectionId))
|
||||
) {
|
||||
setReviewSelectedSectionId(reviewCache.threadKey, fallbackId);
|
||||
}
|
||||
}, [reviewCache.selectedSectionId, reviewCache.threadKey, reviewSections]);
|
||||
|
||||
useEffect(() => {
|
||||
const latest = readyCheckpoints[0];
|
||||
if (!latest) {
|
||||
return;
|
||||
}
|
||||
|
||||
const latestId = getReviewSectionIdForCheckpoint(latest);
|
||||
if (reviewCache.turnDiffById[latestId] !== undefined || loadingTurnIds[latestId]) {
|
||||
return;
|
||||
}
|
||||
|
||||
void loadTurnDiff(latest);
|
||||
}, [loadTurnDiff, loadingTurnIds, readyCheckpoints, reviewCache.turnDiffById]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedSection || selectedSection.kind !== "turn" || selectedSection.diff !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpoint = checkpointBySectionId[selectedSection.id];
|
||||
if (checkpoint && !loadingTurnIds[selectedSection.id]) {
|
||||
void loadTurnDiff(checkpoint);
|
||||
}
|
||||
}, [checkpointBySectionId, loadTurnDiff, loadingTurnIds, selectedSection]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!reviewCache.threadKey || !selectedSection?.id || parsedDiff.kind !== "files") {
|
||||
return;
|
||||
}
|
||||
|
||||
updateReviewExpandedFileIds(reviewCache.threadKey, selectedSection.id, (existing) => {
|
||||
const validIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
|
||||
if (
|
||||
existing !== undefined &&
|
||||
validIds.length === existing.length &&
|
||||
validIds.every((id, index) => id === existing[index])
|
||||
) {
|
||||
return existing;
|
||||
}
|
||||
return validIds;
|
||||
});
|
||||
}, [parsedDiff, reviewCache.threadKey, selectedSection?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
nativeHighlightedRowIdsRef.current = new Set();
|
||||
nativeVisibleChunkIndexRef.current = 0;
|
||||
nativeVisibleRangeRef.current = { firstRowIndex: 0, lastRowIndex: 80 };
|
||||
setNativeTokensPatchJson(JSON.stringify({ resetKey: nativeTokensResetKey, tokensByRowId: {} }));
|
||||
if (nativeReviewDiffData.rows.length > 0) {
|
||||
setNativeVisibleHighlightRequest((request) => request + 1);
|
||||
}
|
||||
}, [nativeReviewDiffData.rows.length, nativeTokensResetKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (parsedDiff.kind !== "files" || nativeReviewDiffData.rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
const requestRange = nativeVisibleRangeRef.current;
|
||||
const engine: NativeReviewDiffHighlightEngine = "native";
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await highlightNativeReviewDiffVisibleRows({
|
||||
files: nativeReviewDiffData.files,
|
||||
rows: nativeReviewDiffData.rows,
|
||||
scheme: selectedTheme,
|
||||
engine,
|
||||
firstRowIndex: requestRange.firstRowIndex,
|
||||
lastRowIndex: requestRange.lastRowIndex,
|
||||
alreadyHighlightedRowIds: nativeHighlightedRowIdsRef.current,
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (abortController.signal.aborted || result.rowCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const rowId of Object.keys(result.tokensByRowId)) {
|
||||
nativeHighlightedRowIdsRef.current.add(rowId);
|
||||
}
|
||||
|
||||
const chunkIndex = nativeVisibleChunkIndexRef.current;
|
||||
nativeVisibleChunkIndexRef.current += 1;
|
||||
setNativeTokensPatchJson(
|
||||
JSON.stringify({
|
||||
resetKey: nativeTokensResetKey,
|
||||
chunkIndex,
|
||||
fileId: "visible",
|
||||
filePath: "visible rows",
|
||||
language: "diff",
|
||||
lineCount: result.rowCount,
|
||||
durationMs: result.durationMs,
|
||||
tokensByRowId: result.tokensByRowId,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (!abortController.signal.aborted) {
|
||||
logReviewDiffDiagnostic("native visible highlight failed", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => abortController.abort();
|
||||
}, [
|
||||
nativeReviewDiffData.files,
|
||||
nativeReviewDiffData.rows,
|
||||
nativeTokensResetKey,
|
||||
nativeVisibleHighlightRequest,
|
||||
parsedDiff.kind,
|
||||
selectedTheme,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return;
|
||||
}
|
||||
|
||||
markReviewEvent("parsed-diff-ready", {
|
||||
sectionId: selectedSection?.id ?? null,
|
||||
fileCount: parsedDiff.fileCount,
|
||||
additions: parsedDiff.additions,
|
||||
deletions: parsedDiff.deletions,
|
||||
renderedItems: nativeReviewDiffData.rows.length,
|
||||
});
|
||||
logReviewDiffDiagnostic("parsed diff files", {
|
||||
selectedSectionId: selectedSection?.id ?? null,
|
||||
fileCount: parsedDiff.fileCount,
|
||||
renderableFileCount: parsedDiff.files.length,
|
||||
});
|
||||
}, [nativeReviewDiffData.rows.length, parsedDiff, selectedSection?.id]);
|
||||
|
||||
const refreshSelectedSection = useCallback(async () => {
|
||||
if (!selectedSection) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedSection.kind === "turn") {
|
||||
const checkpoint = checkpointBySectionId[selectedSection.id];
|
||||
if (checkpoint) {
|
||||
await loadTurnDiff(checkpoint, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await loadGitDiffs();
|
||||
}, [checkpointBySectionId, loadGitDiffs, loadTurnDiff, selectedSection]);
|
||||
|
||||
const handleToggleExpandedFile = useCallback(
|
||||
(fileId: string) => {
|
||||
if (!selectedSection?.id || parsedDiff.kind !== "files") {
|
||||
return;
|
||||
}
|
||||
|
||||
const sectionId = selectedSection.id;
|
||||
|
||||
setLocalExpandedFileIdsBySection((current) => {
|
||||
const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);
|
||||
const nextIds = currentIds.includes(fileId)
|
||||
? currentIds.filter((id) => id !== fileId)
|
||||
: [...currentIds, fileId];
|
||||
|
||||
return {
|
||||
...current,
|
||||
[sectionId]: nextIds,
|
||||
};
|
||||
});
|
||||
|
||||
if (reviewCache.threadKey) {
|
||||
updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {
|
||||
const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
|
||||
return currentIds.includes(fileId)
|
||||
? currentIds.filter((id) => id !== fileId)
|
||||
: [...currentIds, fileId];
|
||||
});
|
||||
}
|
||||
},
|
||||
[parsedDiff, reviewCache.threadKey, selectedSection?.id],
|
||||
);
|
||||
|
||||
const handleToggleViewedFile = useCallback(
|
||||
(fileId: string) => {
|
||||
if (!selectedSection?.id || parsedDiff.kind !== "files") {
|
||||
return;
|
||||
}
|
||||
|
||||
const sectionId = selectedSection.id;
|
||||
const shouldCollapse = !viewedFileIds.includes(fileId);
|
||||
|
||||
setLocalViewedFileIdsBySection((current) => {
|
||||
const currentIds = current[sectionId] ?? [];
|
||||
const nextIds = currentIds.includes(fileId)
|
||||
? currentIds.filter((id) => id !== fileId)
|
||||
: [...currentIds, fileId];
|
||||
|
||||
return {
|
||||
...current,
|
||||
[sectionId]: nextIds,
|
||||
};
|
||||
});
|
||||
|
||||
if (shouldCollapse) {
|
||||
setLocalExpandedFileIdsBySection((current) => {
|
||||
const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, current[sectionId]);
|
||||
return {
|
||||
...current,
|
||||
[sectionId]: currentIds.filter((id) => id !== fileId),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (reviewCache.threadKey) {
|
||||
updateReviewViewedFileIds(reviewCache.threadKey, sectionId, (existing) => {
|
||||
const currentIds = existing ?? [];
|
||||
return currentIds.includes(fileId)
|
||||
? currentIds.filter((id) => id !== fileId)
|
||||
: [...currentIds, fileId];
|
||||
});
|
||||
|
||||
if (shouldCollapse) {
|
||||
updateReviewExpandedFileIds(reviewCache.threadKey, sectionId, (existing) => {
|
||||
const currentIds = getValidReviewExpandedFileIds(parsedDiff.files, existing);
|
||||
return currentIds.filter((id) => id !== fileId);
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
[parsedDiff, reviewCache.threadKey, selectedSection?.id, viewedFileIds],
|
||||
);
|
||||
|
||||
const handleNativeDebug = useCallback((event: NativeSyntheticEvent<Record<string, unknown>>) => {
|
||||
const payload = event.nativeEvent;
|
||||
const message = payload.message;
|
||||
if (
|
||||
(message === "draw-metrics" || message === "visible-range") &&
|
||||
typeof payload.firstRowIndex === "number" &&
|
||||
typeof payload.lastRowIndex === "number"
|
||||
) {
|
||||
const previousRange = nativeVisibleRangeRef.current;
|
||||
const nextRange = {
|
||||
firstRowIndex: payload.firstRowIndex,
|
||||
lastRowIndex: payload.lastRowIndex,
|
||||
};
|
||||
const movedRows =
|
||||
Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
|
||||
Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
|
||||
|
||||
nativeVisibleRangeRef.current = nextRange;
|
||||
if (movedRows >= 20) {
|
||||
setNativeVisibleHighlightRequest((request) => request + 1);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleNativeToggleFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
if (fileId) {
|
||||
handleToggleExpandedFile(fileId);
|
||||
}
|
||||
},
|
||||
[handleToggleExpandedFile],
|
||||
);
|
||||
|
||||
const handleNativeToggleViewedFile = useCallback(
|
||||
(event: NativeSyntheticEvent<{ readonly fileId?: string }>) => {
|
||||
const { fileId } = event.nativeEvent;
|
||||
if (fileId) {
|
||||
handleToggleViewedFile(fileId);
|
||||
}
|
||||
},
|
||||
[handleToggleViewedFile],
|
||||
);
|
||||
|
||||
const parsedDiffNotice =
|
||||
parsedDiff.kind === "files" || parsedDiff.kind === "raw" ? parsedDiff.notice : null;
|
||||
|
||||
const listHeader = useMemo(() => {
|
||||
const children: ReactElement[] = [];
|
||||
|
||||
if (error) {
|
||||
children.push(
|
||||
<View key="review-error" className="border-b border-border bg-card px-4 py-3">
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">Review unavailable</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">{error}</Text>
|
||||
</View>,
|
||||
);
|
||||
}
|
||||
|
||||
if (parsedDiffNotice) {
|
||||
children.push(<ReviewNotice key="review-notice" notice={parsedDiffNotice} />);
|
||||
}
|
||||
|
||||
if (children.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}, [error, parsedDiffNotice]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
headerTintColor: headerIcon,
|
||||
headerStyle: {
|
||||
backgroundColor: "transparent",
|
||||
},
|
||||
headerTitle: () => (
|
||||
<View style={{ alignItems: "center" }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 18,
|
||||
fontWeight: "900",
|
||||
color: headerForeground,
|
||||
letterSpacing: -0.4,
|
||||
}}
|
||||
>
|
||||
Files Changed
|
||||
</NativeText>
|
||||
<View
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 6,
|
||||
flexWrap: "wrap",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.additions && headerDiffSummary.deletions ? (
|
||||
<>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: "#16a34a",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.additions}
|
||||
</NativeText>
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: "#e11d48",
|
||||
}}
|
||||
>
|
||||
{headerDiffSummary.deletions}
|
||||
</NativeText>
|
||||
{pendingReviewCommentCount > 0 ? (
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: "#b45309",
|
||||
}}
|
||||
>
|
||||
{pendingReviewCommentCount} pending
|
||||
</NativeText>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: headerMuted,
|
||||
}}
|
||||
>
|
||||
{selectedSection?.title ?? "Review changes"}
|
||||
</NativeText>
|
||||
{pendingReviewCommentCount > 0 ? (
|
||||
<NativeText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
color: "#b45309",
|
||||
}}
|
||||
>
|
||||
{pendingReviewCommentCount} pending
|
||||
</NativeText>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
),
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack.Toolbar placement="right">
|
||||
<Stack.Toolbar.Menu icon="ellipsis.circle" title="Select diff" separateBackground>
|
||||
{reviewSections.map((section) => (
|
||||
<Stack.Toolbar.MenuAction
|
||||
key={section.id}
|
||||
icon={section.id === selectedSection?.id ? "checkmark" : "circle"}
|
||||
onPress={() => {
|
||||
if (reviewCache.threadKey) {
|
||||
setReviewSelectedSectionId(reviewCache.threadKey, section.id);
|
||||
}
|
||||
}}
|
||||
subtitle={section.subtitle ?? undefined}
|
||||
>
|
||||
<Stack.Toolbar.Label>{section.title}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
icon="arrow.clockwise"
|
||||
disabled={
|
||||
loadingGitDiffs ||
|
||||
(selectedSection?.kind === "turn" && loadingTurnIds[selectedSection.id] === true)
|
||||
}
|
||||
onPress={() => void refreshSelectedSection()}
|
||||
subtitle="Reload current diff"
|
||||
>
|
||||
<Stack.Toolbar.Label>Refresh</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View className="flex-1 bg-sheet">
|
||||
{selectedSection && parsedDiff.kind === "files" ? (
|
||||
<View
|
||||
className="flex-1"
|
||||
style={{
|
||||
backgroundColor: nativeReviewDiffTheme.background,
|
||||
paddingTop: topContentInset + REVIEW_HEADER_SPACING,
|
||||
}}
|
||||
>
|
||||
{listHeader}
|
||||
<View className="flex-1" collapsable={false}>
|
||||
<NativeReviewDiffView
|
||||
key={`${reviewCache.threadKey}:${selectedSection.id}`}
|
||||
collapsable={false}
|
||||
testID="review-native-diff-view"
|
||||
style={StyleSheet.absoluteFillObject}
|
||||
appearanceScheme={selectedTheme}
|
||||
collapsedFileIdsJson={nativeCollapsedFileIdsJson}
|
||||
contentWidth={NATIVE_REVIEW_DIFF_CONTENT_WIDTH}
|
||||
rowHeight={NATIVE_REVIEW_DIFF_ROW_HEIGHT}
|
||||
rowsJson={nativeRowsJson}
|
||||
styleJson={nativeStyleJson}
|
||||
themeJson={nativeThemeJson}
|
||||
tokensPatchJson={nativeTokensPatchJson}
|
||||
tokensResetKey={nativeTokensResetKey}
|
||||
viewedFileIdsJson={nativeViewedFileIdsJson}
|
||||
onDebug={handleNativeDebug}
|
||||
onToggleFile={handleNativeToggleFile}
|
||||
onToggleViewedFile={handleNativeToggleViewedFile}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
contentInset={{ top: topContentInset }}
|
||||
contentOffset={{ x: 0, y: -topContentInset }}
|
||||
scrollIndicatorInsets={{ top: topContentInset }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={{ flex: 1 }}
|
||||
contentContainerStyle={{
|
||||
paddingTop: REVIEW_HEADER_SPACING,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
}}
|
||||
>
|
||||
{listHeader}
|
||||
{!selectedSection ? (
|
||||
<View className="border-b border-border bg-card px-4 py-5">
|
||||
<Text className="text-[14px] font-t3-bold text-foreground">No review diffs</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">
|
||||
This thread has no ready turn diffs and the worktree diff is empty.
|
||||
</Text>
|
||||
</View>
|
||||
) : selectedSection.isLoading && selectedSection.diff === null ? (
|
||||
<View className="items-center gap-3 border-b border-border bg-card px-4 py-6">
|
||||
<ActivityIndicator size="small" />
|
||||
<Text className="text-[12px] text-foreground-muted">Loading diff…</Text>
|
||||
</View>
|
||||
) : parsedDiff.kind === "empty" ? (
|
||||
<View className="border-b border-border bg-card px-4 py-5">
|
||||
<Text className="text-[14px] font-t3-bold text-foreground">No changes</Text>
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">
|
||||
{selectedSection.subtitle ?? "This diff is empty."}
|
||||
</Text>
|
||||
</View>
|
||||
) : parsedDiff.kind === "raw" ? (
|
||||
<View className="gap-3 border-b border-border bg-card px-4 py-4">
|
||||
<Text className="text-[12px] leading-[18px] text-foreground-muted">
|
||||
{parsedDiff.reason}
|
||||
</Text>
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} bounces={false}>
|
||||
<Text selectable className="font-mono text-[12px] leading-[19px] text-foreground">
|
||||
{parsedDiff.text}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
)}
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildNativeReviewDiffData } from "./nativeReviewDiffAdapter";
|
||||
import { buildReviewParsedDiff } from "./reviewModel";
|
||||
|
||||
describe("buildNativeReviewDiffData", () => {
|
||||
it("maps real parsed file diffs into native rows with headers, hunks, lines, and notices", () => {
|
||||
const parsed = buildReviewParsedDiff(
|
||||
[
|
||||
"diff --git a/apps/demo/src/main.ts b/apps/demo/src/main.ts",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/apps/demo/src/main.ts",
|
||||
"+++ b/apps/demo/src/main.ts",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"-const retryLimit = 2;",
|
||||
"+const retryLimit = 4;",
|
||||
" console.log(retryLimit);",
|
||||
"diff --git a/apps/demo/src/old.ts b/apps/demo/src/new.ts",
|
||||
"similarity index 100%",
|
||||
"rename from apps/demo/src/old.ts",
|
||||
"rename to apps/demo/src/new.ts",
|
||||
"diff --git a/apps/demo/assets/review-logo.png b/apps/demo/assets/review-logo.png",
|
||||
"new file mode 100644",
|
||||
"index 0000000..1111111",
|
||||
"Binary files /dev/null and b/apps/demo/assets/review-logo.png differ",
|
||||
].join("\n"),
|
||||
"native-adapter-test",
|
||||
);
|
||||
|
||||
const data = buildNativeReviewDiffData(parsed);
|
||||
|
||||
expect(data.additions).toBe(1);
|
||||
expect(data.deletions).toBe(1);
|
||||
expect(data.files).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: "apps/demo/src/main.ts",
|
||||
language: "typescript",
|
||||
additions: 1,
|
||||
deletions: 1,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: "apps/demo/src/new.ts",
|
||||
language: "typescript",
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(data.rows).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "file",
|
||||
filePath: "apps/demo/src/main.ts",
|
||||
changeType: "modified",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "hunk",
|
||||
text: "@@ -1,2 +1,2 @@",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "line",
|
||||
change: "delete",
|
||||
content: "const retryLimit = 2;",
|
||||
wordDiffRanges: [{ start: 19, end: 20 }],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "line",
|
||||
change: "add",
|
||||
content: "const retryLimit = 4;",
|
||||
wordDiffRanges: [{ start: 19, end: 20 }],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "file",
|
||||
filePath: "apps/demo/src/new.ts",
|
||||
previousPath: "apps/demo/src/old.ts",
|
||||
changeType: "rename-pure",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "notice",
|
||||
text: "This file was renamed without modifications.",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "notice",
|
||||
text: "Unsupported format. Diff contents are not available.",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
import type {
|
||||
NativeReviewDiffRow,
|
||||
NativeReviewDiffTheme,
|
||||
} from "../debug/native-review-diff/nativeReviewDiffModule";
|
||||
import type {
|
||||
NativeReviewDiffFile,
|
||||
NativeReviewDiffLanguage,
|
||||
} from "../debug/native-review-diff/nativeReviewDiffParser";
|
||||
import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";
|
||||
import { computeWordAltDiffRanges } from "./reviewWordDiffs";
|
||||
import {
|
||||
getReviewFilePreviewState,
|
||||
type ReviewParsedDiff,
|
||||
type ReviewRenderableFile,
|
||||
type ReviewRenderableLineRow,
|
||||
} from "./reviewModel";
|
||||
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
|
||||
const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
|
||||
|
||||
export const NATIVE_REVIEW_DIFF_ROW_HEIGHT = 20;
|
||||
export const NATIVE_REVIEW_DIFF_CONTENT_WIDTH = 2_800;
|
||||
|
||||
export const NATIVE_REVIEW_DIFF_STYLE = {
|
||||
rowHeight: NATIVE_REVIEW_DIFF_ROW_HEIGHT,
|
||||
contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
|
||||
changeBarWidth: 4,
|
||||
gutterWidth: 46,
|
||||
codePadding: 7,
|
||||
textVerticalInset: 2,
|
||||
fileHeaderHeight: 56,
|
||||
fileHeaderHorizontalMargin: 8,
|
||||
fileHeaderVerticalMargin: 6,
|
||||
fileHeaderCornerRadius: 10,
|
||||
fileHeaderHorizontalPadding: 10,
|
||||
fileHeaderPathRightPadding: 118,
|
||||
fileHeaderCountColumnWidth: 38,
|
||||
fileHeaderCountGap: 5,
|
||||
codeFontSize: 11,
|
||||
codeFontWeight: "regular",
|
||||
lineNumberFontSize: 10,
|
||||
lineNumberFontWeight: "regular",
|
||||
hunkFontSize: 11,
|
||||
hunkFontWeight: "medium",
|
||||
fileHeaderFontSize: 11,
|
||||
fileHeaderFontWeight: "semibold",
|
||||
fileHeaderMetaFontSize: 10,
|
||||
fileHeaderMetaFontWeight: "semibold",
|
||||
fileHeaderSubtextFontSize: 11,
|
||||
fileHeaderSubtextFontWeight: "medium",
|
||||
emptyStateFontSize: 12,
|
||||
emptyStateFontWeight: "medium",
|
||||
} as const;
|
||||
|
||||
export interface NativeReviewDiffData {
|
||||
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
|
||||
readonly files: ReadonlyArray<NativeReviewDiffFile>;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
export function createNativeReviewDiffTheme(
|
||||
scheme: TerminalAppearanceScheme,
|
||||
): NativeReviewDiffTheme {
|
||||
const terminalTheme = getPierreTerminalTheme(scheme);
|
||||
const [, terminalRed, , , terminalBlue] = terminalTheme.palette;
|
||||
|
||||
if (scheme === "dark") {
|
||||
return {
|
||||
background: terminalTheme.background,
|
||||
text: terminalTheme.foreground,
|
||||
mutedText: terminalTheme.mutedForeground,
|
||||
headerBackground: terminalTheme.background,
|
||||
border: terminalTheme.border,
|
||||
hunkBackground: "#071f28",
|
||||
hunkText: terminalBlue ?? "#009fff",
|
||||
addBackground: "#0d2f28",
|
||||
deleteBackground: "#391415",
|
||||
addBar: "#00cab1",
|
||||
deleteBar: terminalRed ?? "#ff2e3f",
|
||||
addText: "#5ECC71",
|
||||
deleteText: "#FF6762",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
background: "#ffffff",
|
||||
text: "#070707",
|
||||
mutedText: terminalTheme.mutedForeground,
|
||||
headerBackground: "#ffffff",
|
||||
border: terminalTheme.border,
|
||||
hunkBackground: "#e0f2ff",
|
||||
hunkText: terminalBlue ?? "#009fff",
|
||||
addBackground: "#e5f8f5",
|
||||
deleteBackground: "#ffe6e7",
|
||||
addBar: "#00cab1",
|
||||
deleteBar: terminalRed ?? "#ff2e3f",
|
||||
addText: "#199F43",
|
||||
deleteText: "#D52C36",
|
||||
};
|
||||
}
|
||||
|
||||
function mapChangeType(file: ReviewRenderableFile): NativeReviewDiffRow["changeType"] {
|
||||
switch (file.changeType) {
|
||||
case "change":
|
||||
return "modified";
|
||||
case "new":
|
||||
case "deleted":
|
||||
case "rename-pure":
|
||||
case "rename-changed":
|
||||
return file.changeType;
|
||||
default:
|
||||
return "modified";
|
||||
}
|
||||
}
|
||||
|
||||
function getLanguageForPath(
|
||||
filePath: string,
|
||||
languageHint: string | null,
|
||||
): NativeReviewDiffLanguage {
|
||||
const hinted = languageHint?.toLowerCase();
|
||||
if (hinted === "typescript" || hinted === "tsx" || hinted === "javascript" || hinted === "jsx") {
|
||||
return hinted;
|
||||
}
|
||||
if (hinted === "json" || hinted === "yaml" || hinted === "bash" || hinted === "diff") {
|
||||
return hinted;
|
||||
}
|
||||
|
||||
const normalizedPath = filePath.toLowerCase();
|
||||
if (normalizedPath.endsWith(".tsx")) return "tsx";
|
||||
if (normalizedPath.endsWith(".ts")) return "typescript";
|
||||
if (normalizedPath.endsWith(".jsx")) return "jsx";
|
||||
if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
|
||||
if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
|
||||
if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
|
||||
if (
|
||||
normalizedPath.endsWith(".sh") ||
|
||||
normalizedPath.includes("/bin/") ||
|
||||
normalizedPath.includes("shell")
|
||||
) {
|
||||
return "bash";
|
||||
}
|
||||
return "diff";
|
||||
}
|
||||
|
||||
function createNoticeRow(fileId: string, suffix: string, text: string): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "notice",
|
||||
id: `${fileId}:notice:${suffix}`,
|
||||
fileId,
|
||||
text,
|
||||
};
|
||||
}
|
||||
|
||||
function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
|
||||
if (file.rows.length > 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const previewState = getReviewFilePreviewState(file);
|
||||
if (previewState.kind === "suppressed" && previewState.reason === "non-text") {
|
||||
return [
|
||||
createNoticeRow(file.id, "non-text", "Unsupported format. Diff contents are not available."),
|
||||
];
|
||||
}
|
||||
|
||||
if (file.changeType === "rename-pure") {
|
||||
return [createNoticeRow(file.id, "rename", "This file was renamed without modifications.")];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function trimWordDiffRanges(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
|
||||
return ranges.flatMap((range) => {
|
||||
let start = Math.max(0, range.start);
|
||||
let end = Math.min(content.length, range.end);
|
||||
|
||||
while (start < end && /\s/.test(content[start] ?? "")) {
|
||||
start += 1;
|
||||
}
|
||||
while (end > start && /\s/.test(content[end - 1] ?? "")) {
|
||||
end -= 1;
|
||||
}
|
||||
|
||||
return end > start ? [{ start, end }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonWhitespaceLength(value: string) {
|
||||
return value.replace(/\s/g, "").length;
|
||||
}
|
||||
|
||||
function shouldUseWordDiffRanges(
|
||||
content: string,
|
||||
ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
|
||||
) {
|
||||
if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const meaningfulLength = nonWhitespaceLength(content);
|
||||
if (meaningfulLength === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const highlightedLength = ranges.reduce(
|
||||
(total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
|
||||
0,
|
||||
);
|
||||
return highlightedLength / meaningfulLength <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
|
||||
}
|
||||
|
||||
function addNativeWordDiffRanges(
|
||||
rows: ReadonlyArray<NativeReviewDiffRow>,
|
||||
): ReadonlyArray<NativeReviewDiffRow> {
|
||||
const nextRows = [...rows];
|
||||
let index = 0;
|
||||
|
||||
while (index < nextRows.length) {
|
||||
const deletedRowIndexes: number[] = [];
|
||||
const addedRowIndexes: number[] = [];
|
||||
const fileId = nextRows[index]?.fileId;
|
||||
|
||||
while (
|
||||
nextRows[index]?.kind === "line" &&
|
||||
nextRows[index]?.change === "delete" &&
|
||||
nextRows[index]?.fileId === fileId
|
||||
) {
|
||||
deletedRowIndexes.push(index);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
while (
|
||||
nextRows[index]?.kind === "line" &&
|
||||
nextRows[index]?.change === "add" &&
|
||||
nextRows[index]?.fileId === fileId
|
||||
) {
|
||||
addedRowIndexes.push(index);
|
||||
index += 1;
|
||||
}
|
||||
|
||||
const pairedCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
|
||||
for (let pairIndex = 0; pairIndex < pairedCount; pairIndex += 1) {
|
||||
const deletedRowIndex = deletedRowIndexes[pairIndex];
|
||||
const addedRowIndex = addedRowIndexes[pairIndex];
|
||||
const deletedRow = nextRows[deletedRowIndex];
|
||||
const addedRow = nextRows[addedRowIndex];
|
||||
if (!deletedRow?.content || !addedRow?.content) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const ranges = computeWordAltDiffRanges({
|
||||
deletionLine: deletedRow.content,
|
||||
additionLine: addedRow.content,
|
||||
});
|
||||
const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
|
||||
const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
|
||||
|
||||
if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
|
||||
nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
|
||||
}
|
||||
if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
|
||||
nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
|
||||
}
|
||||
}
|
||||
|
||||
if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) {
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return nextRows;
|
||||
}
|
||||
|
||||
function mapLineRow(
|
||||
file: ReviewRenderableFile,
|
||||
row: ReviewRenderableLineRow,
|
||||
rowIndex: number,
|
||||
): NativeReviewDiffRow {
|
||||
return {
|
||||
kind: "line",
|
||||
id: `${file.id}:line:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
content: row.content,
|
||||
change: row.change,
|
||||
oldLineNumber: row.oldLineNumber,
|
||||
newLineNumber: row.newLineNumber,
|
||||
};
|
||||
}
|
||||
|
||||
function mapFileRows(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
|
||||
const rows: NativeReviewDiffRow[] = [
|
||||
{
|
||||
kind: "file",
|
||||
id: `${file.id}:header`,
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
previousPath: file.previousPath,
|
||||
changeType: mapChangeType(file),
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
},
|
||||
];
|
||||
|
||||
file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
rows.push({
|
||||
kind: "hunk",
|
||||
id: `${file.id}:hunk:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
text: row.context ? `${row.header} ${row.context}` : row.header,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
rows.push(mapLineRow(file, row, rowIndex));
|
||||
});
|
||||
|
||||
rows.push(...noticeRowsForFile(file));
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData {
|
||||
if (parsedDiff.kind !== "files") {
|
||||
return {
|
||||
rows: [],
|
||||
files: [],
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const files = parsedDiff.files.map<NativeReviewDiffFile>((file) => ({
|
||||
id: file.id,
|
||||
path: file.path,
|
||||
language: getLanguageForPath(file.path, file.languageHint),
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
}));
|
||||
const rows = addNativeWordDiffRanges(parsedDiff.files.flatMap(mapFileRows));
|
||||
|
||||
return {
|
||||
rows,
|
||||
files,
|
||||
additions: parsedDiff.additions,
|
||||
deletions: parsedDiff.deletions,
|
||||
};
|
||||
}
|
||||
File renamed without changes.
+14
-6
@@ -1,6 +1,6 @@
|
||||
import { Platform, Text as NativeText, View } from "react-native";
|
||||
|
||||
import { cn } from "../../../lib/cn";
|
||||
import { cn } from "../../lib/cn";
|
||||
|
||||
import type { ReviewRenderableLineRow } from "./reviewModel";
|
||||
import type { ReviewHighlightedToken } from "./shikiReviewHighlighter";
|
||||
@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
export const REVIEW_DIFF_LINE_HEIGHT = 26;
|
||||
const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
|
||||
|
||||
export function renderVisibleWhitespace(value: string): string {
|
||||
const expandedTabs = value.replace(/\t/g, " ");
|
||||
return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
|
||||
@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
|
||||
export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
|
||||
if (props.change === "delete") {
|
||||
return (
|
||||
<View className="w-[5px] self-stretch overflow-hidden">
|
||||
<View className="flex-1 justify-between">
|
||||
{Array.from({ length: 6 }, (_, index) => (
|
||||
<View key={index} className="h-[2px] w-[5px] bg-rose-400" />
|
||||
<View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View>
|
||||
{Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
|
||||
<View key={index}>
|
||||
<View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
|
||||
<View style={{ height: 1 }} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="w-[5px] self-stretch overflow-hidden">
|
||||
<View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
|
||||
</View>
|
||||
);
|
||||
@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
|
||||
if (!props.tokens || props.tokens.length === 0) {
|
||||
return (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
+3
-3
@@ -6,9 +6,9 @@ import {
|
||||
} from "./reviewHighlighterEngine";
|
||||
|
||||
describe("resolveReviewHighlighterEnginePreference", () => {
|
||||
it("defaults invalid values to javascript", () => {
|
||||
expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");
|
||||
expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");
|
||||
it("defaults invalid values to native", () => {
|
||||
expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");
|
||||
expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");
|
||||
});
|
||||
|
||||
it("accepts supported values", () => {
|
||||
+1
-1
@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(
|
||||
case "native":
|
||||
return "native";
|
||||
default:
|
||||
return "javascript";
|
||||
return "native";
|
||||
}
|
||||
}
|
||||
|
||||
+14
-3
@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("flattens expanded files into virtualizable review items", () => {
|
||||
it("flattens expanded file rows into virtualized review items", () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/a.ts",
|
||||
rows: [
|
||||
@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
|
||||
|
||||
expect(items).toEqual([
|
||||
expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
|
||||
expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
|
||||
expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
|
||||
expect.objectContaining({
|
||||
kind: "hunk",
|
||||
fileId: file.id,
|
||||
file,
|
||||
row: file.rows[0],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "line",
|
||||
fileId: file.id,
|
||||
file,
|
||||
row: file.rows[1],
|
||||
lineIndex: 0,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
+12
-4
@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
|
||||
readonly kind: "hunk";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableHunkRow;
|
||||
}
|
||||
|
||||
@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
|
||||
readonly kind: "line";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableLineRow;
|
||||
readonly lineIndex: number;
|
||||
}
|
||||
|
||||
export type ReviewListItem =
|
||||
@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
|
||||
}
|
||||
|
||||
// The flattened review list item model is inspired by pierre/diffs' iterator-first
|
||||
// virtualization architecture, adapted here for React Native and LegendList.
|
||||
// virtualization architecture, adapted here for React Native virtualization.
|
||||
// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
|
||||
// Reference files:
|
||||
// - src/utils/iterateOverDiff.ts
|
||||
@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
|
||||
}
|
||||
}
|
||||
|
||||
file.rows.forEach((row) => {
|
||||
let lineIndex = 0;
|
||||
file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
items.push({
|
||||
kind: "hunk",
|
||||
id: row.id,
|
||||
id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
file,
|
||||
row,
|
||||
});
|
||||
return;
|
||||
@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
|
||||
|
||||
items.push({
|
||||
kind: "line",
|
||||
id: row.id,
|
||||
id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
file,
|
||||
row,
|
||||
lineIndex,
|
||||
});
|
||||
lineIndex += 1;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
interface ReviewPerformanceLike {
|
||||
readonly now?: () => number;
|
||||
readonly mark?: (name: string) => void;
|
||||
readonly measure?: (name: string, startMark: string, endMark: string) => void;
|
||||
readonly clearMarks?: (name?: string) => void;
|
||||
readonly clearMeasures?: (name?: string) => void;
|
||||
}
|
||||
|
||||
const REVIEW_PERF_PREFIX = "t3.review";
|
||||
let reviewPerfSequence = 0;
|
||||
|
||||
function getPerformance(): ReviewPerformanceLike | null {
|
||||
const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;
|
||||
return candidate ?? null;
|
||||
}
|
||||
|
||||
export function isReviewPerfEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
export function measureReviewWork<T>(name: string, callback: () => T): T {
|
||||
if (!isReviewPerfEnabled()) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
const perf = getPerformance();
|
||||
const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
|
||||
const startMark = `${marker}.start`;
|
||||
const endMark = `${marker}.end`;
|
||||
const startedAt = perf?.now?.() ?? Date.now();
|
||||
|
||||
perf?.mark?.(startMark);
|
||||
try {
|
||||
return callback();
|
||||
} finally {
|
||||
const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
|
||||
perf?.mark?.(endMark);
|
||||
perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
|
||||
perf?.clearMarks?.(startMark);
|
||||
perf?.clearMarks?.(endMark);
|
||||
console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
|
||||
}
|
||||
}
|
||||
|
||||
export async function measureReviewAsyncWork<T>(
|
||||
name: string,
|
||||
callback: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (!isReviewPerfEnabled()) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
const perf = getPerformance();
|
||||
const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
|
||||
const startMark = `${marker}.start`;
|
||||
const endMark = `${marker}.end`;
|
||||
const startedAt = perf?.now?.() ?? Date.now();
|
||||
|
||||
perf?.mark?.(startMark);
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
|
||||
perf?.mark?.(endMark);
|
||||
perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
|
||||
perf?.clearMarks?.(startMark);
|
||||
perf?.clearMarks?.(endMark);
|
||||
console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
|
||||
}
|
||||
}
|
||||
|
||||
export function markReviewEvent(name: string, details?: Record<string, unknown>): void {
|
||||
if (!isReviewPerfEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);
|
||||
if (details) {
|
||||
console.log(`[review-perf] ${name}`, details);
|
||||
return;
|
||||
}
|
||||
console.log(`[review-perf] ${name}`);
|
||||
}
|
||||
+27
-2
@@ -3,8 +3,8 @@ import { useAtomValue } from "@effect/atom-react";
|
||||
import { EnvironmentId, ThreadId, type GitReviewDiffSection } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { scopedThreadKey } from "../../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../../state/atom-registry";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { buildReviewParsedDiff, type ReviewParsedDiff } from "./reviewModel";
|
||||
|
||||
const EMPTY_GIT_REVIEW_SECTIONS = Object.freeze<ReadonlyArray<GitReviewDiffSection>>([]);
|
||||
@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string
|
||||
),
|
||||
);
|
||||
|
||||
const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
|
||||
Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),
|
||||
),
|
||||
);
|
||||
|
||||
const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>
|
||||
Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {
|
||||
? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)
|
||||
: EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
|
||||
);
|
||||
const viewedFileIdsBySection = useAtomValue(
|
||||
threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
|
||||
);
|
||||
|
||||
return {
|
||||
threadKey,
|
||||
@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {
|
||||
selectedSectionId,
|
||||
expandedFileIdsBySection,
|
||||
revealedLargeFileIdsBySection,
|
||||
viewedFileIdsBySection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(
|
||||
});
|
||||
}
|
||||
|
||||
export function updateReviewViewedFileIds(
|
||||
threadKey: string,
|
||||
sectionId: string,
|
||||
update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,
|
||||
): void {
|
||||
const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);
|
||||
const current = appAtomRegistry.get(atom);
|
||||
const nextValue = update(current[sectionId]);
|
||||
appAtomRegistry.set(atom, {
|
||||
...current,
|
||||
[sectionId]: nextValue,
|
||||
});
|
||||
}
|
||||
|
||||
export function getCachedReviewParsedDiff(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly sectionId: string | null;
|
||||
File renamed without changes.
File renamed without changes.
+15
-7
@@ -24,7 +24,7 @@ function makeRenderableFile(
|
||||
describe("highlightReviewFile", () => {
|
||||
it("preserves one highlighted token row per diff line even without trailing newlines", async () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/example.test.ts",
|
||||
path: "apps/mobile/src/example.txt",
|
||||
additionLines: [
|
||||
'const items = ["a"];',
|
||||
'expect(items).toEqual(["a"]);',
|
||||
@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {
|
||||
const highlighted = await highlightReviewFile(file, "light");
|
||||
|
||||
expect(highlighted.additionLines).toHaveLength(file.additionLines.length);
|
||||
expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);
|
||||
expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);
|
||||
expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);
|
||||
expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);
|
||||
expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[0],
|
||||
);
|
||||
expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[1],
|
||||
);
|
||||
expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[2],
|
||||
);
|
||||
expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[3],
|
||||
);
|
||||
});
|
||||
|
||||
it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/example-inline-diff.test.ts",
|
||||
path: "apps/mobile/src/example-inline-diff.txt",
|
||||
additionLines: ["const after = 2;"],
|
||||
deletionLines: ["const before = 1;"],
|
||||
rows: [
|
||||
@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {
|
||||
it("falls back to plain tokens for very long lines", async () => {
|
||||
const longLine = `const value = "${"a".repeat(1_100)}";`;
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/example-long-line.ts",
|
||||
path: "apps/mobile/src/example-long-line.txt",
|
||||
additionLines: [longLine],
|
||||
rows: [
|
||||
{
|
||||
+304
-22
@@ -1,5 +1,14 @@
|
||||
import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
|
||||
import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
|
||||
import bashLanguage from "@shikijs/langs/bash";
|
||||
import javascriptLanguage from "@shikijs/langs/javascript";
|
||||
import jsonLanguage from "@shikijs/langs/json";
|
||||
import jsxLanguage from "@shikijs/langs/jsx";
|
||||
import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import githubDarkDefault from "@shikijs/themes/github-dark-default";
|
||||
import githubLightDefault from "@shikijs/themes/github-light-default";
|
||||
import { getFiletypeFromFileName } from "@pierre/diffs/utils";
|
||||
|
||||
import {
|
||||
@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode
|
||||
import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
|
||||
|
||||
export type ReviewDiffTheme = "light" | "dark";
|
||||
export type { ReviewHighlighterEngine };
|
||||
|
||||
export interface ReviewHighlightedToken {
|
||||
content: string;
|
||||
@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {
|
||||
readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
|
||||
}
|
||||
|
||||
export interface ReviewHighlightFileProgress {
|
||||
readonly highlightedFile: ReviewHighlightedFile;
|
||||
readonly complete: boolean;
|
||||
readonly highlightedLineCount: number;
|
||||
}
|
||||
|
||||
const SHIKI_THEME_NAME_BY_SCHEME = {
|
||||
light: "github-light-default",
|
||||
dark: "github-dark-default",
|
||||
} as const;
|
||||
const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =
|
||||
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";
|
||||
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??
|
||||
(process.env.NODE_ENV === "test" ? "javascript" : "native");
|
||||
const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(
|
||||
REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
|
||||
);
|
||||
@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF
|
||||
false,
|
||||
);
|
||||
const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;
|
||||
const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;
|
||||
const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();
|
||||
const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();
|
||||
const loadedLanguages = new Set<string>(["text"]);
|
||||
const REVIEW_INITIAL_LANGUAGE_MODULES = [
|
||||
bashLanguage,
|
||||
javascriptLanguage,
|
||||
jsonLanguage,
|
||||
jsxLanguage,
|
||||
tsxLanguage,
|
||||
typescriptLanguage,
|
||||
yamlLanguage,
|
||||
] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
|
||||
const loadedLanguages = new Set<string>([
|
||||
"text",
|
||||
"bash",
|
||||
"javascript",
|
||||
"json",
|
||||
"jsx",
|
||||
"tsx",
|
||||
"typescript",
|
||||
"yaml",
|
||||
]);
|
||||
const languageLoadingPromises = new Map<string, Promise<boolean>>();
|
||||
const languageImports: Partial<Record<string, () => Promise<unknown>>> = {
|
||||
javascript: () => import("@shikijs/langs/javascript"),
|
||||
@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {
|
||||
|
||||
function waitForNextFrame(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
if (typeof requestAnimationFrame === "function") {
|
||||
requestAnimationFrame(() => resolve());
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(resolve, 0);
|
||||
});
|
||||
}
|
||||
|
||||
async function getHighlighter(): Promise<HighlighterCore> {
|
||||
if (!highlighterPromise) {
|
||||
const configuredHighlighterPromise = Promise.all([
|
||||
import("@shikijs/themes/github-light-default"),
|
||||
import("@shikijs/themes/github-dark-default"),
|
||||
]).then(async ([lightThemeModule, darkThemeModule]) => {
|
||||
const configuredHighlighterPromise = (async () => {
|
||||
let nativeEngineAvailable = false;
|
||||
|
||||
logReviewHighlighterDiagnostic("initializing", {
|
||||
@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,
|
||||
});
|
||||
|
||||
const themes = [lightThemeModule.default, darkThemeModule.default];
|
||||
const themes = [githubLightDefault, githubDarkDefault];
|
||||
|
||||
if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {
|
||||
try {
|
||||
const nativeEngineModule = await import("react-native-shiki-engine");
|
||||
logReviewHighlighterDiagnostic("imported react-native-shiki-engine");
|
||||
nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();
|
||||
logReviewHighlighterDiagnostic("checked native engine availability", {
|
||||
nativeEngineAvailable,
|
||||
@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
logReviewHighlighterDiagnostic("creating native regex engine");
|
||||
const highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: [],
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: nativeEngineModule.createNativeEngine(),
|
||||
});
|
||||
logReviewHighlighterDiagnostic("using native engine");
|
||||
@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
);
|
||||
const highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: [],
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
logReviewHighlighterDiagnostic("using javascript engine", {
|
||||
@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
highlighter,
|
||||
engine,
|
||||
};
|
||||
});
|
||||
})();
|
||||
|
||||
highlighterPromise = configuredHighlighterPromise
|
||||
.then((result) => result.highlighter)
|
||||
@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh
|
||||
return activeHighlighterEnginePromise ?? Promise.resolve("javascript");
|
||||
}
|
||||
|
||||
export async function prepareReviewHighlighter(): Promise<void> {
|
||||
await getHighlighter();
|
||||
}
|
||||
|
||||
export async function prepareReviewHighlighterLanguages(
|
||||
languages: ReadonlyArray<string>,
|
||||
): Promise<void> {
|
||||
const highlighter = await getHighlighter();
|
||||
await Promise.all(
|
||||
languages.map(async (language) => {
|
||||
const candidate = resolveLanguageAlias(language);
|
||||
if (candidate === "text" || !(candidate in languageImports)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await loadSingleLanguage(highlighter, candidate);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function resolveLanguageAlias(language: string): string {
|
||||
const normalized = language.toLowerCase();
|
||||
return languageAliases[normalized] ?? normalized;
|
||||
}
|
||||
|
||||
function resolveLoadedLanguageFromPath(
|
||||
path: string,
|
||||
languageHint: string | null = null,
|
||||
): string | null {
|
||||
const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
|
||||
if (!detectedLanguage) {
|
||||
return "text";
|
||||
}
|
||||
|
||||
const candidate = resolveLanguageAlias(detectedLanguage);
|
||||
if (candidate === "text" || candidate === "ansi") {
|
||||
return "text";
|
||||
}
|
||||
|
||||
if (!(candidate in languageImports)) {
|
||||
return "text";
|
||||
}
|
||||
|
||||
return loadedLanguages.has(candidate) ? candidate : null;
|
||||
}
|
||||
|
||||
async function loadSingleLanguage(
|
||||
highlighter: HighlighterCore,
|
||||
language: string,
|
||||
@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(
|
||||
path: string,
|
||||
languageHint: string | null = null,
|
||||
): Promise<string> {
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);
|
||||
if (loadedLanguage) {
|
||||
return loadedLanguage;
|
||||
}
|
||||
|
||||
const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
|
||||
if (!detectedLanguage) {
|
||||
return "text";
|
||||
@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(
|
||||
return "text";
|
||||
}
|
||||
|
||||
if (loadedLanguages.has(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const highlighter = await getHighlighter();
|
||||
const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));
|
||||
const loaded = await loadSingleLanguage(highlighter, candidate);
|
||||
if (!loaded) {
|
||||
return "text";
|
||||
}
|
||||
@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(
|
||||
}
|
||||
|
||||
async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {
|
||||
return resolveLanguageFromPath(file.path, file.languageHint);
|
||||
return (
|
||||
resolveLoadedLanguageFromPath(file.path, file.languageHint) ??
|
||||
(await resolveLanguageFromPath(file.path, file.languageHint))
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeHighlightedLines(
|
||||
@@ -399,6 +478,18 @@ function normalizeHighlightedLines(
|
||||
);
|
||||
}
|
||||
|
||||
function makePlainHighlightedLines(
|
||||
lines: ReadonlyArray<string>,
|
||||
): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {
|
||||
return lines.map((line) => [
|
||||
{
|
||||
content: stripTrailingNewline(line),
|
||||
color: null,
|
||||
fontStyle: null,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function applyWordAltDiffHighlightsToFile(
|
||||
file: ReviewRenderableFile,
|
||||
highlighted: ReviewHighlightedFile,
|
||||
@@ -594,6 +685,67 @@ async function highlightLines(
|
||||
return highlightedLines;
|
||||
}
|
||||
|
||||
async function highlightPatchLinesInChunks(input: {
|
||||
readonly lines: ReadonlyArray<string>;
|
||||
readonly language: string;
|
||||
readonly theme: string;
|
||||
readonly onChunk: (
|
||||
startIndex: number,
|
||||
tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,
|
||||
) => void;
|
||||
}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
|
||||
if (input.lines.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const highlighter = await getHighlighter();
|
||||
const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
|
||||
for (
|
||||
let startIndex = 0;
|
||||
startIndex < input.lines.length;
|
||||
startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE
|
||||
) {
|
||||
const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);
|
||||
const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
const tokenizableLines: string[] = [];
|
||||
const tokenizableIndexes: number[] = [];
|
||||
|
||||
lineChunk.forEach((line, index) => {
|
||||
const strippedLine = stripTrailingNewline(line);
|
||||
if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {
|
||||
chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];
|
||||
return;
|
||||
}
|
||||
|
||||
tokenizableIndexes.push(index);
|
||||
tokenizableLines.push(strippedLine);
|
||||
});
|
||||
|
||||
if (tokenizableLines.length > 0) {
|
||||
const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), {
|
||||
lang: input.language,
|
||||
theme: input.theme,
|
||||
});
|
||||
const normalizedTokenLines = normalizeHighlightedLines(tokenLines);
|
||||
|
||||
tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {
|
||||
chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];
|
||||
});
|
||||
}
|
||||
|
||||
const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);
|
||||
highlightedLines.push(...completedChunk);
|
||||
input.onChunk(startIndex, completedChunk);
|
||||
|
||||
if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {
|
||||
await waitForNextFrame();
|
||||
}
|
||||
}
|
||||
|
||||
return highlightedLines;
|
||||
}
|
||||
|
||||
function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {
|
||||
return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;
|
||||
}
|
||||
@@ -667,7 +819,28 @@ export async function highlightReviewFile(
|
||||
deletionLineCount: file.deletionLines.length,
|
||||
rowCount: file.rows.length,
|
||||
});
|
||||
const language = await resolveLanguage(file);
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
|
||||
const language = loadedLanguage ?? (await resolveLanguage(file));
|
||||
if (language === "text") {
|
||||
const highlighted = applyWordAltDiffHighlightsToFile(file, {
|
||||
additionLines: makePlainHighlightedLines(file.additionLines),
|
||||
deletionLines: makePlainHighlightedLines(file.deletionLines),
|
||||
});
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
storeResolvedHighlightedFile(cacheKey, highlighted);
|
||||
}
|
||||
logReviewHighlighterDiagnostic("file highlight complete", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
language,
|
||||
highlightedAdditionLineCount: highlighted.additionLines.length,
|
||||
highlightedDeletionLineCount: highlighted.deletionLines.length,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
return highlighted;
|
||||
}
|
||||
|
||||
const additionLines = await highlightLines(
|
||||
joinPatchLines(file.additionLines),
|
||||
language,
|
||||
@@ -707,6 +880,113 @@ export async function highlightReviewFile(
|
||||
});
|
||||
}
|
||||
|
||||
export async function streamHighlightReviewFile(
|
||||
file: ReviewRenderableFile,
|
||||
theme: ReviewDiffTheme,
|
||||
onProgress: (progress: ReviewHighlightFileProgress) => void,
|
||||
): Promise<ReviewHighlightedFile> {
|
||||
const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];
|
||||
const cacheKey = getHighlightCacheKey(file, theme);
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
const resolved = resolvedHighlightCache.get(cacheKey);
|
||||
if (resolved) {
|
||||
onProgress({
|
||||
highlightedFile: resolved,
|
||||
complete: true,
|
||||
highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,
|
||||
});
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
logReviewHighlighterDiagnostic("file stream highlight start", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
additionLineCount: file.additionLines.length,
|
||||
deletionLineCount: file.deletionLines.length,
|
||||
rowCount: file.rows.length,
|
||||
});
|
||||
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
|
||||
const language = loadedLanguage ?? (await resolveLanguage(file));
|
||||
if (language === "text") {
|
||||
const highlighted = applyWordAltDiffHighlightsToFile(file, {
|
||||
additionLines: makePlainHighlightedLines(file.additionLines),
|
||||
deletionLines: makePlainHighlightedLines(file.deletionLines),
|
||||
});
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
storeResolvedHighlightedFile(cacheKey, highlighted);
|
||||
}
|
||||
onProgress({
|
||||
highlightedFile: highlighted,
|
||||
complete: true,
|
||||
highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
|
||||
});
|
||||
logReviewHighlighterDiagnostic("file stream highlight complete", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
language,
|
||||
highlightedAdditionLineCount: highlighted.additionLines.length,
|
||||
highlightedDeletionLineCount: highlighted.deletionLines.length,
|
||||
highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
return highlighted;
|
||||
}
|
||||
|
||||
const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
let highlightedLineCount = 0;
|
||||
|
||||
await highlightPatchLinesInChunks({
|
||||
lines: file.additionLines,
|
||||
language,
|
||||
theme: shikiTheme,
|
||||
onChunk: (startIndex, tokens) => {
|
||||
tokens.forEach((lineTokens, index) => {
|
||||
additionLines[startIndex + index] = lineTokens;
|
||||
});
|
||||
highlightedLineCount += tokens.length;
|
||||
},
|
||||
});
|
||||
await waitForNextFrame();
|
||||
await highlightPatchLinesInChunks({
|
||||
lines: file.deletionLines,
|
||||
language,
|
||||
theme: shikiTheme,
|
||||
onChunk: (startIndex, tokens) => {
|
||||
tokens.forEach((lineTokens, index) => {
|
||||
deletionLines[startIndex + index] = lineTokens;
|
||||
});
|
||||
highlightedLineCount += tokens.length;
|
||||
},
|
||||
});
|
||||
|
||||
const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
storeResolvedHighlightedFile(cacheKey, highlighted);
|
||||
}
|
||||
onProgress({
|
||||
highlightedFile: highlighted,
|
||||
complete: true,
|
||||
highlightedLineCount,
|
||||
});
|
||||
logReviewHighlighterDiagnostic("file stream highlight complete", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
language,
|
||||
highlightedAdditionLineCount: highlighted.additionLines.length,
|
||||
highlightedDeletionLineCount: highlighted.deletionLines.length,
|
||||
highlightedLineCount,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
return highlighted;
|
||||
}
|
||||
|
||||
export async function highlightReviewSelectedLines(input: {
|
||||
readonly filePath: string;
|
||||
readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
|
||||
@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {
|
||||
return {};
|
||||
}
|
||||
|
||||
const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);
|
||||
const language =
|
||||
loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
|
||||
const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
|
||||
const additionLikeLines = input.lines
|
||||
.filter((line) => line.change !== "delete")
|
||||
+15
-4
@@ -1,4 +1,4 @@
|
||||
import { memo, useCallback } from "react";
|
||||
import { memo, useCallback, useEffect } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
ScrollView,
|
||||
@@ -14,9 +14,10 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { resolveNativeTerminalSurfaceView } from "./nativeTerminalModule";
|
||||
import {
|
||||
buildGhosttyThemeConfig,
|
||||
getGitHubTerminalTheme,
|
||||
getPierreTerminalTheme,
|
||||
type TerminalTheme,
|
||||
} from "./terminalTheme";
|
||||
import { terminalDebugLog } from "./terminalDebugLog";
|
||||
|
||||
interface TerminalInputEvent {
|
||||
readonly data: string;
|
||||
@@ -53,7 +54,7 @@ function estimateGridSize(input: {
|
||||
const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: TerminalSurfaceProps) {
|
||||
const fontSize = props.fontSize ?? 12;
|
||||
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const theme = props.theme ?? getGitHubTerminalTheme(appearanceScheme);
|
||||
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
|
||||
const statusLabel = props.isRunning
|
||||
? "Native terminal unavailable. Using text fallback."
|
||||
: "Open terminal to start a shell.";
|
||||
@@ -165,9 +166,19 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props: Ter
|
||||
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
|
||||
const fontSize = props.fontSize ?? 12;
|
||||
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const theme = props.theme ?? getGitHubTerminalTheme(appearanceScheme);
|
||||
const theme = props.theme ?? getPierreTerminalTheme(appearanceScheme);
|
||||
const { onInput, onResize } = props;
|
||||
const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
|
||||
const hasNativeSurface = Boolean(NativeTerminalSurfaceView);
|
||||
|
||||
useEffect(() => {
|
||||
terminalDebugLog("native:surface", {
|
||||
terminalKey: props.terminalKey,
|
||||
native: hasNativeSurface,
|
||||
bufferLen: props.buffer.length,
|
||||
isRunning: props.isRunning,
|
||||
});
|
||||
}, [hasNativeSurface, props.buffer.length, props.isRunning, props.terminalKey]);
|
||||
const handleNativeInput = useCallback(
|
||||
(event: NativeSyntheticEvent<TerminalInputEvent>) => {
|
||||
onInput(event.nativeEvent.data);
|
||||
+39
-34
@@ -1,17 +1,22 @@
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { getEnvironmentClient } from "../../state/use-remote-environment-registry";
|
||||
import { useTerminalSession, useTerminalSessionTarget } from "../../state/use-terminal-session";
|
||||
import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface";
|
||||
import { hasNativeTerminalSurface } from "../../native/terminal/nativeTerminalModule";
|
||||
import {
|
||||
attachTerminalSession,
|
||||
useTerminalSession,
|
||||
useTerminalSessionTarget,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
import { hasNativeTerminalSurface } from "./nativeTerminalModule";
|
||||
import { terminalDebugLog } from "./terminalDebugLog";
|
||||
|
||||
interface ThreadTerminalPanelProps {
|
||||
readonly environmentId: string;
|
||||
readonly threadId: string;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly cwd: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly visible: boolean;
|
||||
@@ -36,31 +41,41 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
});
|
||||
const hasOpenedRef = useRef(false);
|
||||
|
||||
const terminalKey = useMemo(
|
||||
() => `${props.environmentId}:${props.threadId}:${terminalId}`,
|
||||
[props.environmentId, props.threadId, terminalId],
|
||||
);
|
||||
const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
|
||||
useEffect(() => {
|
||||
hasOpenedRef.current = false;
|
||||
}, [terminalKey]);
|
||||
|
||||
const openTerminal = useCallback(async () => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client) {
|
||||
if (!props.visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
await client.terminal.open({
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
if (!client) {
|
||||
terminalDebugLog("panel:attach-skip", {
|
||||
reason: "no-environment-client",
|
||||
environmentId: props.environmentId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
terminalDebugLog("panel:attach", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cwd: props.cwd,
|
||||
worktreePath: props.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
});
|
||||
|
||||
return attachTerminalSession({
|
||||
environmentId: props.environmentId,
|
||||
client,
|
||||
terminal: {
|
||||
threadId: props.threadId,
|
||||
terminalId,
|
||||
cwd: props.cwd,
|
||||
worktreePath: props.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
lastGridSize.cols,
|
||||
@@ -69,20 +84,10 @@ export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.worktreePath,
|
||||
props.visible,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.visible || hasOpenedRef.current || terminal.status !== "closed") {
|
||||
return;
|
||||
}
|
||||
|
||||
hasOpenedRef.current = true;
|
||||
void openTerminal().catch(() => {
|
||||
hasOpenedRef.current = false;
|
||||
});
|
||||
}, [openTerminal, props.visible, terminal.status]);
|
||||
|
||||
const handleInput = useCallback(
|
||||
(data: string) => {
|
||||
const client = getEnvironmentClient(props.environmentId);
|
||||
+44
-2
@@ -12,6 +12,8 @@ describe("resolveTerminalRouteBootstrap", () => {
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "term-2",
|
||||
currentTerminalStatus: "closed",
|
||||
hasCurrentTerminalHydration: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "redirect",
|
||||
@@ -19,7 +21,7 @@ describe("resolveTerminalRouteBootstrap", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("hydrates the current running terminal instead of skipping open", () => {
|
||||
it("hydrates the current running terminal when client state is not hydrated yet", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
@@ -28,13 +30,15 @@ describe("resolveTerminalRouteBootstrap", () => {
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "default",
|
||||
currentTerminalStatus: "running",
|
||||
hasCurrentTerminalHydration: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "open",
|
||||
});
|
||||
});
|
||||
|
||||
it("opens explicit terminal routes once so they replay existing history", () => {
|
||||
it("opens explicit terminal routes when the session still needs hydration", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
@@ -43,6 +47,8 @@ describe("resolveTerminalRouteBootstrap", () => {
|
||||
requestedTerminalId: "term-2",
|
||||
currentTerminalId: "term-2",
|
||||
runningTerminalId: "term-2",
|
||||
currentTerminalStatus: "running",
|
||||
hasCurrentTerminalHydration: false,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "open",
|
||||
@@ -58,6 +64,42 @@ describe("resolveTerminalRouteBootstrap", () => {
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "default",
|
||||
currentTerminalStatus: "running",
|
||||
hasCurrentTerminalHydration: true,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "idle",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays idle when the current running terminal is already hydrated in client state", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
hasWorkspaceRoot: true,
|
||||
hasOpened: false,
|
||||
requestedTerminalId: null,
|
||||
currentTerminalId: "default",
|
||||
runningTerminalId: "default",
|
||||
currentTerminalStatus: "running",
|
||||
hasCurrentTerminalHydration: true,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "idle",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays idle for explicit running terminal routes that already have hydrated output", () => {
|
||||
expect(
|
||||
resolveTerminalRouteBootstrap({
|
||||
hasThread: true,
|
||||
hasWorkspaceRoot: true,
|
||||
hasOpened: false,
|
||||
requestedTerminalId: "term-2",
|
||||
currentTerminalId: "term-2",
|
||||
runningTerminalId: "term-2",
|
||||
currentTerminalStatus: "running",
|
||||
hasCurrentTerminalHydration: true,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "idle",
|
||||
+477
-100
@@ -1,35 +1,53 @@
|
||||
import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
EnvironmentId,
|
||||
type TerminalAttachStreamEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { KnownTerminalSession } from "@t3tools/client-runtime";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { useAnimatedKeyboard, useAnimatedStyle } from "react-native-reanimated";
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { LoadingScreen } from "../../components/LoadingScreen";
|
||||
import { buildThreadTerminalRoutePath } from "../../lib/routes";
|
||||
import { buildThreadTerminalNavigation } from "../../lib/routes";
|
||||
import {
|
||||
getEnvironmentClient,
|
||||
useRemoteEnvironmentState,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
terminalSessionManager,
|
||||
attachTerminalSession,
|
||||
useKnownTerminalSessions,
|
||||
useTerminalSession,
|
||||
useTerminalSessionTarget,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { TerminalSurface } from "../../native/terminal/NativeTerminalSurface";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
import { getPierreTerminalTheme } from "./terminalTheme";
|
||||
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
|
||||
import { terminalDebugLog } from "./terminalDebugLog";
|
||||
import {
|
||||
getTerminalBufferReplayKey,
|
||||
getTerminalSurfaceReplayBuffer,
|
||||
TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
|
||||
} from "./terminalBufferReplay";
|
||||
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
|
||||
import { resolveTerminalOpenLocation } from "./terminalLaunchContext";
|
||||
import {
|
||||
resolveTerminalOpenLocation,
|
||||
stagePendingTerminalLaunch,
|
||||
takePendingTerminalLaunch,
|
||||
} from "./terminalLaunchContext";
|
||||
import {
|
||||
basename,
|
||||
buildTerminalMenuSessions,
|
||||
getTerminalLabel,
|
||||
getTerminalStatusLabel,
|
||||
nextTerminalId,
|
||||
nextOpenTerminalId,
|
||||
resolveTerminalSessionLabel,
|
||||
type TerminalMenuSession,
|
||||
} from "./terminalMenu";
|
||||
import {
|
||||
DEFAULT_TERMINAL_FONT_SIZE,
|
||||
@@ -38,6 +56,12 @@ import {
|
||||
TERMINAL_FONT_SIZE_STEP,
|
||||
normalizeTerminalFontSize,
|
||||
} from "./terminalPreferences";
|
||||
import {
|
||||
cacheTerminalFontSize,
|
||||
cacheTerminalGridSize,
|
||||
getCachedTerminalFontSize,
|
||||
getCachedTerminalGridSize,
|
||||
} from "./terminalUiState";
|
||||
|
||||
const DEFAULT_TERMINAL_COLS = 80;
|
||||
const DEFAULT_TERMINAL_ROWS = 24;
|
||||
@@ -55,13 +79,6 @@ type TerminalToolbarAction =
|
||||
readonly modifier: PendingModifier;
|
||||
};
|
||||
|
||||
interface TerminalMenuSession {
|
||||
readonly terminalId: string;
|
||||
readonly cwd: string | null;
|
||||
readonly status: "starting" | "running" | "exited" | "error" | "closed";
|
||||
readonly updatedAt: string | null;
|
||||
}
|
||||
|
||||
function getTerminalStatusTone(input: {
|
||||
readonly status: TerminalMenuSession["status"];
|
||||
readonly hasRunningSubprocess?: boolean;
|
||||
@@ -154,9 +171,30 @@ function applyCtrlModifier(input: string): string {
|
||||
return input;
|
||||
}
|
||||
|
||||
function withAlpha(hexColor: string, alpha: string): string {
|
||||
return /^#[0-9a-f]{6}$/i.test(hexColor) ? `${hexColor}${alpha}` : hexColor;
|
||||
}
|
||||
|
||||
function pickRunningTerminalSessionForBootstrap(
|
||||
sessions: ReadonlyArray<KnownTerminalSession>,
|
||||
): KnownTerminalSession | null {
|
||||
const running = sessions.filter(
|
||||
(session) => session.state.status === "running" || session.state.status === "starting",
|
||||
);
|
||||
if (running.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ??
|
||||
running[0] ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export function ThreadTerminalRouteScreen() {
|
||||
const router = useRouter();
|
||||
const keyboard = useAnimatedKeyboard();
|
||||
const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
|
||||
const { isLoadingSavedConnection } = useRemoteEnvironmentState();
|
||||
const params = useLocalSearchParams<{
|
||||
environmentId?: string | string[];
|
||||
@@ -166,51 +204,147 @@ export function ThreadTerminalRouteScreen() {
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const routeThreadIdRaw = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentId = routeEnvironmentIdRaw
|
||||
? EnvironmentId.make(routeEnvironmentIdRaw)
|
||||
: null;
|
||||
const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
|
||||
const requestedTerminalId = firstRouteParam(params.terminalId);
|
||||
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const cachedFontSize = getCachedTerminalFontSize();
|
||||
const cachedRouteGridSize =
|
||||
routeEnvironmentId && routeThreadId
|
||||
? getCachedTerminalGridSize({
|
||||
environmentId: routeEnvironmentId,
|
||||
threadId: routeThreadId,
|
||||
terminalId,
|
||||
})
|
||||
: null;
|
||||
const knownSessions = useKnownTerminalSessions({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
});
|
||||
const [lastGridSize, setLastGridSize] = useState({
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
});
|
||||
const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);
|
||||
const [fontSize, setFontSize] = useState(DEFAULT_TERMINAL_FONT_SIZE);
|
||||
const [lastGridSize, setLastGridSize] = useState(
|
||||
cachedRouteGridSize ?? {
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
},
|
||||
);
|
||||
const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
|
||||
const hasOpenedRef = useRef(false);
|
||||
const hasLoadedFontPreferenceRef = useRef(false);
|
||||
|
||||
const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const attachStreamLogCountRef = useRef(0);
|
||||
const firstNonEmptyBufferLoggedRef = useRef(false);
|
||||
const lastBufferReplayKeyRef = useRef<string | null>(null);
|
||||
const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
|
||||
const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState(
|
||||
cachedFontSize !== null,
|
||||
);
|
||||
/** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */
|
||||
const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);
|
||||
const [pendingModifierState, setPendingModifierState] = useState<{
|
||||
readonly terminalId: string;
|
||||
readonly value: PendingModifier | null;
|
||||
}>({
|
||||
terminalId,
|
||||
value: null,
|
||||
});
|
||||
const target = useTerminalSessionTarget({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
terminalId,
|
||||
});
|
||||
const terminal = useTerminalSession(target);
|
||||
const terminalKey = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
|
||||
: terminalId,
|
||||
[selectedThread, terminalId],
|
||||
const terminalKey = selectedThread
|
||||
? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
|
||||
: terminalId;
|
||||
const bufferReplayKey = useMemo(
|
||||
() => getTerminalBufferReplayKey({ terminalKey, fontSize }),
|
||||
[fontSize, terminalKey],
|
||||
);
|
||||
if (lastBufferReplayKeyRef.current === null) {
|
||||
lastBufferReplayKeyRef.current = bufferReplayKey;
|
||||
}
|
||||
const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
|
||||
buffer: terminal.buffer,
|
||||
replayKey: bufferReplayKey,
|
||||
readyReplayKey: readyBufferReplayKey,
|
||||
});
|
||||
const isRunning = terminal.status === "running" || terminal.status === "starting";
|
||||
const cwd = terminal.snapshot?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
terminalDebugLog("surface:props", {
|
||||
terminalKey,
|
||||
atomBufferLen: terminal.buffer.length,
|
||||
surfaceBufferLen: terminalSurfaceBuffer.length,
|
||||
replayKey: bufferReplayKey,
|
||||
readyReplayKey: readyBufferReplayKey,
|
||||
status: terminal.status,
|
||||
version: terminal.version,
|
||||
});
|
||||
}, [
|
||||
bufferReplayKey,
|
||||
readyBufferReplayKey,
|
||||
terminal.buffer.length,
|
||||
terminal.status,
|
||||
terminal.version,
|
||||
terminalKey,
|
||||
terminalSurfaceBuffer.length,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
terminalDebugLog("session:status", {
|
||||
terminalKey,
|
||||
status: terminal.status,
|
||||
error: terminal.error,
|
||||
summary: terminal.summary?.cwd ?? null,
|
||||
bufferLen: terminal.buffer.length,
|
||||
version: terminal.version,
|
||||
});
|
||||
}, [
|
||||
terminal.buffer.length,
|
||||
terminal.error,
|
||||
terminal.status,
|
||||
terminal.summary?.cwd,
|
||||
terminal.version,
|
||||
terminalKey,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {
|
||||
return;
|
||||
}
|
||||
firstNonEmptyBufferLoggedRef.current = true;
|
||||
terminalDebugLog("session:first-nonempty-buffer", {
|
||||
terminalKey,
|
||||
length: terminal.buffer.length,
|
||||
preview: terminal.buffer.slice(0, 160),
|
||||
});
|
||||
}, [terminal.buffer, terminal.buffer.length, terminalKey]);
|
||||
const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
|
||||
const hostPlatform = useMemo(
|
||||
() => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
|
||||
[selectedEnvironmentConnection?.environmentLabel],
|
||||
);
|
||||
const runningSession = useMemo(
|
||||
() =>
|
||||
knownSessions.find(
|
||||
(session) => session.state.status === "running" || session.state.status === "starting",
|
||||
) ?? null,
|
||||
() => pickRunningTerminalSessionForBootstrap(knownSessions),
|
||||
[knownSessions],
|
||||
);
|
||||
const activeKnownSession = useMemo(
|
||||
() => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
|
||||
[knownSessions, terminalId],
|
||||
);
|
||||
|
||||
const terminalAttachLaunchHintsRef = useRef({
|
||||
terminalSummary: terminal.summary,
|
||||
activeKnownSummary: activeKnownSession?.state.summary ?? null,
|
||||
});
|
||||
terminalAttachLaunchHintsRef.current = {
|
||||
terminalSummary: terminal.summary,
|
||||
activeKnownSummary: activeKnownSession?.state.summary ?? null,
|
||||
};
|
||||
|
||||
const terminalStatusTone = useMemo(
|
||||
() =>
|
||||
getTerminalStatusTone({
|
||||
@@ -219,6 +353,9 @@ export function ThreadTerminalRouteScreen() {
|
||||
}),
|
||||
[terminal.hasRunningSubprocess, terminal.status],
|
||||
);
|
||||
const terminalTheme = getPierreTerminalTheme(appearanceScheme);
|
||||
const pendingModifier =
|
||||
pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
|
||||
const headerTitle = useMemo(() => {
|
||||
const topLineParts = [
|
||||
selectedEnvironmentConnection?.environmentLabel ?? null,
|
||||
@@ -278,6 +415,8 @@ export function ThreadTerminalRouteScreen() {
|
||||
terminalId,
|
||||
cwd: cwd ?? null,
|
||||
status: terminal.status,
|
||||
hasRunningSubprocess: terminal.hasRunningSubprocess,
|
||||
displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
|
||||
updatedAt: terminal.updatedAt,
|
||||
},
|
||||
}),
|
||||
@@ -285,55 +424,209 @@ export function ThreadTerminalRouteScreen() {
|
||||
cwd,
|
||||
knownSessions,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.hasRunningSubprocess,
|
||||
terminal.summary,
|
||||
terminal.status,
|
||||
terminal.updatedAt,
|
||||
terminalId,
|
||||
],
|
||||
);
|
||||
|
||||
const openTerminal = useCallback(async () => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
const logAttachStreamEvent = useCallback((event: TerminalAttachStreamEvent) => {
|
||||
const n = ++attachStreamLogCountRef.current;
|
||||
if (event.type === "output" && n > 32 && n % 64 !== 0) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "snapshot") {
|
||||
terminalDebugLog("attach:stream", {
|
||||
n,
|
||||
type: event.type,
|
||||
status: event.snapshot.status,
|
||||
historyLen: event.snapshot.history.length,
|
||||
cwd: event.snapshot.cwd,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.type === "output") {
|
||||
terminalDebugLog("attach:stream", { n, type: event.type, dataLen: event.data.length });
|
||||
return;
|
||||
}
|
||||
terminalDebugLog("attach:stream", { n, type: event.type });
|
||||
}, []);
|
||||
|
||||
const attachTerminal = useCallback(() => {
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
terminalDebugLog("attach:abort", { reason: "no-thread-or-workspace" });
|
||||
return null;
|
||||
}
|
||||
|
||||
const client = getEnvironmentClient(selectedThread.environmentId);
|
||||
if (!client) {
|
||||
return;
|
||||
terminalDebugLog("attach:abort", {
|
||||
reason: "no-environment-client",
|
||||
environmentId: selectedThread.environmentId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const launchLocation = resolveTerminalOpenLocation({
|
||||
terminalSnapshot: terminal.snapshot,
|
||||
activeSessionSnapshot: activeKnownSession?.state.snapshot ?? null,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
});
|
||||
|
||||
const snapshot = await client.terminal.open({
|
||||
const pendingLaunchTarget = {
|
||||
environmentId: selectedThread.environmentId,
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
cwd: launchLocation.cwd,
|
||||
worktreePath: launchLocation.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
});
|
||||
};
|
||||
const pendingLaunch = takePendingTerminalLaunch(pendingLaunchTarget);
|
||||
let initialInputSent = false;
|
||||
|
||||
terminalSessionManager.syncSnapshot({ environmentId: selectedThread.environmentId }, snapshot);
|
||||
try {
|
||||
const launchLocation = pendingLaunch
|
||||
? {
|
||||
cwd: pendingLaunch.cwd,
|
||||
worktreePath: pendingLaunch.worktreePath,
|
||||
}
|
||||
: resolveTerminalOpenLocation({
|
||||
terminalLocation: terminalAttachLaunchHintsRef.current.terminalSummary,
|
||||
activeSessionLocation: terminalAttachLaunchHintsRef.current.activeKnownSummary,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
});
|
||||
|
||||
terminalDebugLog("attach:start", {
|
||||
terminalId,
|
||||
threadId: selectedThread.id,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
cwd: launchLocation.cwd,
|
||||
worktreePath: launchLocation.worktreePath,
|
||||
});
|
||||
|
||||
return attachTerminalSession({
|
||||
environmentId: selectedThread.environmentId,
|
||||
client,
|
||||
terminal: {
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
cwd: launchLocation.cwd,
|
||||
worktreePath: launchLocation.worktreePath,
|
||||
cols: lastGridSize.cols,
|
||||
rows: lastGridSize.rows,
|
||||
env: pendingLaunch?.env,
|
||||
},
|
||||
onEvent: logAttachStreamEvent,
|
||||
onSnapshot: () => {
|
||||
if (!pendingLaunch?.initialInput || initialInputSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
initialInputSent = true;
|
||||
void client.terminal.write({
|
||||
threadId: selectedThread.id,
|
||||
terminalId,
|
||||
data: pendingLaunch.initialInput,
|
||||
});
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
terminalDebugLog("attach:error", {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
if (pendingLaunch) {
|
||||
stagePendingTerminalLaunch({
|
||||
target: pendingLaunchTarget,
|
||||
launch: pendingLaunch,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}, [
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
activeKnownSession?.state.snapshot,
|
||||
logAttachStreamEvent,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThread,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminal.snapshot,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
const attachTerminalRef = useRef(attachTerminal);
|
||||
attachTerminalRef.current = attachTerminal;
|
||||
const selectedThreadRef = useRef(selectedThread);
|
||||
selectedThreadRef.current = selectedThread;
|
||||
const selectedThreadProjectBootstrapRef = useRef(selectedThreadProject);
|
||||
selectedThreadProjectBootstrapRef.current = selectedThreadProject;
|
||||
const runningSessionRef = useRef(runningSession);
|
||||
runningSessionRef.current = runningSession;
|
||||
const terminalBootstrapRef = useRef({
|
||||
status: terminal.status,
|
||||
bufferLen: terminal.buffer.length,
|
||||
});
|
||||
terminalBootstrapRef.current = {
|
||||
status: terminal.status,
|
||||
bufferLen: terminal.buffer.length,
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
hasOpenedRef.current = false;
|
||||
attachStreamLogCountRef.current = 0;
|
||||
firstNonEmptyBufferLoggedRef.current = false;
|
||||
}, [terminalKey]);
|
||||
|
||||
const clearBufferReplayTimer = useCallback(() => {
|
||||
if (bufferReplayTimerRef.current !== null) {
|
||||
clearTimeout(bufferReplayTimerRef.current);
|
||||
bufferReplayTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const scheduleBufferReplayReady = useCallback(() => {
|
||||
clearBufferReplayTimer();
|
||||
const replayKey = bufferReplayKey;
|
||||
terminalDebugLog("replay:schedule-ready", {
|
||||
replayKey,
|
||||
delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
|
||||
});
|
||||
bufferReplayTimerRef.current = setTimeout(() => {
|
||||
bufferReplayTimerRef.current = null;
|
||||
setReadyBufferReplayKey(replayKey);
|
||||
terminalDebugLog("replay:ready", { replayKey });
|
||||
}, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
|
||||
}, [bufferReplayKey, clearBufferReplayTimer]);
|
||||
|
||||
useEffect(() => {
|
||||
if (lastBufferReplayKeyRef.current === bufferReplayKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastBufferReplayKeyRef.current = bufferReplayKey;
|
||||
clearBufferReplayTimer();
|
||||
setReadyBufferReplayKey(null);
|
||||
}, [bufferReplayKey, clearBufferReplayTimer]);
|
||||
|
||||
useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!routeEnvironmentId || !routeThreadId) {
|
||||
setLastGridSize({
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setLastGridSize(
|
||||
getCachedTerminalGridSize({
|
||||
environmentId: routeEnvironmentId,
|
||||
threadId: routeThreadId,
|
||||
terminalId,
|
||||
}) ?? {
|
||||
cols: DEFAULT_TERMINAL_COLS,
|
||||
rows: DEFAULT_TERMINAL_ROWS,
|
||||
},
|
||||
);
|
||||
setHasMeasuredSurface(true);
|
||||
}, [routeEnvironmentId, routeThreadId, terminalId]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
@@ -343,15 +636,15 @@ export function ThreadTerminalRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
setFontSize(normalizeTerminalFontSize(preferences.terminalFontSize));
|
||||
hasLoadedFontPreferenceRef.current = true;
|
||||
setFontSize(cacheTerminalFontSize(preferences.terminalFontSize));
|
||||
setHasResolvedFontPreference(true);
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
hasLoadedFontPreferenceRef.current = true;
|
||||
setHasResolvedFontPreference(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
@@ -360,51 +653,91 @@ export function ThreadTerminalRouteScreen() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasLoadedFontPreferenceRef.current) {
|
||||
if (!hasResolvedFontPreference) {
|
||||
return;
|
||||
}
|
||||
|
||||
cacheTerminalFontSize(fontSize);
|
||||
void savePreferencesPatch({
|
||||
terminalFontSize: normalizeTerminalFontSize(fontSize),
|
||||
});
|
||||
}, [fontSize]);
|
||||
}, [fontSize, hasResolvedFontPreference]);
|
||||
|
||||
// Subscribes `terminal.attach` once per route+terminal until thread/env/attach args change.
|
||||
// Use refs for `attachTerminal` / `selectedThread` / `runningSession`: their identities change when
|
||||
// unrelated store updates (e.g. terminal buffer) re-render the parent, which was firing cleanup
|
||||
// → detach immediately after the first snapshot.
|
||||
useEffect(() => {
|
||||
if (!hasResolvedFontPreference || !hasMeasuredSurface) {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = selectedThreadRef.current;
|
||||
const project = selectedThreadProjectBootstrapRef.current;
|
||||
const running = runningSessionRef.current;
|
||||
const termSnap = terminalBootstrapRef.current;
|
||||
|
||||
const bootstrapAction = resolveTerminalRouteBootstrap({
|
||||
hasThread: selectedThread !== null,
|
||||
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
||||
hasThread: thread !== null,
|
||||
hasWorkspaceRoot: Boolean(project?.workspaceRoot),
|
||||
hasOpened: hasOpenedRef.current,
|
||||
requestedTerminalId,
|
||||
currentTerminalId: terminalId,
|
||||
runningTerminalId: runningSession?.target.terminalId ?? null,
|
||||
runningTerminalId: running?.target.terminalId ?? null,
|
||||
currentTerminalStatus: termSnap.status,
|
||||
// Metadata summary (cwd/status) is not scrollback. Only `terminal.attach` fills `buffer`;
|
||||
// treating summary as "hydrated" skipped attach while status was running → empty surface.
|
||||
hasCurrentTerminalHydration: termSnap.bufferLen > 0,
|
||||
});
|
||||
if (bootstrapAction.kind === "idle" || !selectedThread) {
|
||||
if (bootstrapAction.kind !== "idle") {
|
||||
terminalDebugLog("bootstrap:action", {
|
||||
kind: bootstrapAction.kind,
|
||||
hasOpenedBefore: hasOpenedRef.current,
|
||||
hasHydration: termSnap.bufferLen > 0,
|
||||
terminalStatus: termSnap.status,
|
||||
bufLen: termSnap.bufferLen,
|
||||
});
|
||||
}
|
||||
if (bootstrapAction.kind === "idle" || !thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (bootstrapAction.kind === "redirect") {
|
||||
router.replace(buildThreadTerminalRoutePath(selectedThread, bootstrapAction.terminalId));
|
||||
router.replace(buildThreadTerminalNavigation(thread, bootstrapAction.terminalId));
|
||||
return;
|
||||
}
|
||||
|
||||
hasOpenedRef.current = true;
|
||||
void openTerminal().catch(() => {
|
||||
try {
|
||||
const detach = attachTerminalRef.current();
|
||||
terminalDebugLog("bootstrap:subscribe", { hasDetach: Boolean(detach) });
|
||||
if (!detach) {
|
||||
hasOpenedRef.current = false;
|
||||
return;
|
||||
}
|
||||
return () => {
|
||||
detach();
|
||||
hasOpenedRef.current = false;
|
||||
terminalDebugLog("bootstrap:unsubscribe");
|
||||
};
|
||||
} catch (error) {
|
||||
hasOpenedRef.current = false;
|
||||
});
|
||||
terminalDebugLog("bootstrap:attach-threw", {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
}, [
|
||||
openTerminal,
|
||||
hasMeasuredSurface,
|
||||
hasResolvedFontPreference,
|
||||
requestedTerminalId,
|
||||
router,
|
||||
runningSession,
|
||||
selectedThread,
|
||||
selectedThread?.environmentId,
|
||||
selectedThread?.id,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setPendingModifier(null);
|
||||
}, [terminalId]);
|
||||
|
||||
const writeInput = useCallback(
|
||||
(data: string) => {
|
||||
if (!selectedThread || !isRunning) {
|
||||
@@ -432,20 +765,39 @@ export function ThreadTerminalRouteScreen() {
|
||||
}
|
||||
|
||||
if (pendingModifier === "ctrl") {
|
||||
setPendingModifier(null);
|
||||
setPendingModifierState({ terminalId, value: null });
|
||||
writeInput(applyCtrlModifier(data));
|
||||
} else if (pendingModifier === "meta") {
|
||||
setPendingModifier(null);
|
||||
setPendingModifierState({ terminalId, value: null });
|
||||
writeInput(`\u001b${data}`);
|
||||
} else {
|
||||
writeInput(data);
|
||||
}
|
||||
},
|
||||
[pendingModifier, writeInput],
|
||||
[pendingModifier, terminalId, writeInput],
|
||||
);
|
||||
|
||||
const handleResize = useCallback(
|
||||
(size: { readonly cols: number; readonly rows: number }) => {
|
||||
terminalDebugLog("native:onResize", {
|
||||
cols: size.cols,
|
||||
rows: size.rows,
|
||||
terminalKey,
|
||||
});
|
||||
setHasMeasuredSurface(true);
|
||||
if (readyBufferReplayKey !== bufferReplayKey) {
|
||||
scheduleBufferReplayReady();
|
||||
}
|
||||
if (routeEnvironmentId && routeThreadId) {
|
||||
cacheTerminalGridSize(
|
||||
{
|
||||
environmentId: routeEnvironmentId,
|
||||
threadId: routeThreadId,
|
||||
terminalId,
|
||||
},
|
||||
size,
|
||||
);
|
||||
}
|
||||
if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
|
||||
return;
|
||||
}
|
||||
@@ -467,7 +819,19 @@ export function ThreadTerminalRouteScreen() {
|
||||
rows: size.rows,
|
||||
});
|
||||
},
|
||||
[isRunning, lastGridSize.cols, lastGridSize.rows, selectedThread, terminalId],
|
||||
[
|
||||
isRunning,
|
||||
lastGridSize.cols,
|
||||
lastGridSize.rows,
|
||||
bufferReplayKey,
|
||||
readyBufferReplayKey,
|
||||
routeEnvironmentId,
|
||||
routeThreadId,
|
||||
scheduleBufferReplayReady,
|
||||
selectedThread,
|
||||
terminalId,
|
||||
terminalKey,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSelectTerminal = useCallback(
|
||||
@@ -476,7 +840,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
return;
|
||||
}
|
||||
|
||||
router.replace(buildThreadTerminalRoutePath(selectedThread, nextTerminalId));
|
||||
router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
|
||||
},
|
||||
[router, selectedThread, terminalId],
|
||||
);
|
||||
@@ -487,16 +851,19 @@ export function ThreadTerminalRouteScreen() {
|
||||
}
|
||||
|
||||
router.replace(
|
||||
buildThreadTerminalRoutePath(
|
||||
buildThreadTerminalNavigation(
|
||||
selectedThread,
|
||||
nextTerminalId(terminalMenuSessions.map((session) => session.terminalId)),
|
||||
nextOpenTerminalId({
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
activeRouteTerminalId: terminalId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}, [router, selectedThread, terminalMenuSessions]);
|
||||
}, [router, selectedThread, terminalId, terminalMenuSessions]);
|
||||
|
||||
const adjustFontSize = useCallback((delta: number) => {
|
||||
setTimeout(() => {
|
||||
setFontSize((current) => normalizeTerminalFontSize(current + delta));
|
||||
setFontSize((current) => cacheTerminalFontSize(current + delta));
|
||||
}, 0);
|
||||
}, []);
|
||||
|
||||
@@ -511,11 +878,17 @@ export function ThreadTerminalRouteScreen() {
|
||||
const handleToolbarActionPress = useCallback(
|
||||
(action: TerminalToolbarAction) => {
|
||||
if (action.kind === "modifier") {
|
||||
setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
|
||||
setPendingModifierState((current) => ({
|
||||
terminalId,
|
||||
value:
|
||||
(current.terminalId === terminalId ? current.value : null) === action.modifier
|
||||
? null
|
||||
: action.modifier,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
setPendingModifier(null);
|
||||
setPendingModifierState({ terminalId, value: null });
|
||||
if (pendingModifier === "ctrl") {
|
||||
writeInput(applyCtrlModifier(action.data));
|
||||
} else if (pendingModifier === "meta") {
|
||||
@@ -524,7 +897,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
writeInput(action.data);
|
||||
}
|
||||
},
|
||||
[pendingModifier, writeInput],
|
||||
[pendingModifier, terminalId, writeInput],
|
||||
);
|
||||
|
||||
if (!selectedThread) {
|
||||
@@ -561,8 +934,8 @@ export function ThreadTerminalRouteScreen() {
|
||||
headerBackButtonDisplayMode: "minimal",
|
||||
headerBackTitle: "",
|
||||
headerShadowVisible: false,
|
||||
headerStyle: { backgroundColor: "#0a0a0a" },
|
||||
headerTintColor: "#f5f5f5",
|
||||
headerStyle: { backgroundColor: terminalTheme.background },
|
||||
headerTintColor: terminalTheme.foreground,
|
||||
headerTitleAlign: "center",
|
||||
title: "",
|
||||
headerTitle: () => (
|
||||
@@ -576,7 +949,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
<RNText
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: "#f5f5f5",
|
||||
color: terminalTheme.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 13,
|
||||
lineHeight: 16,
|
||||
@@ -588,7 +961,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
style={{
|
||||
color: "#8f8f94",
|
||||
color: terminalTheme.mutedForeground,
|
||||
fontFamily: "Menlo",
|
||||
fontSize: 11,
|
||||
lineHeight: 14,
|
||||
@@ -645,7 +1018,7 @@ export function ThreadTerminalRouteScreen() {
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
<Stack.Toolbar.Label>{getTerminalLabel(session.terminalId)}</Stack.Toolbar.Label>
|
||||
<Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
|
||||
</Stack.Toolbar.MenuAction>
|
||||
))}
|
||||
<Stack.Toolbar.MenuAction
|
||||
@@ -658,10 +1031,10 @@ export function ThreadTerminalRouteScreen() {
|
||||
</Stack.Toolbar.Menu>
|
||||
</Stack.Toolbar>
|
||||
|
||||
<View style={{ flex: 1, backgroundColor: "#050505" }}>
|
||||
<View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
|
||||
<Animated.View style={[{ flex: 1 }, terminalContainerAnimatedStyle]}>
|
||||
<TerminalSurface
|
||||
buffer={terminal.buffer}
|
||||
buffer={terminalSurfaceBuffer}
|
||||
fontSize={fontSize}
|
||||
isRunning={isRunning}
|
||||
onInput={handleInput}
|
||||
@@ -674,8 +1047,8 @@ export function ThreadTerminalRouteScreen() {
|
||||
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: "#0a0a0a",
|
||||
borderTopColor: "rgba(255,255,255,0.08)",
|
||||
backgroundColor: terminalTheme.background,
|
||||
borderTopColor: terminalTheme.border,
|
||||
borderTopWidth: 1,
|
||||
minHeight: TERMINAL_ACCESSORY_HEIGHT,
|
||||
paddingBottom: 4,
|
||||
@@ -698,11 +1071,13 @@ export function ThreadTerminalRouteScreen() {
|
||||
style={({ pressed }) => ({
|
||||
alignItems: "center",
|
||||
backgroundColor: active
|
||||
? "rgba(74, 222, 128, 0.18)"
|
||||
? withAlpha(terminalTheme.palette[10] ?? terminalTheme.foreground, "2e")
|
||||
: pressed
|
||||
? "rgba(255,255,255,0.12)"
|
||||
: "rgba(255,255,255,0.06)",
|
||||
borderColor: active ? "rgba(74, 222, 128, 0.36)" : "rgba(255,255,255,0.08)",
|
||||
? withAlpha(terminalTheme.foreground, "1f")
|
||||
: withAlpha(terminalTheme.foreground, "12"),
|
||||
borderColor: active
|
||||
? withAlpha(terminalTheme.palette[10] ?? terminalTheme.foreground, "52")
|
||||
: terminalTheme.border,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
justifyContent: "center",
|
||||
@@ -713,7 +1088,9 @@ export function ThreadTerminalRouteScreen() {
|
||||
>
|
||||
<RNText
|
||||
style={{
|
||||
color: active ? "#bbf7d0" : "#f5f5f5",
|
||||
color: active
|
||||
? (terminalTheme.palette[10] ?? terminalTheme.foreground)
|
||||
: terminalTheme.foreground,
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
fontWeight: "700",
|
||||
File renamed without changes.
Loaded 100 of 719 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user