diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40c84a71ad84b..d5b44721c7a04 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: # open: if the diff cannot be resolved, everything runs. changes: name: Changes - runs-on: blacksmith-2vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 5 outputs: typecheck: ${{ steps.detect.outputs.typecheck }} @@ -64,7 +64,7 @@ jobs: contents: read id-token: write name: Lint - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -126,7 +126,7 @@ jobs: name: Build and Typecheck needs: changes if: ${{ !cancelled() && (needs.changes.outputs.build != 'false' || needs.changes.outputs.typecheck != 'false') }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -281,7 +281,7 @@ jobs: name: Test needs: changes if: ${{ !cancelled() && needs.changes.outputs.test != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -371,7 +371,7 @@ jobs: name: Test Web ${{ matrix.shard }} needs: changes if: ${{ !cancelled() && needs.changes.outputs.test_web != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 strategy: fail-fast: false @@ -433,7 +433,7 @@ jobs: contents: read id-token: write name: Test Server ${{ matrix.shard }} - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} # Shards take 2-5 minutes. When the shared task cache throttles reads, each # failed fetch stalls vp for 15-90s, which pushed shards past 10 minutes. timeout-minutes: 20 @@ -563,7 +563,7 @@ jobs: name: Rust needs: changes if: ${{ !cancelled() && needs.changes.outputs.rust != 'false' }} - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -597,7 +597,7 @@ jobs: name: Mobile Native Static Analysis needs: changes if: ${{ !cancelled() && needs.changes.outputs.mobile_native != 'false' }} - runs-on: blacksmith-6vcpu-macos-27 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-6vcpu-macos-27' || 'macos-latest' }} timeout-minutes: 10 steps: - name: Checkout @@ -630,7 +630,7 @@ jobs: name: Release Smoke needs: changes if: ${{ !cancelled() && needs.changes.outputs.release_smoke != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 15 steps: - name: Checkout @@ -670,7 +670,7 @@ jobs: mobile_native_static_analysis, release_smoke, ] - runs-on: blacksmith-2vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 5 steps: - name: Require every job to pass diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index da779c2783d4c..e23b5632f2953 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -26,8 +26,9 @@ jobs: deploy_relay: name: Deploy production relay # A manual run from another branch would deploy that branch to production. - if: github.repository == 'pingdotgg/t3code' && github.ref == 'refs/heads/main' - runs-on: blacksmith-8vcpu-ubuntu-2404 + # A fork opts in with the repository variable RELAY_DEPLOY_ENABLED=true. + if: (github.repository == 'pingdotgg/t3code' || vars.RELAY_DEPLOY_ENABLED == 'true') && github.ref == 'refs/heads/main' + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 15 environment: name: production @@ -36,6 +37,11 @@ jobs: PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }} AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }} RELAY_DOMAIN: ${{ vars.RELAY_DOMAIN }} + # Forks on free plans: external (e.g. Neon), off, off. Unset keeps + # PlanetScale, Axiom, and Cloudflare rate limiting. + RELAY_DATABASE_PROVIDER: ${{ vars.RELAY_DATABASE_PROVIDER }} + RELAY_OBSERVABILITY: ${{ vars.RELAY_OBSERVABILITY }} + RELAY_RATE_LIMIT: ${{ vars.RELAY_RATE_LIMIT }} RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }} RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }} RELAY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_TUNNEL_CLEANUP_MODE }} @@ -44,6 +50,8 @@ jobs: RELAY_WARNING_NOTIFIER_ID: ${{ vars.RELAY_WARNING_NOTIFIER_ID }} CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }} + # A fork without an APNs key sets APNS_ENABLED=false. + APNS_ENABLED: ${{ vars.APNS_ENABLED || 'true' }} APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }} APNS_TEAM_ID: ${{ vars.APNS_TEAM_ID }} APNS_KEY_ID: ${{ vars.APNS_KEY_ID }} @@ -67,6 +75,12 @@ jobs: args: - --filter=t3code-relay... + - name: Migrate external relay database + if: vars.RELAY_DATABASE_PROVIDER == 'external' + run: vp run --filter t3code-relay migrate:external-db + env: + RELAY_DATABASE_URL: ${{ secrets.RELAY_DATABASE_URL }} + - name: Deploy production relay stage run: vp run --filter t3code-relay deploy --stage prod --yes --no-input ${{ inputs.force && '--force' || '' }} env: @@ -77,6 +91,7 @@ jobs: PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }} PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }} AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} + RELAY_DATABASE_URL: ${{ secrets.RELAY_DATABASE_URL }} CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }} FCM_SERVICE_ACCOUNT: ${{ secrets.FCM_SERVICE_ACCOUNT }} diff --git a/.github/workflows/desktop-macos-preview.yml b/.github/workflows/desktop-macos-preview.yml index 2c54052ea66d5..ad10990e94faf 100644 --- a/.github/workflows/desktop-macos-preview.yml +++ b/.github/workflows/desktop-macos-preview.yml @@ -29,7 +29,7 @@ concurrency: jobs: build: name: Build preview JS bundle - if: github.event.label.name == 'preview:mac' + if: github.repository == 'pingdotgg/t3code' && github.event.label.name == 'preview:mac' runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 30 steps: diff --git a/.github/workflows/fork-release.yml b/.github/workflows/fork-release.yml new file mode 100644 index 0000000000000..a9797959c7c0f --- /dev/null +++ b/.github/workflows/fork-release.yml @@ -0,0 +1,361 @@ +name: Fork release + +# A fork's own releases. A version tag builds standalone Linux CLI archives with SHA256SUMS and +# desktop apps (Linux, Windows x64 and, with signing, macOS) with their updater feeds into a draft release; publishing the draft is the +# approval. `t3 update`, auto-updating services and desktop apps never see drafts, so nothing +# reaches an install before that. macOS builds only once the Apple signing secrets exist: +# Squirrel.Mac refuses unsigned updates. +on: + push: + tags: + - "v*.*.*" + - "!v*-nightly.*" + - "!v*-preview.*" + +permissions: + contents: read + +concurrency: + group: fork-release-${{ github.ref_name }} + cancel-in-progress: false + +jobs: + build: + name: Linux ${{ matrix.arch }} + needs: [config] + strategy: + matrix: + include: + - arch: x64 + runner: ubuntu-24.04 + # Built natively: the single executable cannot be cross-built for arm64 page sizes. + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + env: + T3CODE_APP_SCHEME: ${{ vars.T3CODE_APP_SCHEME }} + T3CODE_APP_NAME: ${{ vars.T3CODE_APP_NAME }} + T3CODE_HOSTED_APP_URL: ${{ vars.T3CODE_HOSTED_APP_URL }} + # T3 Connect's public values; unset leaves Connect off, as in every build without them. + T3CODE_CLERK_PUBLISHABLE_KEY: ${{ vars.T3CODE_CLERK_PUBLISHABLE_KEY }} + T3CODE_CLERK_JWT_TEMPLATE: ${{ vars.T3CODE_CLERK_JWT_TEMPLATE }} + T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID }} + T3CODE_RELAY_URL: ${{ vars.T3CODE_RELAY_URL }} + RELEASE_REPOSITORY: ${{ github.repository }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + # .repos/ holds vendored references with gitlinks that checkout cannot resolve. + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=t3... --filter=@t3tools/scripts... + + - name: Setup Rust + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + + - name: Install patchelf + run: command -v patchelf || { sudo apt-get update && sudo apt-get install -y patchelf; } + + - name: Build CLI archive + run: scripts/build-standalone-linux-cli.sh "${GITHUB_REF_NAME#v}" "$RELEASE_REPOSITORY" release-cli + + - name: Upload CLI archive + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-linux-${{ matrix.arch }} + path: release-cli/* + if-no-files-found: error + + config: + name: Resolve release config + if: github.repository != 'pingdotgg/t3code' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + outputs: + version: ${{ steps.config.outputs.version }} + mac: ${{ steps.config.outputs.mac }} + env: + # Standalone builds refuse T3 Code's scheme, name and bundle id, so the fork sets its own in repository variables. + T3CODE_APP_SCHEME: ${{ vars.T3CODE_APP_SCHEME }} + T3CODE_APP_NAME: ${{ vars.T3CODE_APP_NAME }} + T3CODE_MOBILE_BUNDLE_ID: ${{ vars.T3CODE_MOBILE_BUNDLE_ID }} + steps: + - name: Require the fork's app scheme, name and bundle id + run: | + [ -n "$T3CODE_APP_SCHEME" ] || { + echo "::error::Set the repository variable T3CODE_APP_SCHEME to this fork's deep-link scheme: gh variable set T3CODE_APP_SCHEME --body " + exit 1 + } + [ -n "$T3CODE_APP_NAME" ] || { + echo "::error::Set the repository variable T3CODE_APP_NAME to this fork's product name: gh variable set T3CODE_APP_NAME --body ''" + exit 1 + } + [ -n "$T3CODE_MOBILE_BUNDLE_ID" ] || { + echo "::error::Set the repository variable T3CODE_MOBILE_BUNDLE_ID to this fork's desktop and mobile bundle id: gh variable set T3CODE_MOBILE_BUNDLE_ID --body " + exit 1 + } + + - id: config + env: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + run: | + echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" + # The same secrets release-desktop.yml signs with; a partial set fails the mac build there. + if [[ -n "$CSC_LINK" && -n "$CSC_KEY_PASSWORD" && -n "$APPLE_API_KEY" && -n "$APPLE_API_KEY_ID" && -n "$APPLE_API_ISSUER" ]]; then + echo "mac=true" >> "$GITHUB_OUTPUT" + else + echo "::notice::macOS skipped: the Apple signing secrets are not set." + echo "mac=false" >> "$GITHUB_OUTPUT" + fi + + build_bundle: + name: Build JS bundle + needs: [config] + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + T3CODE_STANDALONE: "1" + T3CODE_APP_NAME: ${{ vars.T3CODE_APP_NAME }} + T3CODE_APP_SCHEME: ${{ vars.T3CODE_APP_SCHEME }} + T3CODE_DESKTOP_UPDATE_REPOSITORY: ${{ github.repository }} + T3CODE_HOSTED_APP_URL: ${{ vars.T3CODE_HOSTED_APP_URL }} + # The server, web client and Electron main bake these in here; packaging reuses this bundle. + T3CODE_CLERK_PUBLISHABLE_KEY: ${{ vars.T3CODE_CLERK_PUBLISHABLE_KEY }} + T3CODE_CLERK_JWT_TEMPLATE: ${{ vars.T3CODE_CLERK_JWT_TEMPLATE }} + T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID }} + T3CODE_RELAY_URL: ${{ vars.T3CODE_RELAY_URL }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + + - name: Align package versions to release version + run: node scripts/update-release-package-versions.ts "${{ needs.config.outputs.version }}" + + - name: Build JS bundle + run: vp run build:desktop:bundle + + - name: Upload JS bundle + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: js-bundle + path: | + apps/server/dist + apps/desktop/dist-electron + if-no-files-found: error + retention-days: 1 + + desktop_linux: + name: Desktop ${{ matrix.label }} + needs: [config, build_bundle] + strategy: + fail-fast: false + matrix: + include: + - label: Linux x64 + runner: ubuntu-24.04 + platform: linux + target: AppImage + arch: x64 + rust_target: x86_64-unknown-linux-gnu + resource_key: linux-x64 + - label: Linux arm64 + runner: ubuntu-24.04-arm + platform: linux + target: AppImage + arch: arm64 + rust_target: aarch64-unknown-linux-gnu + resource_key: linux-arm64 + permissions: + actions: read + contents: read + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + label: ${{ matrix.label }} + runner: ${{ matrix.runner }} + platform: ${{ matrix.platform }} + target: ${{ matrix.target }} + arch: ${{ matrix.arch }} + rust_target: ${{ matrix.rust_target }} + resource_key: ${{ matrix.resource_key }} + version: ${{ needs.config.outputs.version }} + ref: ${{ github.ref }} + release_channel: stable + relay_client_tracing: false + clerk_publishable_key: ${{ vars.T3CODE_CLERK_PUBLISHABLE_KEY }} + clerk_jwt_template: ${{ vars.T3CODE_CLERK_JWT_TEMPLATE }} + clerk_cli_oauth_client_id: ${{ vars.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID }} + relay_url: ${{ vars.T3CODE_RELAY_URL }} + standalone: true + + desktop_mac: + name: Desktop ${{ matrix.label }} + needs: [config, build_bundle] + if: needs.config.outputs.mac == 'true' + strategy: + fail-fast: false + matrix: + include: + # macOS 26: the Apple Speech helper needs the macOS 26 SDK (SpeechTranscriber). + - label: macOS arm64 + runner: macos-26 + platform: mac + target: dmg + arch: arm64 + rust_target: aarch64-apple-darwin + resource_key: darwin-arm64 + # Native Intel: under Rosetta the 3-core hosted runner times out generating x64 bytecode. + - label: macOS x64 + runner: macos-26-intel + platform: mac + target: dmg + arch: x64 + rust_target: x86_64-apple-darwin + resource_key: darwin-x64 + permissions: + actions: read + contents: read + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + label: ${{ matrix.label }} + runner: ${{ matrix.runner }} + platform: ${{ matrix.platform }} + target: ${{ matrix.target }} + arch: ${{ matrix.arch }} + rust_target: ${{ matrix.rust_target }} + resource_key: ${{ matrix.resource_key }} + version: ${{ needs.config.outputs.version }} + ref: ${{ github.ref }} + release_channel: stable + relay_client_tracing: false + clerk_publishable_key: ${{ vars.T3CODE_CLERK_PUBLISHABLE_KEY }} + clerk_jwt_template: ${{ vars.T3CODE_CLERK_JWT_TEMPLATE }} + clerk_cli_oauth_client_id: ${{ vars.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID }} + relay_url: ${{ vars.T3CODE_RELAY_URL }} + standalone: true + + # Cross-built on Linux like upstream, then verified on Windows. Unsigned without the Azure + # Trusted Signing secrets, which release-desktop.yml checks itself. arm64 is left out: its + # feed would need merging with x64's into one latest.yml, and nobody tests it yet. + desktop_windows: + name: Desktop Windows x64 + # The installer embeds `build`'s Linux CLI archive as the WSL runtime. + needs: [config, build, build_bundle] + permissions: + actions: read + contents: read + uses: ./.github/workflows/release-desktop.yml + secrets: inherit + with: + label: Windows x64 + runner: ubuntu-24.04 + verify_runner: windows-2025 + platform: win + target: nsis + arch: x64 + rust_target: x86_64-pc-windows-msvc + resource_key: win32-x64 + version: ${{ needs.config.outputs.version }} + ref: ${{ github.ref }} + release_channel: stable + relay_client_tracing: false + clerk_publishable_key: ${{ vars.T3CODE_CLERK_PUBLISHABLE_KEY }} + clerk_jwt_template: ${{ vars.T3CODE_CLERK_JWT_TEMPLATE }} + clerk_cli_oauth_client_id: ${{ vars.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID }} + relay_url: ${{ vars.T3CODE_RELAY_URL }} + standalone: true + + release: + name: Draft GitHub release + needs: [config, build, build_bundle, desktop_linux, desktop_mac, desktop_windows] + # desktop_mac is skipped until the Apple signing secrets exist. + if: ${{ !cancelled() && needs.config.result == 'success' && !contains(needs.*.result, 'failure') }} + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: write + steps: + - name: Checkout + if: needs.config.outputs.mac == 'true' + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup dependencies + if: needs.config.outputs.mac == 'true' + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=@t3tools/scripts... + + - name: Download CLI archives + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: cli-linux-* + merge-multiple: true + path: release-assets + + - name: Download desktop artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: desktop-* + merge-multiple: true + path: release-assets + + # One latest-mac.yml must list both architectures; Linux feeds are already per arch. + - name: Merge macOS updater manifests + if: needs.config.outputs.mac == 'true' + run: | + set -euo pipefail + node scripts/merge-update-manifests.ts --platform mac \ + release-assets/latest-mac.yml release-assets/latest-mac-x64.yml release-assets/latest-mac.yml + rm release-assets/latest-mac-x64.yml + + # release-desktop.yml suffixes the Windows feed with its arch; electron-updater reads latest.yml. + - name: Name the Windows updater manifest + run: mv release-assets/latest-win-x64.yml release-assets/latest.yml + + - name: Create draft release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + APP_NAME: ${{ vars.T3CODE_APP_NAME }} + run: | + set -euo pipefail + cd release-assets + sha256sum t3-*.tar.gz > SHA256SUMS + cat SHA256SUMS + shopt -s nullglob + gh release create "$GITHUB_REF_NAME" --draft --verify-tag --generate-notes \ + --title "$APP_NAME $GITHUB_REF_NAME" t3-*.tar.gz SHA256SUMS \ + *.dmg *.zip *.AppImage *.exe *.blockmap latest*.yml diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 53061f25e9c48..e46e00cb0534d 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -8,6 +8,7 @@ jobs: ios: name: EAS Preview (iOS) if: | + github.repository == 'pingdotgg/t3code' && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') && (github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment') @@ -130,6 +131,7 @@ jobs: android: name: EAS Preview (Android) if: | + github.repository == 'pingdotgg/t3code' && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, '🚀 Mobile Continuous Deployment') && (github.event.action != 'labeled' || github.event.label.name == '🚀 Mobile Continuous Deployment') diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index 11d2ee60e122f..151e1ffa93b95 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -28,7 +28,7 @@ jobs: fingerprint: name: Native fingerprint diff if: github.event.action != 'edited' || github.event.changes.base - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} permissions: contents: read env: diff --git a/.github/workflows/relay-preview-cleanup.yml b/.github/workflows/relay-preview-cleanup.yml index 483e3e0b01b7e..9b9f4b8c05f1b 100644 --- a/.github/workflows/relay-preview-cleanup.yml +++ b/.github/workflows/relay-preview-cleanup.yml @@ -24,6 +24,7 @@ jobs: cleanup_pr: name: Tear down relay preview if: >- + github.repository == 'pingdotgg/t3code' && github.ref == 'refs/heads/main' && github.event_name == 'pull_request_target' && ( @@ -100,7 +101,7 @@ jobs: list_closed_previews: name: List closed relay previews - if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request_target' + if: github.repository == 'pingdotgg/t3code' && github.ref == 'refs/heads/main' && github.event_name != 'pull_request_target' runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 outputs: diff --git a/.github/workflows/relay-preview.yml b/.github/workflows/relay-preview.yml index daec319087759..a3a341c7f2811 100644 --- a/.github/workflows/relay-preview.yml +++ b/.github/workflows/relay-preview.yml @@ -20,6 +20,7 @@ jobs: deploy_preview: name: Deploy relay preview if: >- + github.repository == 'pingdotgg/t3code' && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, 'relay:preview') runs-on: blacksmith-8vcpu-ubuntu-2404 diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 2d3a38168c79e..279aa1eb95a15 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -116,6 +116,11 @@ on: relay_url: required: true type: string + # A fork's standalone build (see docs/operations/standalone-migration.md). + standalone: + required: false + default: false + type: boolean # electron-builder leaves the default arch (x64) out of the unpacked app's # directory name. @@ -140,6 +145,24 @@ jobs: T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ inputs.clerk_cli_oauth_client_id }} T3CODE_RELAY_URL: ${{ inputs.relay_url }} steps: + # Exported only for a standalone build, so official builds see none of these, not even empty. + - name: Configure standalone build + if: inputs.standalone + shell: bash + env: + APP_NAME: ${{ vars.T3CODE_APP_NAME }} + APP_SCHEME: ${{ vars.T3CODE_APP_SCHEME }} + BUNDLE_ID: ${{ vars.T3CODE_MOBILE_BUNDLE_ID }} + UPDATE_REPOSITORY: ${{ github.repository }} + run: | + { + echo "T3CODE_STANDALONE=1" + echo "T3CODE_APP_NAME=$APP_NAME" + echo "T3CODE_APP_SCHEME=$APP_SCHEME" + echo "T3CODE_MOBILE_BUNDLE_ID=$BUNDLE_ID" + echo "T3CODE_DESKTOP_UPDATE_REPOSITORY=$UPDATE_REPOSITORY" + } >> "$GITHUB_ENV" + # The launch check and the CLI archive smoke test both run the bundle. - name: Reject running an untrusted bundle if: inputs.untrusted_bundle && (inputs.launch_check || inputs.cli_archive) @@ -863,6 +886,22 @@ jobs: runs-on: ${{ inputs.verify_runner }} timeout-minutes: 15 steps: + # The verify script resolves the branded executable name from these. + - name: Configure standalone build + if: inputs.standalone + shell: bash + env: + APP_NAME: ${{ vars.T3CODE_APP_NAME }} + APP_SCHEME: ${{ vars.T3CODE_APP_SCHEME }} + UPDATE_REPOSITORY: ${{ github.repository }} + run: | + { + echo "T3CODE_STANDALONE=1" + echo "T3CODE_APP_NAME=$APP_NAME" + echo "T3CODE_APP_SCHEME=$APP_SCHEME" + echo "T3CODE_DESKTOP_UPDATE_REPOSITORY=$UPDATE_REPOSITORY" + } >> "$GITHUB_ENV" + - name: Download verification inputs uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.yml index 69db6b6025e8f..a7b11a3a45273 100644 --- a/.github/workflows/web-preview.yml +++ b/.github/workflows/web-preview.yml @@ -34,6 +34,7 @@ jobs: # workflow should skip rather than fail for them. On `labeled` events, only # the preview label itself triggers a deploy. if: >- + github.repository == 'pingdotgg/t3code' && github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, 'preview:web') && (github.event.action != 'labeled' || github.event.label.name == 'preview:web') diff --git a/.repos/alchemy-effect/submodules/distilled b/.repos/alchemy-effect/submodules/distilled deleted file mode 160000 index e02e9d405b884..0000000000000 --- a/.repos/alchemy-effect/submodules/distilled +++ /dev/null @@ -1 +0,0 @@ -Subproject commit e02e9d405b8848909f4f746b61b12a663f631c7c diff --git a/.repos/alchemy-effect/submodules/floci b/.repos/alchemy-effect/submodules/floci deleted file mode 160000 index 493909133db04..0000000000000 --- a/.repos/alchemy-effect/submodules/floci +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 493909133db04153348eabc503f4e30cf0033d96 diff --git a/README.md b/README.md index 24dc0f8f7f666..174b28dc40ad2 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,22 @@ -

- - T3 Code logo - -

+

EasyDev Code

-

T3 Code

- -

The open-source control plane for coding agents.

+

The open-source control plane for coding agents, from EasyDev Soluções Digitais.

- Download · - iOS · - Android · - Web · + Download · Docs · - Discord + Contact

- - T3 Code on desktop with a finished Claude thread, next to the phone app asking to approve a command from Codex - + The app on desktop with a finished Claude thread, next to the phone app asking to approve a command from Codex

-T3 Code runs the coding agents on your machine and gives them one fast interface. Start a thread at your desk, then approve the next step from your phone. +EasyDev Code runs the coding agents on your machine and gives them one fast interface. Start a thread at your desk, then approve the next step from your phone. + +It works with Claude Code, Codex, Cursor, OpenCode, Grok Build, Antigravity, Kiro, Pi, Muse Code, fx, and any [ACP](./docs/user/providers-acp.md) agent. If an agent is set up on your computer, EasyDev Code can control it. -It works with Claude Code, Codex, Cursor, OpenCode, Grok Build, Antigravity, Kiro, Pi, Muse Code, fx, and any [ACP](./docs/user/providers-acp.md) agent. If an agent is set up on your computer, T3 Code can control it. +Based on [T3 Code](https://github.com/pingdotgg/t3code) (MIT). EasyDev Code is an independent fork; it is not made or supported by T3 Tools. ## What you get @@ -41,47 +32,26 @@ It works with Claude Code, Codex, Cursor, OpenCode, Grok Build, Antigravity, Kir ### Desktop app -[Download T3 Code](https://t3.codes/download) for macOS, Windows, or Linux. You can also use a package manager: - -| Platform | Command | -| -------------- | -------------------------------------------------------------------- | -| macOS | `brew install --cask t3-code` | -| Windows | `winget install T3Tools.T3Code` or `scoop install extras/t3code` | -| Arch Linux | `yay -S t3code-bin` | -| Nix | `nix profile add github:NixOS/nixpkgs/nixos-unstable#t3code` | -| Debian, Ubuntu | `.deb` from [Releases](https://github.com/pingdotgg/t3code/releases) | +Download EasyDev Code for macOS or Linux from [Releases](https://github.com/diogocoutinho/t3code/releases). ### Command line -This installs the `t3` command. Run `t3` to start the server and open the web app. +This installs the `t3` command from this fork's releases. Run `t3` to start the server and open the web app. ```bash -curl -fsSL https://t3.codes/install.sh | sh +curl -fsSL https://raw.githubusercontent.com/diogocoutinho/t3code/main/scripts/install.sh \ + | T3CODE_RELEASE_REPOSITORY=diogocoutinho/t3code sh ``` -On Windows, in PowerShell: - -```powershell -irm https://t3.codes/install.ps1 | iex -``` - -To try it once without an install, run `npx t3@latest`. - ### Phone -Get the app from the [App Store](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) or [Google Play](https://play.google.com/store/apps/details?id=com.t3tools.t3code). Then follow [remote access](./docs/user/remote-access.md) to connect it to your computer. +Store apps are not published yet. [Remote access](./docs/user/remote-access.md) explains how a phone connects to your computer. ### Sign in to an agent -T3 Code needs one agent that is installed and signed in. For example, install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`, or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. - -[Provider setup](./docs/user/install.md#providers) has the steps for each agent. [Install T3 Code](./docs/user/install.md) covers nightly builds, AppImage, WSL, and NixOS. +EasyDev Code needs one agent that is installed and signed in. For example, install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`, or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. -## "Wait, what are you selling me?" - -Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar. - -We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the tool that you want. +[Provider setup](./docs/user/install.md#providers) has the steps for each agent. [Install](./docs/user/install.md) covers nightly builds, AppImage, WSL, and NixOS. ## Documentation @@ -96,12 +66,10 @@ We wanted something performant, remote-ready, and truly open. If we ever go the ## Contributing -We have limited review capacity. Small, focused fixes are the most likely to be merged. Features need an approved discussion first. - -- Read [CONTRIBUTING.md](./CONTRIBUTING.md) before you report a bug or open a pull request. -- Put feature requests in [Ideas](https://github.com/pingdotgg/t3code/discussions/categories/ideas). +- Report bugs and request features in [Issues](https://github.com/diogocoutinho/t3code/issues). +- Report vulnerabilities as [SECURITY.md](./SECURITY.md) describes. - Build from source with the [development runbook](./docs/operations/development.md#first-checkout). The [architecture overview](./docs/internals/overview.md) explains how it works. -- Get help in [Discord](https://discord.gg/jn4EGJjrvv). +- Changes that are not specific to this fork belong upstream in [T3 Code](https://github.com/pingdotgg/t3code); read its [CONTRIBUTING.md](./CONTRIBUTING.md) first. ## License diff --git a/SECURITY.md b/SECURITY.md index 09efb74eff51f..61f8ccf5626ce 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,7 +1,9 @@ # Security -Report vulnerabilities to [security@t3.codes](mailto:security@t3.codes). The -[security policy](.github/SECURITY.md) covers disclosure and safe harbor. +Report vulnerabilities in EasyDev Code to +[contato@easydevsolucoes.com.br](mailto:contato@easydevsolucoes.com.br). Do not disclose them +publicly until we have had a reasonable chance to fix them. Vulnerabilities in upstream T3 Code +go to T3 Tools as its [security policy](.github/SECURITY.md) describes. The rest of this file is for agents and maintainers auditing T3 Code or triaging a report. It says who is trusted with what, which boundaries a real finding diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index e433dc498cada..f8c8f8e5050cb 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -4,6 +4,7 @@ import * as NodeModule from "node:module"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeURL from "node:url"; +import { loadRepoEnv, resolveAppScheme } from "../../../scripts/lib/public-config.ts"; import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs"; const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); @@ -17,7 +18,9 @@ const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Beta)"; const APP_BUNDLE_ID = isDevelopment ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}` : "com.t3tools.t3code"; -const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"]; +// The same variable and .env files the desktop bundle's ElectronProtocol scheme comes from. +const appScheme = resolveAppScheme(loadRepoEnv()); +const APP_PROTOCOL_SCHEMES = isDevelopment ? [`${appScheme}-dev`] : [appScheme]; const LAUNCHER_VERSION = 20; const developmentMacIconPngPath = NodePath.join( repoRoot, diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index e11e946dd41ba..7016cdda3ff2e 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -141,6 +141,8 @@ describe("DesktopLifecycle", () => { Effect.gen(function* () { const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; yield* lifecycle.register; + // DesktopUpdates sets this before calling quitAndInstall. + yield* Ref.set((yield* DesktopState.DesktopState).quitting, true); appListeners.get("before-quit-for-update")?.(); yield* Effect.yieldNow; @@ -166,6 +168,57 @@ describe("DesktopLifecycle", () => { }, ); + it.effect("shuts down in order on a quit after the updater refused to install", () => + Effect.gen(function* () { + const appListeners = new Map void>(); + const quitRequested = yield* Deferred.make(); + const layerEnvironment = Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + platform: "darwin", + isDevelopment: false, + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const layer = DesktopLifecycle.layer.pipe( + Layer.provideMerge( + layerElectronApp( + appListeners, + Deferred.succeed(quitRequested, undefined).pipe(Effect.asVoid), + ), + ), + Layer.provideMerge(layerElectronTheme), + Layer.provideMerge(layerElectronWindow()), + Layer.provideMerge(layerDesktopWindow()), + Layer.provideMerge(layerEnvironment), + Layer.provideMerge(DesktopShutdown.layer), + Layer.provideMerge(DesktopState.layer), + ); + + yield* Effect.scoped( + Effect.gen(function* () { + const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; + const state = yield* DesktopState.DesktopState; + const shutdown = yield* DesktopShutdown.DesktopShutdown; + yield* lifecycle.register; + + yield* Ref.set(state.quitting, true); + appListeners.get("before-quit-for-update")?.(); + // DesktopUpdates.recoverFailedInstall after Squirrel reports an install error. + yield* Ref.set(state.quitting, false); + + let prevented = false; + appListeners.get("before-quit")?.({ + preventDefault: () => { + prevented = true; + }, + } as Electron.Event); + + assert.isTrue(prevented, "the recovered backends must stop before the app quits"); + yield* shutdown.awaitRequest; + yield* shutdown.markComplete; + yield* Deferred.await(quitRequested); + }), + ).pipe(Effect.provide(layer)); + }), + ); + it.effect("destroys windows before waiting for backend shutdown", () => Effect.gen(function* () { const appListeners = new Map void>(); diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 9568e72dde310..252c23876fae0 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -254,9 +254,14 @@ export const make = DesktopLifecycle.of({ const electronApp = yield* ElectronApp.ElectronApp; const electronTheme = yield* ElectronTheme.ElectronTheme; const environment = yield* DesktopEnvironment.DesktopEnvironment; + const desktopState = yield* DesktopState.DesktopState; const context = yield* Effect.context(); const runEffect = Effect.runPromiseWith(context); const quit: QuitState = { phase: "running", waitingSinceNanos: 0n }; + // Every allowed quit keeps `quitting` set; a refused update install clears it on recovery. + const dropRecoveredUpdaterQuit = () => { + if (quit.phase === "allowed" && !Ref.getUnsafe(desktopState.quitting)) quit.phase = "running"; + }; yield* electronTheme.onUpdated(() => { void runEffect( desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")), @@ -282,6 +287,7 @@ export const make = DesktopLifecycle.of({ ); }); yield* electronApp.on("before-quit", (event: Electron.Event) => { + dropRecoveredUpdaterQuit(); handleBeforeQuit(event, runEffect, quit); }); yield* electronApp.on("activate", () => { @@ -312,6 +318,7 @@ export const make = DesktopLifecycle.of({ process, "exit", (exitCode: number) => { + dropRecoveredUpdaterQuit(); Effect.runSyncWith(context)( Effect.gen(function* () { const shutdown = yield* DesktopShutdown.DesktopShutdown; diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index 768fe2ee3d8d3..12dcd0e106221 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -20,7 +20,14 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopObservability from "./DesktopObservability.ts"; import * as DesktopState from "./DesktopState.ts"; -const RELEASES_URL = "https://github.com/pingdotgg/t3code/releases"; +declare const __T3CODE_BUILD_RELEASE_REPOSITORY__: string | undefined; + +const RELEASE_REPOSITORY = + typeof __T3CODE_BUILD_RELEASE_REPOSITORY__ === "string" && + /^[\w.-]+\/[\w.-]+$/.test(__T3CODE_BUILD_RELEASE_REPOSITORY__) + ? __T3CODE_BUILD_RELEASE_REPOSITORY__ + : "pingdotgg/t3code"; +const RELEASES_URL = `https://github.com/${RELEASE_REPOSITORY}/releases`; const LAST_STARTED_VERSION_FILE = "desktop-last-started-version"; // Buttons are plain links to this host; will-navigate cancels them and runs the action. const ACTION_ORIGIN = "https://startup-recovery.invalid"; diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 7563898f43efc..484cc38767229 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -10,11 +10,12 @@ import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import { APP_SCHEME } from "@t3tools/shared/appScheme"; import * as Electron from "electron"; export const DESKTOP_HOST = "app"; -const DESKTOP_PRODUCTION_SCHEME = "t3code"; -const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev"; +const DESKTOP_PRODUCTION_SCHEME = APP_SCHEME; +const DESKTOP_DEVELOPMENT_SCHEME = `${APP_SCHEME}-dev`; export function getDesktopScheme(isDevelopment: boolean): string { return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME; diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index c88ddd0827df0..7aa48b0b89518 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,7 +1,11 @@ import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; -import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; +import { + receiveProviderAuthCallback, + cancelProviderAuthCallback, + signInWithCloudflareAccessWindow, +} from "./methods/providerAuth.ts"; import { appleSpeechAvailable, appleSpeechPrepare, @@ -164,6 +168,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(readMedia); yield* ipc.handle(receiveProviderAuthCallback); yield* ipc.handle(cancelProviderAuthCallback); + yield* ipc.handle(signInWithCloudflareAccessWindow); yield* ipc.handle(openSystemSettings); yield* ipc.handle(checkSystemPermission); yield* ipc.handle(appleSpeechAvailable); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 71d272333fdc7..3e92eeec1f8e1 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -148,6 +148,7 @@ export const PREVIEW_ANNOTATION_VOICE_STATE_CHANNEL = "desktop:preview-annotatio export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-auth-callback"; export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback"; +export const CLOUDFLARE_ACCESS_SIGN_IN_CHANNEL = "desktop:cloudflare-access-sign-in"; export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage"; export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; diff --git a/apps/desktop/src/ipc/methods/providerAuth.ts b/apps/desktop/src/ipc/methods/providerAuth.ts index d7f432815d2ae..5da7cb9af846a 100644 --- a/apps/desktop/src/ipc/methods/providerAuth.ts +++ b/apps/desktop/src/ipc/methods/providerAuth.ts @@ -8,6 +8,7 @@ import { } from "../../app/CodexAuthCallback.ts"; import * as ElectronShell from "../../electron/ElectronShell.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import { signInWithCloudflareAccess } from "../../window/CloudflareAccessLoginWindow.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; import * as IpcChannels from "../channels.ts"; @@ -52,3 +53,28 @@ export const cancelProviderAuthCallback = DesktopIpc.makeIpcMethod({ catch: () => new CodexAuthCallbackError({ detail: "Invalid ChatGPT sign-in request." }), }), }); + +export class CloudflareAccessSignInError extends Schema.TaggedError()( + "CloudflareAccessSignInError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not open the sign-in window."; + } +} + +export const signInWithCloudflareAccessWindow = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.CLOUDFLARE_ACCESS_SIGN_IN_CHANNEL, + payload: Schema.String.check(Schema.isMaxLength(2048)), + result: Schema.NullOr(Schema.String), + handler: Effect.fn("desktop.ipc.providerAuth.cloudflareAccessSignIn")(function* (host) { + const windows = yield* ElectronWindow.ElectronWindow; + const parent = yield* windows.focusedMainOrFirst; + const token = yield* Effect.tryPromise({ + try: () => signInWithCloudflareAccess(host, Option.getOrNull(parent)), + catch: (cause) => new CloudflareAccessSignInError({ cause }), + }); + if (Option.isSome(parent)) yield* windows.reveal(parent.value); + return token; + }), +}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ac52fbc73d868..50c8886af763d 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -257,6 +257,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), + signInWithCloudflareAccess: (host: string) => + ipcRenderer.invoke(IpcChannels.CLOUDFLARE_ACCESS_SIGN_IN_CHANNEL, host), startFileDrag: (input) => ipcRenderer.invoke(IpcChannels.START_FILE_DRAG_CHANNEL, input), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index d66ca346aabb3..748974f8b999d 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -62,7 +62,7 @@ const clientSettings: ClientSettings = { }, sidebarProjectSortOrder: "manual", sidebarThreadSortOrder: "created_at", - boringSidebarEnabled: false, + classicSidebarEnabled: false, boringSidebarMultilineRows: false, threadDetailsUsageEnabled: false, threadDetailsItems: {}, diff --git a/apps/desktop/src/window/CloudflareAccessLoginWindow.ts b/apps/desktop/src/window/CloudflareAccessLoginWindow.ts new file mode 100644 index 0000000000000..07d707bca0e82 --- /dev/null +++ b/apps/desktop/src/window/CloudflareAccessLoginWindow.ts @@ -0,0 +1,88 @@ +import { + CLOUDFLARE_ACCESS_APP_CALLBACK_URL, + cloudflareAccessAppLoginUrl, + cloudflareAccessLoginOrigin, + readCloudflareAccessAppCallback, +} from "@t3tools/shared/cloudflareAccessLogin"; +import * as Electron from "electron"; + +import { embeddedSignInUserAgent } from "./cloudflareAccessLoginUserAgent.ts"; + +// In memory, so a sign-in never outlives the app or mixes with the renderer's or previews' cookies. +const PARTITION = "cloudflare-access-login"; + +const isWebUrl = (url: string) => /^https?:/i.test(url); + +let closeActive: (() => void) | null = null; + +/** + * Signs in through Cloudflare Access in a sandboxed window and returns the pairing credential the + * server hands back on this build's app scheme, or null when the user closes the window. The + * scheme redirect is caught here and never reaches the OS, so no other app can receive it. + */ +export const signInWithCloudflareAccess = ( + host: string, + parent: Electron.BrowserWindow | null, +): Promise => { + const origin = cloudflareAccessLoginOrigin(host); + if (origin === null) return Promise.reject(new Error("Sign-in needs an https address.")); + closeActive?.(); + + return new Promise((resolve) => { + const browserSession = Electron.session.fromPartition(PARTITION); + browserSession.setUserAgent(embeddedSignInUserAgent(Electron.app.userAgentFallback)); + const webPreferences = { + session: browserSession, + sandbox: true, + contextIsolation: true, + nodeIntegration: false, + } satisfies Electron.WebPreferences; + const window = new Electron.BrowserWindow({ + width: 520, + height: 720, + ...(parent ? { parent } : {}), + autoHideMenuBar: true, + webPreferences, + }); + let settled = false; + const finish = (token: string | null) => { + if (settled) return; + settled = true; + if (closeActive === close) closeActive = null; + resolve(token); + if (!window.isDestroyed()) window.close(); + }; + const close = () => finish(null); + closeActive = close; + + // Only web pages load here; the callback is read and every other scheme is dropped. + const guard = (event: Electron.Event, url: string) => { + if (isWebUrl(url)) return; + event.preventDefault(); + // This build knows its own scheme, so only its exact callback counts. + if (!url.startsWith(CLOUDFLARE_ACCESS_APP_CALLBACK_URL)) return; + const token = readCloudflareAccessAppCallback(url); + if (token !== null) finish(token); + }; + const guardContents = (contents: Electron.WebContents) => { + contents.on("will-navigate", guard); + contents.on("will-redirect", guard); + contents.on("will-frame-navigate", (event) => { + if (!event.isMainFrame && !isWebUrl(event.url)) event.preventDefault(); + }); + }; + guardContents(window.webContents); + // Identity providers may open popups; they stay in this session and under the same guard. + window.webContents.setWindowOpenHandler(({ url }) => + isWebUrl(url) + ? { action: "allow", overrideBrowserWindowOptions: { parent: window, webPreferences } } + : { action: "deny" }, + ); + window.webContents.on("did-create-window", (popup) => guardContents(popup.webContents)); + window.on("closed", close); + + void window.loadURL(cloudflareAccessAppLoginUrl(origin)).catch(() => { + // A load aborted by the callback redirect is expected; anything else leaves the page shown. + }); + }); +}; diff --git a/apps/desktop/src/window/cloudflareAccessLoginUserAgent.test.ts b/apps/desktop/src/window/cloudflareAccessLoginUserAgent.test.ts new file mode 100644 index 0000000000000..6e6fea76e9da0 --- /dev/null +++ b/apps/desktop/src/window/cloudflareAccessLoginUserAgent.test.ts @@ -0,0 +1,13 @@ +import { expect, it } from "vite-plus/test"; + +import { embeddedSignInUserAgent } from "./cloudflareAccessLoginUserAgent.ts"; + +it("keeps only the tokens a plain Chrome sends", () => { + expect( + embeddedSignInUserAgent( + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) easydevcode/0.1.16 Chrome/138.0.7204.243 Electron/37.4.0 Safari/537.36", + ), + ).toBe( + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.7204.243 Safari/537.36", + ); +}); diff --git a/apps/desktop/src/window/cloudflareAccessLoginUserAgent.ts b/apps/desktop/src/window/cloudflareAccessLoginUserAgent.ts new file mode 100644 index 0000000000000..77e33601cbcbe --- /dev/null +++ b/apps/desktop/src/window/cloudflareAccessLoginUserAgent.ts @@ -0,0 +1,12 @@ +const KEPT_PRODUCTS = new Set(["Mozilla", "AppleWebKit", "Chrome", "Safari"]); + +/** + * Identity providers such as Google refuse sign-in from user agents that name an embedding app, + * so drop every product token except the ones a plain Chrome sends. + */ +export const embeddedSignInUserAgent = (userAgent: string): string => + userAgent + .replace(/(^|\s)([A-Za-z][\w.-]*)\/\S+/g, (token, _space: string, product: string) => + KEPT_PRODUCTS.has(product) ? token : "", + ) + .trim(); diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 6ded8e851ddbb..21b41862ae7e7 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -4,9 +4,13 @@ import * as NodeOS from "node:os"; import { defaultInclude, defineConfig } from "vite-plus"; import { isDesktopRuntimeExternalDependency } from "../../scripts/lib/desktop-external-packages.ts"; -import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import { appSchemeDefine, loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import { rebrandPlugin } from "../../scripts/lib/rebrand.ts"; +import { standaloneBuildDefine } from "../../scripts/lib/standalone-build.ts"; const repoEnv = loadRepoEnv(); +const releaseRepository = + repoEnv.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || repoEnv.GITHUB_REPOSITORY?.trim(); const domTests = ["src/preview/PickPreload.test.ts"]; // Install only bundle externals; the server bundle already carries its dependency tree. @@ -24,6 +28,14 @@ const publicConfigDefine = { __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify( repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "", ), + // The repository whose releases feed updates; recovery links and SSH CLI downloads use it too. + // Omitted when unset so shared code falls back to the official repository instead of "". + ...(releaseRepository + ? { __T3CODE_BUILD_RELEASE_REPOSITORY__: JSON.stringify(releaseRepository) } + : {}), + // Standalone builds validate the fork repository and override the value above. + ...standaloneBuildDefine(repoEnv), + ...appSchemeDefine(repoEnv), }; export default defineConfig({ @@ -72,6 +84,7 @@ export default defineConfig({ sourcemap: true, outExtensions: () => ({ js: ".cjs" }), define: publicConfigDefine, + plugins: [rebrandPlugin(repoEnv)], outputOptions: { codeSplitting: false }, entry: ["src/main.ts"], clean: true, @@ -89,6 +102,7 @@ export default defineConfig({ sourcemap: true, outExtensions: () => ({ js: ".cjs" }), define: publicConfigDefine, + plugins: [rebrandPlugin(repoEnv)], entry: [ "src/electron/WindowsForegroundFocusWorker.ts", "src/snapShot/GlobalShiftShortcutWorker.ts", @@ -122,6 +136,7 @@ export default defineConfig({ sourcemap: true, outExtensions: () => ({ js: ".cjs" }), define: publicConfigDefine, + plugins: [rebrandPlugin(repoEnv)], entry: ["src/preload.ts"], deps: { // Sandboxed preloads cannot resolve imports inside ASAR; bundle Clerk's bridge. diff --git a/apps/marketing/src/pages/schema/t3.json.ts b/apps/marketing/src/pages/schema/t3.json.ts index d837e66ad58f7..ba70b719afcef 100644 --- a/apps/marketing/src/pages/schema/t3.json.ts +++ b/apps/marketing/src/pages/schema/t3.json.ts @@ -2,7 +2,9 @@ import type { APIRoute } from "astro"; import { buildT3ProjectFileJsonSchema } from "@t3tools/shared/t3ProjectFile"; -export const GET: APIRoute = () => - new Response(`${JSON.stringify(buildT3ProjectFileJsonSchema(), null, 2)}\n`, { - headers: { "Content-Type": "application/json" }, - }); +// A fork serving this site under its own domain names that copy, not T3's. +export const GET: APIRoute = ({ site, url }) => + new Response( + `${JSON.stringify(buildT3ProjectFileJsonSchema(new URL(url.pathname, site ?? url).href), null, 2)}\n`, + { headers: { "Content-Type": "application/json" } }, + ); diff --git a/apps/mobile/app.config.test.ts b/apps/mobile/app.config.test.ts index 9be2204d5132c..540c829dfe5c2 100644 --- a/apps/mobile/app.config.test.ts +++ b/apps/mobile/app.config.test.ts @@ -1,13 +1,37 @@ import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + import { afterEach, expect, it, vi } from "vite-plus/test"; +import { buildFontCssVariables, resolveBuildFontFamilies } from "./src/lib/easydevFonts.ts"; + import appleAppSiteAssociation from "../web/public/.well-known/apple-app-site-association.json"; import assetLinks from "../web/public/.well-known/assetlinks.json"; // Keep config parsing independent of local env files and build credentials. -vi.mock("../../scripts/lib/public-config.ts", () => ({ - loadRepoEnv: () => ({ APP_VARIANT: process.env.APP_VARIANT }), -})); +vi.mock("../../scripts/lib/public-config.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + resolveAppScheme: actual.resolveAppScheme, + isStandaloneBuild: actual.isStandaloneBuild, + // app.config copies these into process.env, so an unset key must stay absent, not "undefined". + loadRepoEnv: () => + Object.fromEntries( + [ + "APP_VARIANT", + "T3CODE_STANDALONE", + "T3CODE_EAS_PROJECT_ID", + "T3CODE_HOSTED_APP_URL", + "T3CODE_MOBILE_BUNDLE_ID", + "T3CODE_IOS_TEAM_ID", + "T3CODE_DESKTOP_UPDATE_REPOSITORY", + "T3CODE_APP_SCHEME", + "T3CODE_APP_NAME", + ].flatMap((key) => (process.env[key] === undefined ? [] : [[key, process.env[key]]])), + ), + }; +}); afterEach(() => { vi.unstubAllEnvs(); @@ -34,6 +58,7 @@ it.each([ const config = await loadConfig(value); expect(config.ios?.bundleIdentifier).toBe(identifier); expect(config.android?.package).toBe(identifier); + expect(config.scheme).toBe(identifier.replace("com.t3tools.t3code", "t3code").replace(".", "-")); // Copied thread links open this app only while app.t3.codes lists it. const host = new URL(DEFAULT_HOSTED_APP_URL).host; expect(config.ios?.associatedDomains).toContain(`applinks:${host}`); @@ -45,3 +70,109 @@ it.each([ ]); expect(assetLinks.map((link) => link.target.package_name)).toContain(identifier); }); + +it("keeps T3's Expo project, owner, hosted app, and Apple team out of a standalone build", async () => { + vi.stubEnv("T3CODE_STANDALONE", "1"); + vi.stubEnv("T3CODE_MOBILE_BUNDLE_ID", "com.fork.code"); + const config = await loadConfig("production"); + expect(config.ios?.appleTeamId).toBeUndefined(); + expect(config.updates).toMatchObject({ enabled: false }); + expect(config.updates?.url).toBeUndefined(); + expect(config.owner).toBeUndefined(); + expect(config.extra?.eas?.projectId).toBeUndefined(); + expect(config.extra?.hostedAppUrl).toBe(""); + expect(config.ios?.associatedDomains).toEqual([]); + expect(config.android?.intentFilters).toEqual([]); + expect(JSON.stringify(config)).not.toMatch(/t3\.codes|d763fcb8|pingdotgg|t3tools|ARK85ZXQ4Z/); +}); + +it("requires a standalone build to bring its own bundle identifier", async () => { + vi.stubEnv("T3CODE_STANDALONE", "1"); + await expect(loadConfig("production")).rejects.toThrow("T3CODE_MOBILE_BUNDLE_ID"); + vi.stubEnv("T3CODE_MOBILE_BUNDLE_ID", "com.fork-code.app"); + await expect(loadConfig("production")).rejects.toThrow("T3CODE_MOBILE_BUNDLE_ID"); +}); + +it.each([ + ["development", "com.fork.code.dev"], + ["preview", "com.fork.code.preview"], + ["production", "com.fork.code"], +])("signs APP_VARIANT=%j as the fork's app", async (value, identifier) => { + vi.stubEnv("T3CODE_MOBILE_BUNDLE_ID", "com.fork.code"); + vi.stubEnv("T3CODE_IOS_TEAM_ID", "FORKTEAM01"); + vi.stubEnv("T3CODE_APP_SCHEME", "forkcode"); + vi.stubEnv("T3CODE_DESKTOP_UPDATE_REPOSITORY", "fork/t3code"); + const config = await loadConfig(value); + expect(config.ios?.bundleIdentifier).toBe(identifier); + expect(config.android?.package).toBe(identifier); + expect(config.ios?.appleTeamId).toBe("FORKTEAM01"); + // The URL scheme follows the variant like the identifier: forkcode, forkcode-dev, forkcode-preview. + expect(config.scheme).toBe(identifier.replace("com.fork.code", "forkcode").replace(".", "-")); + expect(config.ios?.entitlements?.["keychain-access-groups"]).toEqual([ + `$(AppIdentifierPrefix)${identifier}`, + ]); + expect(config.extra?.releaseRepository).toBe("fork/t3code"); +}); + +it("uses the fork's own Expo project and hosted app in a standalone build", async () => { + vi.stubEnv("T3CODE_STANDALONE", "1"); + vi.stubEnv("T3CODE_MOBILE_BUNDLE_ID", "com.fork.code"); + vi.stubEnv("T3CODE_EAS_PROJECT_ID", "fork-project"); + vi.stubEnv("T3CODE_HOSTED_APP_URL", "https://app.fork.example"); + vi.stubEnv("T3CODE_APP_NAME", "Fork Code"); + const config = await loadConfig("production"); + expect(config.name).toBe("Fork Code"); + expect(JSON.stringify(config)).not.toMatch(/T3 Code/); + expect(config.updates).toMatchObject({ enabled: true, url: "https://u.expo.dev/fork-project" }); + expect(config.extra?.eas?.projectId).toBe("fork-project"); + expect(config.ios?.associatedDomains).toEqual(["applinks:app.fork.example"]); + expect(config.android?.intentFilters?.[0]?.data).toEqual([ + { scheme: "https", host: "app.fork.example", pathPrefix: "/threads/" }, + ]); +}); + +function expoFontOptions(config: Awaited>) { + const plugin = config.plugins?.find( + (entry): entry is [string, { ios: { fonts: string[] }; android: { fonts: AndroidFont[] } }] => + Array.isArray(entry) && entry[0] === "expo-font", + ); + return plugin![1]; +} + +type AndroidFont = { fontFamily: string; fontDefinitions: { path: string; weight: number }[] }; + +it("compiles only DM Sans into stock builds and leaves their font defaults alone", async () => { + const fonts = expoFontOptions(await loadConfig("production")); + expect(fonts.ios.fonts.every((path) => path.includes("dm-sans"))).toBe(true); + expect(fonts.android.fonts.map((font) => font.fontFamily)).toEqual([ + "DMSans-Regular", + "DMSans-Medium", + "DMSans-Bold", + ]); + expect(buildFontCssVariables(false)).toEqual({}); + expect(resolveBuildFontFamilies(false)).toMatchObject({ + regular: "DMSans-Regular", + medium: "DMSans-Medium", + bold: "DMSans-Bold", + header: null, + mono: null, + }); +}); + +it("registers every standalone default family on iOS and Android", async () => { + vi.stubEnv("T3CODE_STANDALONE", "1"); + vi.stubEnv("T3CODE_MOBILE_BUNDLE_ID", "com.fork.code"); + const fonts = expoFontOptions(await loadConfig("production")); + const android = new Map(fonts.android.fonts.map((font) => [font.fontFamily, font])); + // A family missing here renders in the system font with no error on either platform. + for (const family of new Set(Object.values(resolveBuildFontFamilies(true)))) { + const path = android.get(family!)?.fontDefinitions[0]?.path; + expect(path, family!).toBeDefined(); + expect(fonts.ios.fonts).toContain(path); + expect(NodePath.basename(path!, ".ttf")).toBe(family); + expect(NodeFS.existsSync(NodePath.join(import.meta.dirname, path!))).toBe(true); + } + expect(Object.values(buildFontCssVariables(true)).every((family) => android.has(family))).toBe( + true, + ); +}); diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index bad4faed441fd..3b2544c1c9447 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -1,7 +1,15 @@ import type { ExpoConfig } from "expo/config"; -import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts"; -import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import { + resolveBrandAssetPaths, + STANDALONE_ANDROID_ASSETS, +} from "../../scripts/lib/brand-assets.ts"; +import { + isStandaloneBuild as isRepoStandaloneBuild, + loadRepoEnv, + resolveAppScheme, +} from "../../scripts/lib/public-config.ts"; +import { rebrandName, rebrandStrings } from "../../scripts/lib/rebrand.ts"; type AppVariant = "development" | "preview" | "production"; @@ -11,6 +19,16 @@ Object.assign(process.env, repoEnv); process.env.EXPO_NO_TYPESCRIPT_SETUP = "1"; const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT); +// iOS URL types and Android intent filters claim it; a fork's own keeps official links out. +const appScheme = resolveAppScheme(repoEnv); +// Standalone builds use only the fork's own Expo project and hosted app; unset means none. +const isStandaloneBuild = isRepoStandaloneBuild(repoEnv); +const easProjectId = + repoEnv.T3CODE_EAS_PROJECT_ID?.trim() || + (isStandaloneBuild ? undefined : "d763fcb8-d37c-41ea-a773-b54a0ab4a454"); +const easOwner = repoEnv.T3CODE_EAS_OWNER?.trim() || (isStandaloneBuild ? undefined : "pingdotgg"); +const hostedAppUrl = + repoEnv.T3CODE_HOSTED_APP_URL?.trim() || (isStandaloneBuild ? undefined : "https://app.t3.codes"); const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1"; const runtimeVersionPolicy = process.env.MOBILE_VERSION_POLICY ?? @@ -18,6 +36,13 @@ const runtimeVersionPolicy = const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim(); const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/; +const MOBILE_BUNDLE_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/; +// Also the Android package; variants append .dev or .preview. +const mobileBundleId = repoEnv.T3CODE_MOBILE_BUNDLE_ID?.trim() || undefined; +const iosTeamId = + repoEnv.T3CODE_IOS_TEAM_ID?.trim() || (isStandaloneBuild ? undefined : "ARK85ZXQ4Z"); +const releaseRepository = + repoEnv.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || repoEnv.GITHUB_REPOSITORY?.trim() || ""; // Compiled into the native project. Without a relay, Observe's native side could dispatch to // Expo's own ingest before observe.ts turns it off; `.invalid` never resolves (RFC 6761). @@ -26,6 +51,7 @@ const observeEndpointUrl = repoEnv.T3CODE_RELAY_URL?.trim() : "https://observe.invalid"; const fromRepoRoot = (relativePath: string) => `../../${relativePath}`; +const BRAND_ASSET_PATHS = resolveBrandAssetPaths(repoEnv); const androidAdaptiveForeground = "./assets/android-icon-foreground.png"; if ( @@ -38,6 +64,12 @@ if ( ); } +if (mobileBundleId ? !MOBILE_BUNDLE_ID_PATTERN.test(mobileBundleId) : isStandaloneBuild) { + throw new Error( + "T3CODE_MOBILE_BUNDLE_ID must be a reverse-DNS identifier such as com.example.t3code; T3CODE_STANDALONE=1 requires it.", + ); +} + const DEVELOPMENT_ASSETS = { appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng), iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject), @@ -77,30 +109,40 @@ const RELEASE_ASSETS = { androidNotificationColor: "#FFFFFF", } as const; +const STANDALONE_ASSETS = { + appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng), + iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject), + splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng), + androidAdaptiveForeground: fromRepoRoot(STANDALONE_ANDROID_ASSETS.adaptiveForeground), + androidAdaptiveBackgroundColor: STANDALONE_ANDROID_ASSETS.adaptiveBackgroundColor, + androidAdaptiveBackgroundImage: fromRepoRoot(STANDALONE_ANDROID_ASSETS.adaptiveBackgroundImage), + androidSplashIcon: fromRepoRoot(STANDALONE_ANDROID_ASSETS.splashIcon), + androidMonochromeIcon: fromRepoRoot(STANDALONE_ANDROID_ASSETS.monochromeIcon), + androidNotificationIcon: fromRepoRoot(STANDALONE_ANDROID_ASSETS.notificationIcon), + androidNotificationColor: STANDALONE_ANDROID_ASSETS.notificationColor, +} as const; + const VARIANT_CONFIG = { development: { appName: "T3 Code Dev", - scheme: "t3code-dev", - iosBundleIdentifier: "com.t3tools.t3code.dev", - androidPackage: "com.t3tools.t3code.dev", + scheme: `${appScheme}-dev`, + bundleIdSuffix: ".dev", relyingParty: "clerk.t3.codes", assets: DEVELOPMENT_ASSETS, }, preview: { appName: "T3 Code Preview", - scheme: "t3code-preview", - iosBundleIdentifier: "com.t3tools.t3code.preview", - androidPackage: "com.t3tools.t3code.preview", + scheme: `${appScheme}-preview`, + bundleIdSuffix: ".preview", relyingParty: "clerk.t3.codes", - assets: PREVIEW_ASSETS, + assets: isStandaloneBuild ? STANDALONE_ASSETS : PREVIEW_ASSETS, }, production: { appName: "T3 Code", - scheme: "t3code", - iosBundleIdentifier: "com.t3tools.t3code", - androidPackage: "com.t3tools.t3code", + scheme: appScheme, + bundleIdSuffix: "", relyingParty: "clerk.t3.codes", - assets: RELEASE_ASSETS, + assets: isStandaloneBuild ? STANDALONE_ASSETS : RELEASE_ASSETS, }, } as const; @@ -118,17 +160,39 @@ function resolveAppVariant(value: string | undefined): AppVariant { } const variant = VARIANT_CONFIG[APP_VARIANT]; -// Copied thread links open the app. app.t3.codes/.well-known lists every variant's identifiers. -const HOSTED_APP_HOST = "app.t3.codes"; +const variantBundleIdentifier = `${mobileBundleId ?? "com.t3tools.t3code"}${variant.bundleIdSuffix}`; +// Copied thread links open the app. The hosted app's /.well-known lists every variant's identifiers. +const hostedAppHost = hostedAppUrl ? new URL(hostedAppUrl).host : undefined; const iosBundleIdentifier = isIosPersonalTeamBuild ? personalTeamBundleIdentifier! - : variant.iosBundleIdentifier; + : variantBundleIdentifier; const dmSansFonts = { regular: "@expo-google-fonts/dm-sans/400Regular/DMSans_400Regular.ttf", medium: "@expo-google-fonts/dm-sans/500Medium/DMSans_500Medium.ttf", bold: "@expo-google-fonts/dm-sans/700Bold/DMSans_700Bold.ttf", } as const; +// Families src/lib/easydevFonts.ts selects. Each file is named for its PostScript name, which iOS +// resolves by, and Android registers the same name. DM Sans stays: native composer chips name it. +const standaloneFonts = isStandaloneBuild + ? ( + [ + ["inter", "Inter-Regular", 400], + ["inter", "Inter-Medium", 500], + ["inter", "Inter-SemiBold", 600], + ["inter", "Inter-Bold", 700], + ["jetbrains-mono", "JetBrainsMono-Regular", 400], + ["jetbrains-mono", "JetBrainsMono-Medium", 500], + ["outfit", "Outfit-SemiBold", 600], + ["outfit", "Outfit-Bold", 700], + ["outfit", "Outfit-ExtraBold", 800], + ] as const + ).map(([folder, family, weight]) => ({ + family, + weight, + path: `./assets/fonts/${folder}/${family}.ttf`, + })) + : []; const widgetsPlugin: NonNullable[number] = [ "expo-widgets", @@ -246,8 +310,8 @@ const config: ExpoConfig = { icon: variant.assets.appIcon, userInterfaceStyle: "automatic", updates: { - enabled: repoEnv.T3CODE_MOBILE_UPDATES_ENABLED !== "0", - url: "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454", + enabled: repoEnv.T3CODE_MOBILE_UPDATES_ENABLED !== "0" && easProjectId !== undefined, + ...(easProjectId ? { url: `https://u.expo.dev/${easProjectId}` } : {}), checkAutomatically: "ON_LOAD", fallbackToCacheTimeout: 0, }, @@ -257,14 +321,16 @@ const config: ExpoConfig = { requireFullScreen: process.env.T3_SHOWCASE_CAPTURE_BUILD === "1", bundleIdentifier: iosBundleIdentifier, // Avoid Personal Team fallback: it cannot sign App Groups, Apple sign-in or push entitlements. - appleTeamId: "ARK85ZXQ4Z", + ...(iosTeamId ? { appleTeamId: iosTeamId } : {}), associatedDomains: [ - `applinks:${variant.relyingParty}`, - `webcredentials:${variant.relyingParty}`, - `applinks:${HOSTED_APP_HOST}`, + // T3's Clerk passkey domain; a standalone build has no relying party of its own yet. + ...(isStandaloneBuild + ? [] + : [`applinks:${variant.relyingParty}`, `webcredentials:${variant.relyingParty}`]), + ...(hostedAppHost ? [`applinks:${hostedAppHost}`] : []), ], entitlements: { - "keychain-access-groups": [`$(AppIdentifierPrefix)${variant.iosBundleIdentifier}`], + "keychain-access-groups": [`$(AppIdentifierPrefix)${variantBundleIdentifier}`], }, infoPlist: { UISupportedInterfaceOrientations: [ @@ -298,7 +364,7 @@ const config: ExpoConfig = { }, android: { icon: variant.assets.appIcon, - package: variant.androidPackage, + package: variantBundleIdentifier, ...(repoEnv.T3CODE_ANDROID_GOOGLE_SERVICES_FILE ? { googleServicesFile: repoEnv.T3CODE_ANDROID_GOOGLE_SERVICES_FILE } : {}), @@ -314,14 +380,16 @@ const config: ExpoConfig = { predictiveBackGestureEnabled: true, // expo-sensors declares this for its pedometer, which the app does not use. blockedPermissions: ["android.permission.ACTIVITY_RECOGNITION"], - intentFilters: [ - { - action: "VIEW", - autoVerify: true, - data: [{ scheme: "https", host: HOSTED_APP_HOST, pathPrefix: "/threads/" }], - category: ["BROWSABLE", "DEFAULT"], - }, - ], + intentFilters: hostedAppHost + ? [ + { + action: "VIEW", + autoVerify: true, + data: [{ scheme: "https", host: hostedAppHost, pathPrefix: "/threads/" }], + category: ["BROWSABLE", "DEFAULT"], + }, + ] + : [], }, web: { favicon: variant.assets.appIcon, @@ -332,7 +400,12 @@ const config: ExpoConfig = { "expo-font", { ios: { - fonts: [dmSansFonts.regular, dmSansFonts.medium, dmSansFonts.bold], + fonts: [ + dmSansFonts.regular, + dmSansFonts.medium, + dmSansFonts.bold, + ...standaloneFonts.map((font) => font.path), + ], }, android: { fonts: [ @@ -348,6 +421,10 @@ const config: ExpoConfig = { fontFamily: "DMSans-Bold", fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }], }, + ...standaloneFonts.map((font) => ({ + fontFamily: font.family, + fontDefinitions: [{ path: font.path, weight: font.weight }], + })), ], }, }, @@ -455,6 +532,7 @@ const config: ExpoConfig = { ...(!isIosPersonalTeamBuild ? ["./plugins/withWidgetLogoAsset.cjs", widgetsPlugin] : []), "./plugins/withAndroidNetworkSecurityConfig.cjs", "./plugins/withAndroidGradleHeap.cjs", + ...(isStandaloneBuild ? ["./plugins/withStandaloneNotificationMark.cjs"] : []), "./plugins/withAndroidInputBackground.cjs", "./plugins/withAndroidModernPopupMenu.cjs", "./plugins/withAndroidModernAlertDialog.cjs", @@ -462,6 +540,7 @@ const config: ExpoConfig = { // MainActivity mods run in reverse order; extend the tablet-orientation override. "./plugins/withAndroidWindowDisplayMetrics.cjs", "./plugins/withAndroidTabletOrientation.cjs", + ["./plugins/withProductName.cjs", "T3 Code"], ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []), ], extra: { @@ -470,6 +549,11 @@ const config: ExpoConfig = { process.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", ), iosPersonalTeamBuild: isIosPersonalTeamBuild, + standalone: isStandaloneBuild, + // Empty means no hosted app: the manifest turns null into {}. + hostedAppUrl: hostedAppUrl ?? "", + // owner/repo for release checks and help links; empty means T3's. + releaseRepository, relay: { url: repoEnv.T3CODE_RELAY_URL ?? null, }, @@ -488,15 +572,17 @@ const config: ExpoConfig = { tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null, }, eas: { - projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454", + ...(easProjectId ? { projectId: easProjectId } : {}), observe: { endpointUrl: observeEndpointUrl }, }, }, - owner: "pingdotgg", + ...(easOwner ? { owner: easOwner } : {}), experiments: { // Metro only runs babel-plugin-react-compiler when this is set; see src/reactCompilerCoverage.test.ts. reactCompiler: true, }, }; -export default config; +const appName = rebrandName(repoEnv); + +export default appName ? rebrandStrings(config, appName) : config; diff --git a/apps/mobile/assets/fonts/inter/Inter-Bold.ttf b/apps/mobile/assets/fonts/inter/Inter-Bold.ttf new file mode 100644 index 0000000000000..9fb9b751e5b24 Binary files /dev/null and b/apps/mobile/assets/fonts/inter/Inter-Bold.ttf differ diff --git a/apps/mobile/assets/fonts/inter/Inter-Medium.ttf b/apps/mobile/assets/fonts/inter/Inter-Medium.ttf new file mode 100644 index 0000000000000..458cd0601d280 Binary files /dev/null and b/apps/mobile/assets/fonts/inter/Inter-Medium.ttf differ diff --git a/apps/mobile/assets/fonts/inter/Inter-Regular.ttf b/apps/mobile/assets/fonts/inter/Inter-Regular.ttf new file mode 100644 index 0000000000000..b7aaca8de1fe4 Binary files /dev/null and b/apps/mobile/assets/fonts/inter/Inter-Regular.ttf differ diff --git a/apps/mobile/assets/fonts/inter/Inter-SemiBold.ttf b/apps/mobile/assets/fonts/inter/Inter-SemiBold.ttf new file mode 100644 index 0000000000000..47f8ab1d68144 Binary files /dev/null and b/apps/mobile/assets/fonts/inter/Inter-SemiBold.ttf differ diff --git a/apps/mobile/assets/fonts/inter/OFL.txt b/apps/mobile/assets/fonts/inter/OFL.txt new file mode 100644 index 0000000000000..9b2ca37b3ffc7 --- /dev/null +++ b/apps/mobile/assets/fonts/inter/OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/mobile/assets/fonts/jetbrains-mono/JetBrainsMono-Medium.ttf b/apps/mobile/assets/fonts/jetbrains-mono/JetBrainsMono-Medium.ttf new file mode 100644 index 0000000000000..97671156df256 Binary files /dev/null and b/apps/mobile/assets/fonts/jetbrains-mono/JetBrainsMono-Medium.ttf differ diff --git a/apps/mobile/assets/fonts/jetbrains-mono/JetBrainsMono-Regular.ttf b/apps/mobile/assets/fonts/jetbrains-mono/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000000000..dff66cc50702c Binary files /dev/null and b/apps/mobile/assets/fonts/jetbrains-mono/JetBrainsMono-Regular.ttf differ diff --git a/apps/mobile/assets/fonts/jetbrains-mono/OFL.txt b/apps/mobile/assets/fonts/jetbrains-mono/OFL.txt new file mode 100644 index 0000000000000..8bee4148c1d54 --- /dev/null +++ b/apps/mobile/assets/fonts/jetbrains-mono/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/mobile/assets/fonts/outfit/OFL.txt b/apps/mobile/assets/fonts/outfit/OFL.txt new file mode 100644 index 0000000000000..723cd447edee8 --- /dev/null +++ b/apps/mobile/assets/fonts/outfit/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/mobile/assets/fonts/outfit/Outfit-Bold.ttf b/apps/mobile/assets/fonts/outfit/Outfit-Bold.ttf new file mode 100644 index 0000000000000..03068242baff5 Binary files /dev/null and b/apps/mobile/assets/fonts/outfit/Outfit-Bold.ttf differ diff --git a/apps/mobile/assets/fonts/outfit/Outfit-ExtraBold.ttf b/apps/mobile/assets/fonts/outfit/Outfit-ExtraBold.ttf new file mode 100644 index 0000000000000..7d34f26d4e98a Binary files /dev/null and b/apps/mobile/assets/fonts/outfit/Outfit-ExtraBold.ttf differ diff --git a/apps/mobile/assets/fonts/outfit/Outfit-SemiBold.ttf b/apps/mobile/assets/fonts/outfit/Outfit-SemiBold.ttf new file mode 100644 index 0000000000000..049908c539826 Binary files /dev/null and b/apps/mobile/assets/fonts/outfit/Outfit-SemiBold.ttf differ diff --git a/apps/mobile/babel.config.js b/apps/mobile/babel.config.js index 5c85f81242a7e..3c0152ec2fb18 100644 --- a/apps/mobile/babel.config.js +++ b/apps/mobile/babel.config.js @@ -1,6 +1,39 @@ +const { rebrandName, rebrandText } = require("../../scripts/lib/rebrand.ts"); + +// A standalone build names its own product in every string, as the web and desktop bundles do. +function rebrandStringsPlugin({ types: t }, { name }) { + const rename = (state, path, value, make) => { + if (state.filename?.includes("node_modules")) return; + const next = rebrandText(value, name); + if (next !== value) path.replaceWith(make(next)); + }; + return { + visitor: { + StringLiteral(path, state) { + rename(state, path, path.node.value, t.stringLiteral); + }, + JSXText(path, state) { + rename(state, path, path.node.value, t.jsxText); + }, + TemplateElement(path, state) { + const { raw, cooked } = path.node.value; + rename(state, path, raw, (next) => + t.templateElement( + { raw: next, cooked: cooked == null ? cooked : rebrandText(cooked, name) }, + path.node.tail, + ), + ); + }, + }, + }; +} + module.exports = function (api) { + // Metro's cacheVersion carries the name, so a cached config never outlives a rename. api.cache(true); + const name = rebrandName(process.env); return { presets: [["babel-preset-expo", { unstable_transformImportMeta: true }]], + plugins: name ? [[rebrandStringsPlugin, { name }]] : [], }; }; diff --git a/apps/mobile/eas.json b/apps/mobile/eas.json index 3667f582e1edb..434e0aceb4de9 100644 --- a/apps/mobile/eas.json +++ b/apps/mobile/eas.json @@ -87,7 +87,7 @@ }, "production": { "ios": { - "ascAppId": "6787819824" + "ascAppId": "6837682828" }, "android": { "track": "internal" diff --git a/apps/mobile/generated-uniwind-theme-names.json b/apps/mobile/generated-uniwind-theme-names.json index 4ec9f01f8ee7d..c66d0860c8a65 100644 --- a/apps/mobile/generated-uniwind-theme-names.json +++ b/apps/mobile/generated-uniwind-theme-names.json @@ -8,5 +8,7 @@ "ember-light", "ember-dark", "iris-light", - "iris-dark" + "iris-dark", + "easydev-light", + "easydev-dark" ] diff --git a/apps/mobile/generated-uniwind-themes.css b/apps/mobile/generated-uniwind-themes.css index 039c7d694ed5b..1c37f6bd09c78 100644 --- a/apps/mobile/generated-uniwind-themes.css +++ b/apps/mobile/generated-uniwind-themes.css @@ -1956,5 +1956,331 @@ --color-clerk-border: #191919; --color-clerk-danger: #ff6467; } + + @variant easydev-light { + --color-screen: #fafaf8; + --color-sheet: rgba(250, 250, 248, 0.98); + --color-sheet-solid: #fafaf8; + --color-card: #ffffff; + --color-grouped-card: #f5f4f0; + --color-card-alt: #ffffff; + --color-card-translucent: rgba(255, 255, 255, 0.8); + --color-thread-canvas: #fafaf8; + --color-thread-selected: #eae7df; + --color-thread-selected-foreground: #212121; + --color-thread-selected-foreground-muted: #5e5a52; + --color-thread-hover: #efede7; + --color-row-hover: #f2f0ea; + --color-composer-panel: rgba(250, 250, 248, 0.88); + --color-composer-surface: rgba(245, 244, 240, 0.94); + --color-composer-border: rgba(231, 228, 220, 0.8); + --color-foreground: #212121; + --color-foreground-secondary: #5e5a52; + --color-foreground-muted: #5e5a52; + --color-foreground-tertiary: #5e5a52; + --color-border: #e7e4dc; + --color-focus: #866a19; + --color-border-subtle: rgba(231, 228, 220, 0.7); + --color-separator: rgba(231, 228, 220, 0.55); + --color-subtle: #f5f4f0; + --color-subtle-strong: #f5f4f0; + --color-inline-skill-background: #f0eee8; + --color-inline-skill-border: rgba(134, 106, 25, 0.42); + --color-inline-skill-foreground: #212121; + --color-primary: #d4af37; + --color-prominent-action: #d4af37; + --color-prominent-action-foreground: #1a1a1a; + --color-primary-foreground: #1a1a1a; + --color-primary-text: #856d22; + --color-primary-shadow: #000000; + --color-secondary: #f5f4f0; + --color-secondary-foreground: #212121; + --color-secondary-border: #e7e4dc; + --color-switch-active-track: #d4af37; + --color-switch-active-thumb: #1a1a1a; + --color-switch-inactive-track: #f5f4f0; + --color-switch-inactive-thumb: #5e5a52; + --color-warning: #fcf1e6; + --color-warning-border: rgba(224, 123, 46, 0.32); + --color-warning-foreground: #8a4b12; + --color-danger: #fce9e6; + --color-danger-border: rgba(200, 68, 58, 0.32); + --color-danger-foreground: #b53b32; + --color-update: #f0f5fb; + --color-update-foreground: #3570b3; + --color-input: #ffffff; + --color-input-border: #e2ded5; + --color-sidebar-search: #eceae3; + --color-placeholder: #6b665d; + --color-icon: #212121; + --color-icon-muted: #77726a; + --color-icon-subtle: #5e5a52; + --color-header: rgba(250, 250, 248, 0.97); + --color-header-foreground: #212121; + --color-header-border: #e7e4dc; + --color-glass-surface: rgba(255, 255, 255, 0.74); + --color-glass-fallback: rgba(245, 244, 240, 0.94); + --color-glass-tint: rgba(255, 255, 255, 0.22); + --color-status-bar: #fafaf8; + --color-md-body: #212121; + --color-md-strong: #212121; + --color-md-link: #897124; + --color-md-blockquote-border: #e7e4dc; + --color-md-blockquote-bg: #f5f4f0; + --color-md-code-bg: #ffffff; + --color-md-code-text: #212121; + --color-md-user-code-bg: rgba(33, 33, 33, 0.18); + --color-md-user-code-text: #212121; + --color-md-user-fence-bg: rgba(0, 0, 0, 0.16); + --color-md-user-fence-text: #212121; + --color-md-hr: #e7e4dc; + --color-user-bubble: #f0eee8; + --color-user-bubble-foreground: #212121; + --color-user-bubble-foreground-muted: rgba(33, 33, 33, 0.78); + --color-user-bubble-skill-foreground: #816a21; + --color-backdrop: rgba(0, 0, 0, 0.22); + --color-drawer: #f5f4f0; + --color-drawer-foreground: #212121; + --color-drawer-foreground-muted: #5e5a52; + --color-drawer-border: #e7e4dc; + --color-drawer-shadow: rgba(0, 0, 0, 0.12); + --color-dot-separator: rgba(94, 90, 82, 0.35); + --color-wordmark: #212121; + --color-chevron: rgba(94, 90, 82, 0.42); + --color-adaptive-amber-50-950-a40: oklch(98.7% 0.022 95.277); + --color-adaptive-amber-200-900-a60: oklch(92.4% 0.12 95.746); + --color-adaptive-amber-500-a12-a16: oklch(76.9% 0.188 70.08 / 12%); + --color-adaptive-amber-500-a10-400-a10: oklch(76.9% 0.188 70.08 / 10%); + --color-adaptive-amber-500-a25-400-a25: oklch(76.9% 0.188 70.08 / 25%); + --color-adaptive-amber-700-300: oklch(55.5% 0.163 48.998); + --color-adaptive-amber-700-400: oklch(55.5% 0.163 48.998); + --color-adaptive-amber-800-200: oklch(47.3% 0.137 46.201); + --color-adaptive-blue-50-blue-400-a14: oklch(97% 0.014 254.604); + --color-adaptive-blue-300-a50-blue-400-a28: oklch(80.9% 0.105 251.813 / 50%); + --color-adaptive-blue-500-a20-blue-400-a15: oklch(62.3% 0.214 259.815 / 20%); + --color-adaptive-blue-500-400: oklch(62.3% 0.214 259.815); + --color-adaptive-blue-600-400: oklch(54.6% 0.245 262.881); + --color-adaptive-black-a10-a25: rgb(0 0 0 / 10%); + --color-adaptive-black-a15-a35: rgb(0 0 0 / 15%); + --color-adaptive-black-a2p5-white-a2p5: rgb(0 0 0 / 2.5%); + --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 12%); + --color-adaptive-emerald-600-400: oklch(59.6% 0.145 163.225); + --color-adaptive-emerald-700-300: oklch(50.8% 0.118 165.612); + --color-adaptive-fuchsia-500-a50-300-a40: oklch(66.7% 0.295 322.15 / 50%); + --color-adaptive-fuchsia-600-300: oklch(59.1% 0.293 322.896); + --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 12%); + --color-adaptive-indigo-600-300: oklch(51.1% 0.262 276.966); + --color-adaptive-indigo-700-300: oklch(45.7% 0.24 277.023); + --color-adaptive-neutral-100-900: oklch(97% 0 none); + --color-adaptive-neutral-200-700-a60: oklch(92.2% 0 none); + --color-adaptive-neutral-200-800: oklch(92.2% 0 none); + --color-adaptive-neutral-200-a70-white-a8: oklch(92.2% 0 none / 70%); + --color-adaptive-neutral-200-white-a6: oklch(92.2% 0 none); + --color-adaptive-neutral-200-white-a8: oklch(92.2% 0 none); + --color-adaptive-neutral-200-a80-white-a8: oklch(92.2% 0 none / 80%); + --color-adaptive-neutral-300-a60-white-a12: oklch(87% 0 none / 60%); + --color-adaptive-neutral-400-500: oklch(70.8% 0 none); + --color-adaptive-neutral-400-a60-500-a60: oklch(70.8% 0 none / 60%); + --color-adaptive-neutral-400-a80-500-a80: oklch(70.8% 0 none / 80%); + --color-adaptive-neutral-500-a10-a16: oklch(55.6% 0 none / 10%); + --color-adaptive-neutral-500-400: oklch(55.6% 0 none); + --color-adaptive-neutral-500-500: oklch(55.6% 0 none); + --color-adaptive-neutral-600-300: oklch(43.9% 0 none); + --color-adaptive-neutral-600-400: oklch(43.9% 0 none); + --color-adaptive-neutral-950-50: oklch(14.5% 0 none); + --color-adaptive-neutral-950-a5-white-a5: oklch(14.5% 0 none / 5%); + --color-adaptive-neutral-950-a10-white-a10: oklch(14.5% 0 none / 10%); + --color-adaptive-red-50-950-a80: oklch(97.1% 0.013 17.38); + --color-adaptive-red-200-800: oklch(88.5% 0.062 18.334); + --color-adaptive-red-600-a80-400-a80: oklch(57.7% 0.245 27.325 / 80%); + --color-adaptive-red-700-300: oklch(50.5% 0.213 27.518); + --color-adaptive-rose-100-500-a18: oklch(94.1% 0.03 12.58); + --color-adaptive-rose-100-a80-500-a12: oklch(94.1% 0.03 12.58 / 80%); + --color-adaptive-rose-300-a70-400-a28: oklch(81% 0.117 11.638 / 70%); + --color-adaptive-rose-500-a12-a16: oklch(64.5% 0.246 16.439 / 12%); + --color-adaptive-rose-500-400: oklch(64.5% 0.246 16.439); + --color-adaptive-rose-600-400: oklch(58.6% 0.253 17.585); + --color-adaptive-rose-700-300: oklch(51.4% 0.222 16.935); + --color-adaptive-sky-500-a12-a16: oklch(68.5% 0.169 237.323 / 12%); + --color-adaptive-sky-500-a10-400-a10: oklch(68.5% 0.169 237.323 / 10%); + --color-adaptive-sky-500-a25-400-a25: oklch(68.5% 0.169 237.323 / 25%); + --color-adaptive-sky-600-400: oklch(58.8% 0.158 241.966); + --color-adaptive-sky-700-300: oklch(50% 0.134 242.749); + --color-adaptive-violet-500-a12-a16: oklch(60.6% 0.25 292.717 / 12%); + --color-adaptive-violet-600-400: oklch(54.1% 0.281 293.009); + --color-adaptive-violet-700-300: oklch(49.1% 0.27 292.581); + --color-adaptive-white-neutral-950-a70: #fff; + --color-adaptive-zinc-500-a12-a16: oklch(55.2% 0.016 285.938 / 12%); + --color-adaptive-zinc-500-400: oklch(55.2% 0.016 285.938); + --color-adaptive-zinc-600-300: oklch(44.2% 0.017 285.786); + --color-clerk-page: #fcfcfc; + --color-clerk-foreground: #27272a; + --color-clerk-foreground-muted: #71717b; + --color-clerk-border: #e4e4e7; + --color-clerk-danger: #c10007; + } + + @variant easydev-dark { + --color-screen: #121110; + --color-sheet: rgba(18, 17, 16, 0.98); + --color-sheet-solid: #121110; + --color-card: #1a1916; + --color-grouped-card: #1a1916; + --color-card-alt: #22201d; + --color-card-translucent: rgba(26, 25, 22, 0.8); + --color-thread-canvas: #121110; + --color-thread-selected: #22201d; + --color-thread-selected-foreground: #f3f1ec; + --color-thread-selected-foreground-muted: #b8b2a7; + --color-thread-hover: #1e1c19; + --color-row-hover: #22201d; + --color-composer-panel: rgba(18, 17, 16, 0.92); + --color-composer-surface: rgba(26, 25, 22, 0.9); + --color-composer-border: rgba(36, 34, 31, 0.46); + --color-foreground: #f3f1ec; + --color-foreground-secondary: #b8b2a7; + --color-foreground-muted: #b8b2a7; + --color-foreground-tertiary: #b8b2a7; + --color-border: #24221f; + --color-focus: #d4af37; + --color-border-subtle: rgba(36, 34, 31, 0.7); + --color-separator: rgba(36, 34, 31, 0.55); + --color-subtle: #1a1916; + --color-subtle-strong: #22201d; + --color-inline-skill-background: #2b2925; + --color-inline-skill-border: rgba(212, 175, 55, 0.42); + --color-inline-skill-foreground: #f3f1ec; + --color-primary: #d4af37; + --color-prominent-action: #d4af37; + --color-prominent-action-foreground: #1a1a1a; + --color-primary-foreground: #1a1a1a; + --color-primary-text: #d4af37; + --color-primary-shadow: #000000; + --color-secondary: #22201d; + --color-secondary-foreground: #f3f1ec; + --color-secondary-border: #24221f; + --color-switch-active-track: #d4af37; + --color-switch-active-thumb: #1a1a1a; + --color-switch-inactive-track: #22201d; + --color-switch-inactive-thumb: #b8b2a7; + --color-warning: #33241a; + --color-warning-border: rgba(242, 154, 78, 0.32); + --color-warning-foreground: #f29a4e; + --color-danger: #3a1f1c; + --color-danger-border: rgba(236, 123, 110, 0.32); + --color-danger-foreground: #ec7b6e; + --color-update: #1c2633; + --color-update-foreground: #7fb0e8; + --color-input: #1a1916; + --color-input-border: #34312c; + --color-sidebar-search: #1a1916; + --color-placeholder: #8f897e; + --color-icon: #f3f1ec; + --color-icon-muted: #8f897e; + --color-icon-subtle: #b8b2a7; + --color-header: rgba(18, 17, 16, 0.97); + --color-header-foreground: #f3f1ec; + --color-header-border: #24221f; + --color-glass-surface: rgba(34, 32, 29, 0.74); + --color-glass-fallback: rgba(26, 25, 22, 0.9); + --color-glass-tint: rgba(34, 32, 29, 0.22); + --color-status-bar: #121110; + --color-md-body: #f3f1ec; + --color-md-strong: #f3f1ec; + --color-md-link: #d4af37; + --color-md-blockquote-border: #24221f; + --color-md-blockquote-bg: #1a1916; + --color-md-code-bg: #1a1916; + --color-md-code-text: #f3f1ec; + --color-md-user-code-bg: rgba(243, 241, 236, 0.18); + --color-md-user-code-text: #f3f1ec; + --color-md-user-fence-bg: rgba(0, 0, 0, 0.28); + --color-md-user-fence-text: #f3f1ec; + --color-md-hr: #24221f; + --color-user-bubble: #22201d; + --color-user-bubble-foreground: #f3f1ec; + --color-user-bubble-foreground-muted: rgba(243, 241, 236, 0.78); + --color-user-bubble-skill-foreground: #d4af37; + --color-backdrop: rgba(0, 0, 0, 0.48); + --color-drawer: #161513; + --color-drawer-foreground: #f3f1ec; + --color-drawer-foreground-muted: #b8b2a7; + --color-drawer-border: #24221f; + --color-drawer-shadow: rgba(0, 0, 0, 0.32); + --color-dot-separator: rgba(184, 178, 167, 0.35); + --color-wordmark: #f3f1ec; + --color-chevron: rgba(184, 178, 167, 0.42); + --color-adaptive-amber-50-950-a40: oklch(27.9% 0.077 45.635 / 40%); + --color-adaptive-amber-200-900-a60: oklch(41.4% 0.112 45.904 / 60%); + --color-adaptive-amber-500-a12-a16: oklch(76.9% 0.188 70.08 / 16%); + --color-adaptive-amber-500-a10-400-a10: oklch(82.8% 0.189 84.429 / 10%); + --color-adaptive-amber-500-a25-400-a25: oklch(82.8% 0.189 84.429 / 25%); + --color-adaptive-amber-700-300: oklch(87.9% 0.169 91.605); + --color-adaptive-amber-700-400: oklch(82.8% 0.189 84.429); + --color-adaptive-amber-800-200: oklch(92.4% 0.12 95.746); + --color-adaptive-blue-50-blue-400-a14: oklch(70.7% 0.165 254.624 / 14%); + --color-adaptive-blue-300-a50-blue-400-a28: oklch(70.7% 0.165 254.624 / 28%); + --color-adaptive-blue-500-a20-blue-400-a15: oklch(70.7% 0.165 254.624 / 15%); + --color-adaptive-blue-500-400: oklch(70.7% 0.165 254.624); + --color-adaptive-blue-600-400: oklch(70.7% 0.165 254.624); + --color-adaptive-black-a10-a25: rgb(0 0 0 / 25%); + --color-adaptive-black-a15-a35: rgb(0 0 0 / 35%); + --color-adaptive-black-a2p5-white-a2p5: rgb(255 255 255 / 2.5%); + --color-adaptive-emerald-500-a12-a16: oklch(69.6% 0.17 162.48 / 16%); + --color-adaptive-emerald-600-400: oklch(76.5% 0.177 163.223); + --color-adaptive-emerald-700-300: oklch(84.5% 0.143 164.978); + --color-adaptive-fuchsia-500-a50-300-a40: oklch(83.3% 0.145 321.434 / 40%); + --color-adaptive-fuchsia-600-300: oklch(83.3% 0.145 321.434); + --color-adaptive-indigo-500-a12-a16: oklch(58.5% 0.233 277.117 / 16%); + --color-adaptive-indigo-600-300: oklch(78.5% 0.115 274.713); + --color-adaptive-indigo-700-300: oklch(78.5% 0.115 274.713); + --color-adaptive-neutral-100-900: oklch(20.5% 0 none); + --color-adaptive-neutral-200-700-a60: oklch(37.1% 0 none / 60%); + --color-adaptive-neutral-200-800: oklch(26.9% 0 none); + --color-adaptive-neutral-200-a70-white-a8: rgb(255 255 255 / 8%); + --color-adaptive-neutral-200-white-a6: rgb(255 255 255 / 6%); + --color-adaptive-neutral-200-white-a8: rgb(255 255 255 / 8%); + --color-adaptive-neutral-200-a80-white-a8: rgb(255 255 255 / 8%); + --color-adaptive-neutral-300-a60-white-a12: rgb(255 255 255 / 12%); + --color-adaptive-neutral-400-500: oklch(55.6% 0 none); + --color-adaptive-neutral-400-a60-500-a60: oklch(55.6% 0 none / 60%); + --color-adaptive-neutral-400-a80-500-a80: oklch(55.6% 0 none / 80%); + --color-adaptive-neutral-500-a10-a16: oklch(55.6% 0 none / 16%); + --color-adaptive-neutral-500-400: oklch(70.8% 0 none); + --color-adaptive-neutral-500-500: oklch(55.6% 0 none); + --color-adaptive-neutral-600-300: oklch(87% 0 none); + --color-adaptive-neutral-600-400: oklch(70.8% 0 none); + --color-adaptive-neutral-950-50: oklch(98.5% 0 none); + --color-adaptive-neutral-950-a5-white-a5: rgb(255 255 255 / 5%); + --color-adaptive-neutral-950-a10-white-a10: rgb(255 255 255 / 10%); + --color-adaptive-red-50-950-a80: oklch(25.8% 0.092 26.042 / 80%); + --color-adaptive-red-200-800: oklch(44.4% 0.177 26.899); + --color-adaptive-red-600-a80-400-a80: oklch(70.4% 0.191 22.216 / 80%); + --color-adaptive-red-700-300: oklch(80.8% 0.114 19.571); + --color-adaptive-rose-100-500-a18: oklch(64.5% 0.246 16.439 / 18%); + --color-adaptive-rose-100-a80-500-a12: oklch(64.5% 0.246 16.439 / 12%); + --color-adaptive-rose-300-a70-400-a28: oklch(71.2% 0.194 13.428 / 28%); + --color-adaptive-rose-500-a12-a16: oklch(64.5% 0.246 16.439 / 16%); + --color-adaptive-rose-500-400: oklch(71.2% 0.194 13.428); + --color-adaptive-rose-600-400: oklch(71.2% 0.194 13.428); + --color-adaptive-rose-700-300: oklch(81% 0.117 11.638); + --color-adaptive-sky-500-a12-a16: oklch(68.5% 0.169 237.323 / 16%); + --color-adaptive-sky-500-a10-400-a10: oklch(74.6% 0.16 232.661 / 10%); + --color-adaptive-sky-500-a25-400-a25: oklch(74.6% 0.16 232.661 / 25%); + --color-adaptive-sky-600-400: oklch(74.6% 0.16 232.661); + --color-adaptive-sky-700-300: oklch(82.8% 0.111 230.318); + --color-adaptive-violet-500-a12-a16: oklch(60.6% 0.25 292.717 / 16%); + --color-adaptive-violet-600-400: oklch(70.2% 0.183 293.541); + --color-adaptive-violet-700-300: oklch(81.1% 0.111 293.571); + --color-adaptive-white-neutral-950-a70: oklch(14.5% 0 none / 70%); + --color-adaptive-zinc-500-a12-a16: oklch(55.2% 0.016 285.938 / 16%); + --color-adaptive-zinc-500-400: oklch(70.5% 0.015 286.067); + --color-adaptive-zinc-600-300: oklch(87.1% 0.006 286.286); + --color-clerk-page: #0a0a0a; + --color-clerk-foreground: #f5f5f5; + --color-clerk-foreground-muted: #818181; + --color-clerk-border: #191919; + --color-clerk-danger: #ff6467; + } } } diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 7a4cd4eff5046..f265711a74094 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -17,10 +17,15 @@ /* ─── Typography ────────────────────────────────────────────────────── */ @theme { - /* Keep these native family names aligned with app.config.ts. */ + /* Keep these native family names aligned with app.config.ts. Standalone builds replace them + at runtime with src/lib/easydevFonts.ts. */ --font-sans: "DMSans-Regular"; --font-medium: "DMSans-Medium"; + /* `t3-` keeps these clear of the font-weight utilities of the same name. */ + --font-t3-semibold: "DMSans-Regular"; --font-bold: "DMSans-Bold"; + --font-display: "DMSans-Medium"; + --font-display-bold: "DMSans-Bold"; /* Keep this scale aligned with src/lib/typography.ts for native style props. */ --text-3xs: 11px; diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js index 6371da34fd190..900f8b73dd75d 100644 --- a/apps/mobile/metro.config.js +++ b/apps/mobile/metro.config.js @@ -18,6 +18,7 @@ const licenseGeneratorSource = path.join( const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const generatedDeviceStreamRoot = path.join(__dirname, ".generated", "device-stream"); const generatedPreviewStreamRoot = path.join(__dirname, ".generated", "preview-stream"); +const rebrandedTranslationsRoot = path.join(__dirname, ".generated", "rebrand", "translations"); config.watchFolders = [...new Set([...(config.watchFolders ?? []), workspaceRoot])]; config.resolver = { @@ -110,11 +111,48 @@ async function prepareStreamScripts() { } } -module.exports = Promise.all([generateMobileThirdPartyLicenses(), prepareStreamScripts()]).then( - () => - withUniwindConfig(config, { - cssEntryFile: "./global.css", - extraThemes, - polyfills: { rem: 14 }, - }), +// Metro reads JSON without Babel, so a standalone build serves catalogs keyed by its renamed source. +async function rebrandTranslationCatalogs() { + const importScript = (name) => + import(pathToFileURL(path.join(workspaceRoot, "scripts", "lib", name)).href); + const [{ loadRepoEnv }, { rebrandName, rebrandCatalogFile }] = await Promise.all([ + importScript("public-config.ts"), + importScript("rebrand.ts"), + ]); + const repoEnv = loadRepoEnv(); + const name = rebrandName(repoEnv); + if (!name) return; + // babel.config.js renames the source in Metro's workers, which inherit this environment. + process.env.T3CODE_STANDALONE = repoEnv.T3CODE_STANDALONE; + process.env.T3CODE_APP_NAME = repoEnv.T3CODE_APP_NAME; + config.cacheVersion = `${config.cacheVersion ?? ""}:${name}`; + const sourceDir = path.join(__dirname, "src", "i18n", "translations"); + await fs.promises.mkdir(rebrandedTranslationsRoot, { recursive: true }); + for (const file of await fs.promises.readdir(sourceDir)) { + const catalog = rebrandCatalogFile(path.join(sourceDir, file), name); + if (catalog) { + await writeFileIfChanged(path.join(rebrandedTranslationsRoot, file), JSON.stringify(catalog)); + } + } + const i18nProvider = path.join(__dirname, "src", "i18n", "I18nProvider.tsx"); + const resolveRequest = config.resolver.resolveRequest; + config.resolver.resolveRequest = (context, moduleName, platform) => { + const catalog = /^\.\/translations\/([\w-]+\.json)$/.exec(moduleName)?.[1]; + if (catalog && context.originModulePath === i18nProvider) { + return { type: "sourceFile", filePath: path.join(rebrandedTranslationsRoot, catalog) }; + } + return (resolveRequest ?? context.resolveRequest)(context, moduleName, platform); + }; +} + +module.exports = Promise.all([ + generateMobileThirdPartyLicenses(), + prepareStreamScripts(), + rebrandTranslationCatalogs(), +]).then(() => + withUniwindConfig(config, { + cssEntryFile: "./global.css", + extraThemes, + polyfills: { rem: 14 }, + }), ); diff --git a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt index 69d9ae623b27b..b12006aaed85b 100644 --- a/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt +++ b/apps/mobile/modules/t3-composer-editor/android/src/main/java/expo/modules/t3composereditor/T3ComposerEditorModule.kt @@ -5,6 +5,7 @@ import expo.modules.kotlin.modules.ModuleDefinition import android.content.ClipData import android.content.ClipboardManager import android.content.Context +import android.content.pm.PackageManager import org.json.JSONObject import org.json.JSONArray @@ -15,6 +16,9 @@ internal object T3ComposerClipboard { fun write(context: Context, text: String, fragment: String) { val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val label = context.packageManager + .getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) + .metaData?.getString("t3.productName") ?: "T3 Code" val payload = try { JSONObject(fragment) } catch (_: Exception) { @@ -22,7 +26,7 @@ internal object T3ComposerClipboard { } val records = payload?.optJSONArray("records") if (payload == null || records == null) { - clipboard.setPrimaryClip(ClipData.newPlainText("T3 Code", text)) + clipboard.setPrimaryClip(ClipData.newPlainText(label, text)) return } val all = (0 until records.length()).map { records.getJSONObject(it) } @@ -40,12 +44,12 @@ internal object T3ComposerClipboard { clipboard.setPrimaryClip( if (selected.isEmpty()) { ClipData.newPlainText( - "T3 Code", + label, text ) } else { ClipData.newHtmlText( - "T3 Code", + label, text, "
$escaped
" ) diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt index 2d1fd4a248558..9db57853c04e7 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt @@ -3,6 +3,7 @@ package expo.modules.t3nativecontrols import android.content.ContentValues import android.content.Context import android.content.Intent +import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Environment @@ -120,6 +121,10 @@ class T3NativeControlsModule : Module() { } } +private fun productName(context: Context): String = + context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) + .metaData?.getString("t3.productName") ?: "T3 Code" + // Android 10+ lets apps add their own media without a storage permission. @RequiresApi(Build.VERSION_CODES.Q) private fun saveImageToPictures(context: Context, source: Uri, mimeType: String, name: String) { @@ -127,7 +132,10 @@ private fun saveImageToPictures(context: Context, source: Uri, mimeType: String, val values = ContentValues().apply { put(MediaStore.Images.Media.DISPLAY_NAME, name) put(MediaStore.Images.Media.MIME_TYPE, mimeType) - put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/T3 Code") + put( + MediaStore.Images.Media.RELATIVE_PATH, + "${Environment.DIRECTORY_PICTURES}/${productName(context)}" + ) put(MediaStore.Images.Media.IS_PENDING, 1) } val target = resolver.insert( diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index c8ec3886974a9..c039eb0628206 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -5,6 +5,9 @@ import Security import UIKit import UniformTypeIdentifiers +let photosPermissionMessage = + "Allow \(Bundle.main.object(forInfoDictionaryKey: "T3ProductName") as? String ?? "T3 Code") to add photos in Settings." + @ExpoModule("T3NativeControls") public final class T3NativeControlsModule: Module { private let presentationSources = T3PresentationSources() @@ -348,7 +351,7 @@ public final class T3NativeControlsModule: Module { promise.reject(NSError( domain: "T3NativePhotos", code: 1, - userInfo: [NSLocalizedDescriptionKey: "Allow T3 Code to add photos in Settings."] + userInfo: [NSLocalizedDescriptionKey: photosPermissionMessage] )) return } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift index 382e92875f303..719cf9fab7b7f 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift @@ -870,7 +870,7 @@ final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIG PHPhotoLibrary.requestAuthorization(for: .addOnly) { [weak self] status in guard status == .authorized || status == .limited else { cleanUp() - DispatchQueue.main.async { self?.showSaveError("Allow T3 Code to add photos in Settings.") } + DispatchQueue.main.async { self?.showSaveError(photosPermissionMessage) } return } PHPhotoLibrary.shared().performChanges({ diff --git a/apps/mobile/modules/t3-preview-tunnel/ios/T3TunnelWebView.swift b/apps/mobile/modules/t3-preview-tunnel/ios/T3TunnelWebView.swift index df653b8b08dd6..40bcbd5422627 100644 --- a/apps/mobile/modules/t3-preview-tunnel/ios/T3TunnelWebView.swift +++ b/apps/mobile/modules/t3-preview-tunnel/ios/T3TunnelWebView.swift @@ -270,13 +270,15 @@ private final class T3EnvironmentProxy { func store(proxyPort: UInt16) -> WKWebsiteDataStore { if let dataStore { return dataStore } let store = WKWebsiteDataStore.nonPersistent() - var proxy = ProxyConfiguration( - socksv5Proxy: .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: proxyPort)!) + // The C API, not the Swift overlay: the overlay links libswiftWebKit, which older iOS + // versions don't have, so the app would fail to launch there. + let proxy = nw_proxy_config_create_socksv5( + nw_endpoint_create_host("127.0.0.1", String(proxyPort)) ) // Only the stand-in host belongs to the environment; everything else loads directly. - proxy.matchDomains = [T3Loopback.standInHost] - proxy.allowFailover = false - store.proxyConfigurations = [proxy] + nw_proxy_config_add_match_domain(proxy, T3Loopback.standInHost) + nw_proxy_config_set_failover_allowed(proxy, false) + store.__proxyConfigurations = [proxy] dataStore = store return store } diff --git a/apps/mobile/plugins/withProductName.cjs b/apps/mobile/plugins/withProductName.cjs new file mode 100644 index 0000000000000..abb30ded128d2 --- /dev/null +++ b/apps/mobile/plugins/withProductName.cjs @@ -0,0 +1,19 @@ +"use strict"; + +const { AndroidConfig, withAndroidManifest, withInfoPlist } = require("expo/config-plugins"); + +// Native copy names the product, not the variant's display name ("T3 Code Dev"). +module.exports = function withProductName(config, name) { + config = withInfoPlist(config, (next) => { + next.modResults.T3ProductName = name; + return next; + }); + return withAndroidManifest(config, (next) => { + AndroidConfig.Manifest.addMetaDataItemToMainApplication( + AndroidConfig.Manifest.getMainApplicationOrThrow(next.modResults), + "t3.productName", + name, + ); + return next; + }); +}; diff --git a/apps/mobile/plugins/withStandaloneNotificationMark.cjs b/apps/mobile/plugins/withStandaloneNotificationMark.cjs new file mode 100644 index 0000000000000..e3e996ab194c7 --- /dev/null +++ b/apps/mobile/plugins/withStandaloneNotificationMark.cjs @@ -0,0 +1,28 @@ +"use strict"; + +// App resources override same-named library resources, so this replaces the T3 mark that the +// t3-agent-notifications module ships, without editing the module. + +const path = require("path"); +const fs = require("fs"); +const { withDangerousMod } = require("expo/config-plugins"); + +module.exports = function withStandaloneNotificationMark(config) { + return withDangerousMod(config, [ + "android", + (cfg) => { + const source = path.join( + cfg.modRequest.projectRoot, + "..", + "..", + "assets", + "easydev", + "agent_activity_mark.xml", + ); + const targetDir = path.join(cfg.modRequest.platformProjectRoot, "app/src/main/res/drawable"); + fs.mkdirSync(targetDir, { recursive: true }); + fs.copyFileSync(source, path.join(targetDir, "agent_activity_mark.xml")); + return cfg; + }, + ]); +}; diff --git a/apps/mobile/plugins/withWidgetLogoAsset.cjs b/apps/mobile/plugins/withWidgetLogoAsset.cjs index d20d199119b05..04da1e025ae89 100644 --- a/apps/mobile/plugins/withWidgetLogoAsset.cjs +++ b/apps/mobile/plugins/withWidgetLogoAsset.cjs @@ -31,7 +31,10 @@ function withAssetFiles(config) { return withDangerousMod(config, [ "ios", (cfg) => { - const source = path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME); + // app.config.ts copies repo .env values into process.env before plugins run. + const source = /^(1|true)$/i.test(process.env.T3CODE_STANDALONE?.trim() ?? "") + ? path.join(cfg.modRequest.projectRoot, "..", "..", "assets", "easydev", "widget-mark.svg") + : path.join(cfg.modRequest.projectRoot, "assets", "widget", SVG_NAME); const catalogDir = path.join(cfg.modRequest.platformProjectRoot, TARGET_NAME, CATALOG_NAME); const imageSetDir = path.join(catalogDir, IMAGE_SET); fs.mkdirSync(imageSetDir, { recursive: true }); diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index 16a77b049efa3..a41d706280d50 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -20,7 +20,6 @@ import { type NavigationState, } from "@react-navigation/native"; import { pipe } from "effect/Function"; -import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages"; @@ -56,8 +55,12 @@ import { subscribeComposerDraftModelReconciliation } from "./state/use-composer- import { environmentThreadShells, threadEnvironment } from "./state/threads"; import { environmentShell, shellCachesReadAtom } from "./state/shell"; import { OverlayPortalHost } from "./components/ui/OverlayPortal"; -import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking"; -import { hasCloudPublicConfig } from "./features/cloud/publicConfig"; +import { + hostedAppLinkPrefixes, + shouldHandleAppLink, + restoreDraftLinkState, +} from "./lib/appLinking"; +import { hasCloudPublicConfig, resolveHostedAppUrl } from "./features/cloud/publicConfig"; import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state"; import { pairingFormLinkAction, @@ -143,7 +146,7 @@ const appLinking = { "t3code://", "t3code-dev://", "t3code-preview://", - DEFAULT_HOSTED_APP_URL, + ...hostedAppLinkPrefixes(resolveHostedAppUrl()), ], config: { initialRouteName: "Home" }, filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()), diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 696b01ce29692..e7207c07f466f 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -151,6 +151,7 @@ import { } from "./features/layout/workspace-overlay-routes"; import { ShowcaseReadyMarker } from "./features/showcase/ShowcaseCaptureCoordinator"; import { immersiveRoute, modalRoute, pageRoute, sheetRoute } from "./features/layout/route-options"; +import { FONT_FAMILIES } from "./lib/fontFamilies"; import { deriveLayout } from "./lib/layout"; import { useNativeLayoutMetrics } from "./native/native-layout-metrics"; import { isPresentedRoute } from "./native/workspace-stack-projection"; @@ -369,7 +370,11 @@ const SETTINGS_SCREENS = { linking: "settings/scheduled-tasks", options: { ...settingsPage(), - headerTitleStyle: { fontSize: 16, fontWeight: "800" }, + headerTitleStyle: { + fontSize: 16, + fontWeight: "800", + ...(FONT_FAMILIES.headerHeavy ? { fontFamily: FONT_FAMILIES.headerHeavy } : {}), + }, }, }), SettingsScheduledTaskNew: createNativeStackScreen({ @@ -536,7 +541,7 @@ function NotFoundScreen() { }} style={[{ flex: 1 }, screenBgStyle]} > - + Route not found {WORDMARK_SUFFIX} diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx index 0a8f515787fce..0137b57014781 100644 --- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx +++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx @@ -100,6 +100,7 @@ function emit(value: string, resetGeneration = native.resetGeneration) { } vi.mock("expo", () => ({ requireNativeView: () => NativeView })); +vi.mock("expo-constants", () => ({ default: { expoConfig: { extra: {} } } })); // Vite resolves the platform-neutral module; the race lives in the iOS editor. vi.mock("../native/T3ComposerEditor", () => import("../native/T3ComposerEditor.ios")); vi.mock("react-native", () => ({ StyleSheet: { flatten: (style: unknown) => style } })); diff --git a/apps/mobile/src/components/T3Wordmark.tsx b/apps/mobile/src/components/T3Wordmark.tsx index d7cac80d8f58f..6ff8be9d664f0 100644 --- a/apps/mobile/src/components/T3Wordmark.tsx +++ b/apps/mobile/src/components/T3Wordmark.tsx @@ -1,14 +1,68 @@ +import Constants from "expo-constants"; import type { ColorValue } from "react-native"; -import Svg, { Path } from "react-native-svg"; +import Svg, { G, Path } from "react-native-svg"; import { withUniwind } from "uniwind"; const ThemedPath = withUniwind(Path); +const ThemedGroup = withUniwind(G); -export function T3Wordmark(props: { +const isStandaloneBuild = Constants.expoConfig?.extra?.standalone === true; + +// "EasyDev" in Space Grotesk Bold, outlined; cap height 100, the y descends to 128.57. +const EASYDEV_WORDMARK_PATH = + "M9.43 100L9.43 0L73.71 0L73.71 17.14L28.29 17.14L28.29 41L69.71 41L69.71 58.14L28.29 58.14L28.29 82.86L74.57 82.86L74.57 100ZM111.14 102Q103.57 102 97.57 99.36Q91.57 96.71 88.07 91.64Q84.57 86.57 84.57 79.29Q84.57 72 88.07 67.07Q91.57 62.14 97.79 59.64Q104 57.14 112 57.14L131.43 57.14L131.43 53.14Q131.43 48.14 128.29 44.93Q125.14 41.71 118.29 41.71Q111.57 41.71 108.29 44.79Q105 47.86 104 52.71L87.43 47.14Q89.14 41.71 92.93 37.21Q96.71 32.71 103.07 29.93Q109.43 27.14 118.57 27.14Q132.57 27.14 140.71 34.14Q148.86 41.14 148.86 54.43L148.86 80.86Q148.86 85.14 152.86 85.14L158.57 85.14L158.57 100L146.57 100Q141.29 100 137.86 97.43Q134.43 94.86 134.43 90.57L134.43 90.43L131.71 90.43Q131.14 92.14 129.14 94.93Q127.14 97.71 122.86 99.86Q118.57 102 111.14 102ZM114.29 87.43Q121.86 87.43 126.64 83.21Q131.43 79 131.43 72L131.43 70.57L113.29 70.57Q108.29 70.57 105.43 72.71Q102.57 74.86 102.57 78.71Q102.57 82.57 105.57 85Q108.57 87.43 114.29 87.43ZM201.14 102Q187.29 102 178.43 96Q169.57 90 167.71 78.86L184.29 74.57Q185.29 79.57 187.64 82.43Q190 85.29 193.5 86.5Q197 87.71 201.14 87.71Q207.43 87.71 210.43 85.5Q213.43 83.29 213.43 80Q213.43 76.71 210.57 74.93Q207.71 73.14 201.43 72L197.43 71.29Q190 69.86 183.86 67.36Q177.71 64.86 174 60.43Q170.29 56 170.29 49Q170.29 38.43 178 32.79Q185.71 27.14 198.29 27.14Q210.14 27.14 218 32.43Q225.86 37.71 228.29 46.29L211.57 51.43Q210.43 46 206.93 43.71Q203.43 41.43 198.29 41.43Q193.14 41.43 190.43 43.21Q187.71 45 187.71 48.14Q187.71 51.57 190.57 53.21Q193.43 54.86 198.29 55.71L202.29 56.43Q210.29 57.86 216.79 60.21Q223.29 62.57 227.07 66.93Q230.86 71.29 230.86 78.71Q230.86 89.86 222.79 95.93Q214.71 102 201.14 102ZM254.29 128.57L254.29 112.86L292.86 112.86Q296.86 112.86 296.86 108.57L296.86 90.71L294.29 90.71Q293.14 93.14 290.71 95.57Q288.29 98 284.14 99.57Q280 101.14 273.57 101.14Q265.29 101.14 259.07 97.36Q252.86 93.57 249.43 86.86Q246 80.14 246 71.43L246 29.14L264 29.14L264 70Q264 78 267.93 82Q271.86 86 279.14 86Q287.43 86 292 80.5Q296.57 75 296.57 65.14L296.57 29.14L314.57 29.14L314.57 112.57Q314.57 119.86 310.29 124.21Q306 128.57 298.86 128.57ZM331.14 100L331.14 83.43L344.29 83.43L344.29 16.57L331.14 16.57L331.14 0L372.29 0Q392.43 0 402.93 10.21Q413.43 20.43 413.43 40.57L413.43 59.43Q413.43 79.57 402.93 89.79Q392.43 100 372.29 100ZM363.14 82.86L372.57 82.86Q384 82.86 389.29 76.86Q394.57 70.86 394.57 60L394.57 40Q394.57 29 389.29 23.07Q384 17.14 372.57 17.14L363.14 17.14ZM462 102Q451.43 102 443.36 97.5Q435.29 93 430.79 84.79Q426.29 76.57 426.29 65.43L426.29 63.71Q426.29 52.57 430.71 44.36Q435.14 36.14 443.14 31.64Q451.14 27.14 461.71 27.14Q472.14 27.14 479.86 31.79Q487.57 36.43 491.86 44.64Q496.14 52.86 496.14 63.71L496.14 69.86L444.57 69.86Q444.86 77.14 450 81.71Q455.14 86.29 462.57 86.29Q470.14 86.29 473.71 83Q477.29 79.71 479.14 75.71L493.86 83.43Q491.86 87.14 488.07 91.5Q484.29 95.86 478 98.93Q471.71 102 462 102ZM444.71 56.43L477.86 56.43Q477.29 50.29 472.93 46.57Q468.57 42.86 461.57 42.86Q454.29 42.86 450 46.57Q445.71 50.29 444.71 56.43ZM527 100L504.43 29.14L523.57 29.14L540 86.86L542.57 86.86L559 29.14L578.14 29.14L555.57 100Z"; +const EASYDEV_WORDMARK_DESCENT = 28.57 / 100; + +interface BrandProps { readonly height: number; readonly color?: ColorValue; readonly colorClassName?: string; -}) { +} + +function EasyDevWordmark(props: BrandProps) { + const height = props.height * (1 + EASYDEV_WORDMARK_DESCENT); + return ( + + + + ); +} + +function EasyDevMark(props: BrandProps) { + return ( + + + + + + + ); +} + +/** The brand at icon size: the T3 wordmark upstream, the EasyDev mark in standalone builds. */ +export function BrandGlyph(props: BrandProps) { + return isStandaloneBuild ? : ; +} + +export function T3Wordmark(props: BrandProps) { + if (isStandaloneBuild) return ; const aspectRatio = 94.3941 / 56.96; return ( ) : null} - {props.title} + {props.title} {props.description} diff --git a/apps/mobile/src/connection/catalog.ts b/apps/mobile/src/connection/catalog.ts index 971fa891106fc..5ceabda028211 100644 --- a/apps/mobile/src/connection/catalog.ts +++ b/apps/mobile/src/connection/catalog.ts @@ -1,5 +1,11 @@ import { createEnvironmentCatalogAtoms } from "@t3tools/client-runtime/state/connections"; +import { appAtomRegistry } from "../state/atom-registry"; import { connectionAtomRuntime } from "./runtime"; export const environmentCatalog = createEnvironmentCatalogAtoms(connectionAtomRuntime); + +/** Rebuilds the connection runtime, whose construction reads the saved catalog. */ +export function retryEnvironmentCatalogLoad(): void { + appAtomRegistry.refresh(connectionAtomRuntime); +} diff --git a/apps/mobile/src/features/cloud/publicConfig.test.ts b/apps/mobile/src/features/cloud/publicConfig.test.ts index 8c09819aa72f3..e911bcb227a53 100644 --- a/apps/mobile/src/features/cloud/publicConfig.test.ts +++ b/apps/mobile/src/features/cloud/publicConfig.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { resolveCloudPublicConfig } from "./publicConfig"; +import { + resolveCloudPublicConfig, + resolveHostedAppUrl, + resolveReleaseRepository, +} from "./publicConfig"; vi.mock("expo-constants", () => ({ default: { @@ -33,3 +37,26 @@ describe("resolveCloudPublicConfig", () => { }); }); }); + +describe("resolveHostedAppUrl", () => { + it.each([ + [{ hostedAppUrl: "https://app.fork.example" }, "https://app.fork.example/"], + // A standalone build without a hosted app; the manifest cannot carry null. + [{ hostedAppUrl: "" }, null], + [{}, undefined], + [undefined, undefined], + ])("resolves %j to %j", (extra, expected) => { + expect(resolveHostedAppUrl(extra)).toBe(expected); + }); +}); + +describe("resolveReleaseRepository", () => { + it.each([ + [{ releaseRepository: " fork/t3code " }, "fork/t3code"], + [{ releaseRepository: "" }, undefined], + [{ releaseRepository: "fork/t3code/extra" }, undefined], + [{ releaseRepository: "https://github.com/fork/t3code" }, undefined], + ])("resolves %j to %j", (extra, expected) => { + expect(resolveReleaseRepository(extra)).toBe(expected); + }); +}); diff --git a/apps/mobile/src/features/cloud/publicConfig.ts b/apps/mobile/src/features/cloud/publicConfig.ts index a91a8024d4851..d0f6c18857c0b 100644 --- a/apps/mobile/src/features/cloud/publicConfig.ts +++ b/apps/mobile/src/features/cloud/publicConfig.ts @@ -73,6 +73,21 @@ export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig } satisfies CloudPublicConfig; } +/** The build's hosted app: `null` when the build has none (`""`), undefined for the default. */ +export function resolveHostedAppUrl( + extra: { readonly hostedAppUrl?: unknown } | undefined = Constants.expoConfig?.extra, +): string | null | undefined { + return extra?.hostedAppUrl === "" ? null : (normalizeSecureUrl(extra?.hostedAppUrl) ?? undefined); +} + +/** The build's release repository as owner/repo, for release checks and help links; unset means T3's. */ +export function resolveReleaseRepository( + extra: { readonly releaseRepository?: unknown } | undefined = Constants.expoConfig?.extra, +): string | undefined { + const value = trimNonEmpty(extra?.releaseRepository); + return value && /^[\w.-]+\/[\w.-]+$/.test(value) ? value : undefined; +} + export function hasCloudPublicConfig(): boolean { const config = resolveCloudPublicConfig(); return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url); diff --git a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx index c32a7c5f5f098..20f9f790c6ec6 100644 --- a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx +++ b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx @@ -18,6 +18,7 @@ import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; import { environmentCatalog } from "../../connection/catalog"; +import { resolveReleaseRepository } from "../cloud/publicConfig"; import { cn } from "../../lib/cn"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; @@ -45,6 +46,7 @@ export function useConnectionDiagnosis( via: relayOnly ? "relay" : "direct", clientVersion: Constants.expoConfig?.version, serverVersion: presentation.serverConfig?.environment.serverVersion, + repository: resolveReleaseRepository(), }, messages, ); diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx index b0d78ef3acbce..46be7681002e7 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx @@ -43,6 +43,9 @@ vi.mock("expo-haptics", () => ({ NotificationFeedbackType: { Success: "success", Error: "error" }, })); vi.mock("../../components/ui/ListRow", () => ({ ListRow: () => null })); +vi.mock("../../components/ui/Button", () => ({ Button: () => null })); +vi.mock("./cloudflareAccessSignIn", () => ({ signInWithCloudflareAccess: vi.fn() })); +vi.mock("./useCloudflareAccessLoginOrigin", () => ({ useCloudflareAccessLoginOrigin: () => null })); vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children })); vi.mock("../../components/ui/AppText", () => ({ diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 73e035fe75ece..3df3623d93fab 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -23,8 +23,11 @@ import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { SettingsScreen } from "../settings/components/SettingsScreen"; import { AppText as Text, AppTextInput, type AppTextInputProps } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; import { FrostedCutout } from "../../components/ui/FrostedCutout"; import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing"; +import { signInWithCloudflareAccess } from "./cloudflareAccessSignIn"; +import { useCloudflareAccessLoginOrigin } from "./useCloudflareAccessLoginOrigin"; import { useRemoteConnections } from "../../state/use-remote-environment-registry"; import { SymbolView } from "../../components/ui/AppSymbol"; import { hasCloudPublicConfig } from "../cloud/publicConfig"; @@ -101,6 +104,7 @@ function PairingForm({ const headerIconColor = useUniwindTheme()["--color-icon"]; const connectDisabled = connecting || hostInput.trim().length === 0; + const cloudflareAccessOrigin = useCloudflareAccessLoginOrigin(hostInput); const clearError = () => { setSubmitError(null); @@ -169,8 +173,7 @@ function PairingForm({ } }; - const handleSubmit = async () => { - const pairingUrl = buildPairingUrl(hostInput, codeInput); + const handleSubmit = async (pairingUrl = buildPairingUrl(hostInput, codeInput)) => { setOwnAttempt(true); setSubmitError(null); setIsSubmitting(true); @@ -194,6 +197,27 @@ function PairingForm({ } }; + const handleCloudflareAccessSignIn = async () => { + // Pair with the host the sign-in started from, whatever the field holds by the time it returns. + const origin = cloudflareAccessOrigin; + if (origin === null) return; + setOwnAttempt(true); + setSubmitError(null); + setIsSubmitting(true); + let pairingCode: string | null; + try { + pairingCode = await signInWithCloudflareAccess(origin); + } catch { + pairingCode = null; + } + setIsSubmitting(false); + if (pairingCode === null) { + setSubmitError(gt("Sign-in did not finish. Try again.")); + return; + } + await handleSubmit(buildPairingUrl(origin, pairingCode)); + }; + return ( + {cloudflareAccessOrigin !== null ? ( + {children}, })); vi.mock("../../components/ProjectFavicon", () => ({ ProjectFavicon: () => null })); +vi.mock("../../connection/catalog", () => ({ retryEnvironmentCatalogLoad: vi.fn() })); vi.mock("../connection/environmentStatusText", () => ({ runtimeConnectionErrorText: () => null })); vi.mock("../../state/entities", () => ({ useProjects: () => [regular, scratch], @@ -110,7 +111,7 @@ vi.mock("../../state/use-remote-environment-registry", () => ({ }), })); vi.mock("../../state/workspace", () => ({ - useWorkspaceState: () => ({ state: { hasReadyEnvironment: true } }), + useWorkspaceState: () => ({ state: { hasReadyEnvironment: true, catalogLoadError: null } }), })); vi.mock("../sharing/IncomingShareProvider", () => ({ useIncomingShare: () => ({ getShare: () => null, releaseShareReservation: vi.fn() }), diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx index 716713e4293d2..c40997244a199 100644 --- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx @@ -38,6 +38,8 @@ import { useRemoteConnectionStatus } from "../../state/use-remote-environment-re import type { WorkspaceState } from "../../state/workspaceModel"; import type { MessageResolver } from "../../i18n/messages"; import { useWorkspaceState } from "../../state/workspace"; +import { retryEnvironmentCatalogLoad } from "../../connection/catalog"; +import { deriveHomeEmptyState } from "../home/home-empty-state"; import { useIncomingShare } from "../sharing/IncomingShareProvider"; import { useNewTaskFlow } from "./new-task-flow-provider"; @@ -201,7 +203,11 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps @@ -464,7 +470,15 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps {projectEmptyState.detail} - {Platform.OS === "android" ? ( + {showsRetryCatalogLoad ? ( + + + ); + switch (activeGroup) { + case "browser": + return browserProfiles.length > 1 && props.browserAvailable ? ( + + } + > + + + + {browserProfiles.map((profile) => ( + props.onAddBrowserInProfile(profile.id)}> + {profile.name} + + ))} + + + ) : ( + plainButton(props.onAddBrowser, props.browserAvailable) + ); + case "reviews": + return ( + + } + > + + + + + + {gt("Pull request")} + + + + {gt("Linked items")} + + + + ); + case "devices": + return plainButton(props.onAddDevice, props.deviceAvailable); + case "threads": + return props.onAddSideChat + ? plainButton(() => props.onAddSideChat?.(), sideChatCanStart) + : null; + case "changes": + case "files": + return null; + } + })(); + + const moreMenuItems = + focusedSurface && focusedSurface.kind !== "terminal" + ? surfaceMenuItems(focusedSurface, messages) + : []; + const moreMenu = + focusedSurface && moreMenuItems.length > 0 ? ( + + + } + > + + + + {moreMenuItems.map((item) => ( + runSurfaceMenuAction(item.id, focusedSurface)} + > + {item.label} + + ))} + + + ) : null; + return (
- -
- - {props.surfaces.map((surface) => { - const previewTabId = previewTabIdOf(surface, props.previewSessions); - const favicon = previewFaviconOf( - surface, - props.previewSessions, - props.desktopByTabId, - ); - return ( - - ); + {groupLabel !== null && rail !== null ? ( + + {groupLabel} + + ) : null} + {activeGroup === "changes" && props.changeTotals ? ( + + {/* The totals are the latest turn's, whatever scope the diff below shows. */} + + {gt("Last turn", { $context: "the Changes header totals cover the latest turn" })} + + + + {gt("{count, plural, one {# file} other {# files}}", { + count: props.changeTotals.count, })} - - {props.open !== false ? ( - - - } - > - - - - {addSurfaceActions.map((action) => { - const Icon = action.icon; - if (action.label === "Browser" && action.available) { - return ( - - { - const pointerType = - "pointerType" in event.nativeEvent && - typeof event.nativeEvent.pointerType === "string" - ? event.nativeEvent.pointerType - : undefined; - if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType)) - return; - setAddSurfaceMenuOpen(false); - action.onClick(); - }} - > - - {messages(action.label)} - {action.shortcut} - - - {browserProfiles.map((profile) => ( - props.onAddBrowserInProfile(profile.id)} - > - {profile.name} - - ))} - - - ); - } - return ( - - - {messages(action.label)} - - ); - })} - - - ) : null} -
-
- {tabScrollState.hasOverflow ? ( -
+ + ) : null} + {showTabStrip ? ( + - - - - - } - /> - - Scroll tabs left - - - - - - - } - /> - - Scroll tabs right - - -
+
+ + {headerSurfaces.map((surface) => { + const previewTabId = previewTabIdOf(surface, props.previewSessions); + const favicon = previewFaviconOf( + surface, + props.previewSessions, + props.desktopByTabId, + ); + return ( + + ); + })} + + {groupAddButton ? ( + {groupAddButton} + ) : null} + {rail === null ? launcher : null} +
+ + ) : ( +
+ )} + {moreMenu ? ( + {moreMenu} ) : null} {props.layoutControls} {ownsDesktopTitleBar && !props.layoutControls ? ( @@ -1670,32 +1875,61 @@ export function RightPanelTabs(props: RightPanelTabsProps) { /> ) : null}
-
- {props.activeSurfaceId === null ? ( - +
+
+ {props.activeSurfaceId === null ? ( + + ) : ( + props.children + )} +
+ {props.terminalDrawer ? ( + + ) : null} +
+ {rail ? ( + - ) : ( - props.children - )} + ) : null}
); diff --git a/apps/web/src/components/RightPanelTerminalBodies.tsx b/apps/web/src/components/RightPanelTerminalBodies.tsx new file mode 100644 index 0000000000000..6917a6a46c837 --- /dev/null +++ b/apps/web/src/components/RightPanelTerminalBodies.tsx @@ -0,0 +1,90 @@ +import { memo, useLayoutEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { useShallow } from "zustand/react/shallow"; + +import { + selectActiveTerminalSurface, + useRightPanelStore, + type TerminalPanelSurface, +} from "~/rightPanelStore"; + +import type { RightPanelTerminalProps } from "./chat/RightPanelSurfaceContent"; +import { reconcileMountedTerminalThreads } from "./RightPanelTabs.logic"; +import { RightPanelTerminalBody } from "./RightPanelTerminalBody"; +import type { TerminalBodyHost, TerminalBodyHosts } from "./terminalBodyHosts"; + +const EMPTY_KEYS: readonly string[] = []; + +/** Keeps drawer terminals mounted for recently shown threads; only the active one is visible. */ +export function RightPanelTerminalBodies(props: { + hosts: TerminalBodyHosts; + activeThreadKey: string | null; + drawerVisible: boolean; + terminal: RightPanelTerminalProps; +}) { + const { hosts, activeThreadKey } = props; + const panelOpenKeys = useRightPanelStore( + useShallow((state) => + Object.entries(state.byThreadKey).flatMap(([threadKey, thread]) => + thread.isOpen && thread.surfaces.some((surface) => surface.kind === "terminal") + ? [threadKey] + : [], + ), + ), + ); + const [mounted, setMounted] = useState(EMPTY_KEYS); + const next = reconcileMountedTerminalThreads({ + current: mounted, + panelOpen: new Set(panelOpenKeys), + active: activeThreadKey, + activeShowing: props.drawerVisible, + }); + if (next.length !== mounted.length || next.some((key, index) => key !== mounted[index])) { + setMounted(next); + } + const holderRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- gives parked hosts a hidden DOM home and drops the hosts of threads whose terminals unmounted + useLayoutEffect(() => { + hosts.setHolder(holderRef.current); + hosts.retain(new Set(activeThreadKey === null ? mounted : [...mounted, activeThreadKey])); + }, [activeThreadKey, hosts, mounted]); + const hiddenTerminal = { ...props.terminal, launchContext: null }; + + return ( + + ); +} + +const ThreadTerminalBodyPortal = memo(function ThreadTerminalBodyPortal(props: { + host: TerminalBodyHost; + visible: boolean; + terminal: RightPanelTerminalProps; +}) { + const { threadRef } = props.host; + const surface = useRightPanelStore((state): TerminalPanelSurface | null => + selectActiveTerminalSurface(state.byThreadKey, threadRef), + ); + if (!surface || !threadRef) return null; + return createPortal( + , + props.host.element, + ); +}); diff --git a/apps/web/src/components/RightPanelTerminalBody.tsx b/apps/web/src/components/RightPanelTerminalBody.tsx new file mode 100644 index 0000000000000..f1c77d4a6467d --- /dev/null +++ b/apps/web/src/components/RightPanelTerminalBody.tsx @@ -0,0 +1,103 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { AuthTerminalOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; +import { T } from "gt-react"; +import { memo } from "react"; + +import { Button } from "~/components/ui/button"; +import { + selectClaimedTerminalIds, + useRightPanelStore, + type TerminalPanelSurface, +} from "~/rightPanelStore"; +import { useEnvironmentScope } from "~/state/session"; +import { useTerminalDrawerSessions } from "~/state/terminalSessions"; + +import type { RightPanelTerminalProps } from "./chat/RightPanelSurfaceContent"; +import { PersistentThreadTerminalPanel } from "./PersistentThreadTerminals"; +import { currentTerminalClaims, terminalSurfaceMount } from "./RightPanelTabs.logic"; +import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions"; + +export interface RightPanelTerminalBodyProps { + threadRef: ScopedThreadRef; + surface: TerminalPanelSurface; + visible: boolean; + terminal: RightPanelTerminalProps; +} + +/** A drawer sub-tab's terminal, mounted only when attaching to it cannot start a new shell. */ +export const RightPanelTerminalBody = memo(function RightPanelTerminalBody( + props: RightPanelTerminalBodyProps, +) { + const { threadRef, surface } = props; + const listing = useTerminalDrawerSessions(threadRef.environmentId, threadRef.threadId); + const claimedIds = useRightPanelStore((state) => selectClaimedTerminalIds(state, threadRef)); + const observedSnapshotId = useRightPanelStore( + (state) => state.terminalServerObservationByThreadKey[scopedThreadKey(threadRef)]?.snapshotId, + ); + // Without read access the list never arrives, and the id may be live: Restart would replace + // it, so an unclaimed sub-tab stays pending rather than ended. + const serverIds = listing?.sessions.map((session) => session.target.terminalId) ?? null; + const mount = terminalSurfaceMount({ + terminalIds: surface.terminalIds, + serverIds, + claimedIds: currentTerminalClaims({ + claimedIds, + observedSnapshotId, + serverSnapshotId: listing?.snapshotId, + }), + }); + if (mount.kind === "mount") { + const { terminalIds } = mount; + return ( + + ); + } + if (mount.kind === "ended") return ; + return null; +}); + +function EndedTerminal(props: { threadRef: ScopedThreadRef; surface: TerminalPanelSurface }) { + const terminalActions = useThreadTerminalActions(props.threadRef); + const canOperate = useEnvironmentScope(props.threadRef.environmentId, AuthTerminalOperateScope); + const restart = () => { + for (const terminalId of props.surface.terminalIds) { + const launched = terminalActions.launchTerminal({ + terminalId, + place: (id) => useRightPanelStore.getState().openTerminal(props.threadRef, id), + }); + if (launched) void launched.result; + } + }; + // The server no longer has this terminal, so closing only forgets the sub-tab. + const close = () => useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id); + return ( +
+

+ This terminal has ended. +

+
+ + +
+
+ ); +} diff --git a/apps/web/src/components/RightPanelTerminalDrawer.tsx b/apps/web/src/components/RightPanelTerminalDrawer.tsx new file mode 100644 index 0000000000000..35644f586eac5 --- /dev/null +++ b/apps/web/src/components/RightPanelTerminalDrawer.tsx @@ -0,0 +1,325 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; +import { msg, T, useGT, useMessages } from "gt-react"; +import { + ChevronDown, + ChevronRight, + Maximize2, + Minimize2, + Plus, + TerminalSquare, +} from "lucide-react"; +import { memo, useLayoutEffect, useRef, type PointerEvent as ReactPointerEvent } from "react"; + +import { Button } from "~/components/ui/button"; +import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; +import { cn } from "~/lib/utils"; +import { workspaceAreaProps } from "~/lib/workspaceFocus"; +import type { RightPanelSurface, TerminalPanelSurface } from "~/rightPanelStore"; +import { useKnownTerminalSessions } from "~/state/terminalSessions"; + +import type { TerminalBodyHost } from "./terminalBodyHosts"; +import { + clampTerminalDrawerHeight, + TERMINAL_DRAWER_COLLAPSED_HEIGHT, + TERMINAL_DRAWER_MIN_HEIGHT, + terminalDrawerStatus, + type TerminalDrawerStatus, +} from "./RightPanelTabs.logic"; + +export interface RightPanelTerminalDrawerProps { + threadRef: ScopedThreadRef; + surfaces: readonly TerminalPanelSurface[]; + activeSurfaceId: string | null; + open: boolean; + height: number; + maximized: boolean; + terminalAvailable: boolean; + /** Without operate access a close cannot end the session, so the server would list it again. */ + terminalClosable: boolean; + terminalLabelsById: ReadonlyMap; + /** The thread's terminals, rendered elsewhere so they outlive this drawer. */ + bodyHost: TerminalBodyHost | null; + onToggleOpen: () => void; + onHeightCommit: (height: number) => void; + onToggleMaximized: () => void; + onActivateSurface: (surfaceId: string) => void; + onCloseSurface: (surface: RightPanelSurface) => void; + onNewTerminal: () => void; +} + +const HEIGHT_PROPERTY = "--right-panel-terminal-height"; + +const STATUS_LABELS = { + running: msg("running", { $context: "a terminal command is still running" }), + ok: msg("ok", { $context: "a terminal command exited successfully" }), + failed: msg("failed", { $context: "a terminal command exited with an error" }), +} as const satisfies Record; + +/** Subscribes to terminal metadata alone, so output never re-renders the drawer or the tool. */ +const TerminalDrawerStatusText = memo(function TerminalDrawerStatusText(props: { + threadRef: ScopedThreadRef; + terminalId: string; +}) { + const messages = useMessages(); + const sessions = useKnownTerminalSessions({ + environmentId: props.threadRef.environmentId, + threadId: props.threadRef.threadId, + }); + const summary = + sessions?.find((session) => session.target.terminalId === props.terminalId)?.state.summary ?? + null; + const status = terminalDrawerStatus(summary); + if (status === null) return null; + return ( + + {status === "running" ? ( + + ) : null} + {messages(STATUS_LABELS[status])} + + ); +}); + +function terminalLabel(labels: ReadonlyMap, terminalId: string) { + return labels.get(terminalId) ?? getTerminalLabel(terminalId); +} + +export const RightPanelTerminalDrawer = memo(function RightPanelTerminalDrawer( + props: RightPanelTerminalDrawerProps, +) { + const gt = useGT(); + const drawerRef = useRef(null); + const dragRef = useRef<{ + pointerId: number; + startY: number; + startHeight: number; + containerHeight: number; + height: number; + } | null>(null); + const bodySlotRef = useRef(null); + const { bodyHost } = props; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves the thread's terminal host element into this drawer and back out, so the terminals never remount + useLayoutEffect(() => { + const slot = bodySlotRef.current; + if (!slot || !bodyHost) return; + bodyHost.place(slot); + return () => { + if (bodyHost.element.parentElement === slot) bodyHost.park(); + }; + }, [bodyHost]); + + const activeSurface = + props.surfaces.find((surface) => surface.id === props.activeSurfaceId) ?? + props.surfaces[0] ?? + null; + const activeLabel = activeSurface + ? terminalLabel(props.terminalLabelsById, activeSurface.activeTerminalId) + : null; + + const onResizePointerDown = (event: ReactPointerEvent) => { + const drawer = drawerRef.current; + if (!drawer || event.button !== 0) return; + event.preventDefault(); + event.currentTarget.setPointerCapture(event.pointerId); + const startHeight = drawer.getBoundingClientRect().height; + dragRef.current = { + pointerId: event.pointerId, + startY: event.clientY, + startHeight, + containerHeight: drawer.parentElement?.getBoundingClientRect().height ?? startHeight, + height: startHeight, + }; + }; + const onResizePointerMove = (event: ReactPointerEvent) => { + const drag = dragRef.current; + if (!drag || drag.pointerId !== event.pointerId) return; + drag.height = clampTerminalDrawerHeight( + drag.startHeight + (drag.startY - event.clientY), + drag.containerHeight, + ); + drawerRef.current?.style.setProperty(HEIGHT_PROPERTY, `${drag.height}px`); + }; + const onResizePointerEnd = (event: ReactPointerEvent) => { + const drag = dragRef.current; + if (!drag || drag.pointerId !== event.pointerId) return; + dragRef.current = null; + drawerRef.current?.style.removeProperty(HEIGHT_PROPERTY); + if (drag.height !== drag.startHeight) props.onHeightCommit(drag.height); + }; + + const terminalArea = props.open ? workspaceAreaProps("terminal", 5, gt("Terminal")) : {}; + + return ( +
+ {props.open && !props.maximized ? ( +
+ ) : null} + {props.open ? ( +
+
+ {props.surfaces.map((surface) => { + const label = terminalLabel(props.terminalLabelsById, surface.activeTerminalId); + const active = surface.id === activeSurface?.id; + return ( +
+ {props.terminalClosable ? ( + props.onCloseSurface(surface)} + > + + + ) : ( + + )} + +
+ ); + })} + + + +
+ + {props.maximized ? : } + + + + +
+ ) : ( + + )} + {/* One position for the body, so collapsing hides the terminal without remounting it. */} +
+
+ {activeSurface ? null : props.open ? ( +
+

+ No terminal +

+ +
+ ) : null} +
+
+ ); +}); + +function DrawerIconButton(props: { + label: string; + disabled?: boolean; + onClick: () => void; + children: React.ReactNode; +}) { + return ( + + + } + > + {props.children} + + {props.label} + + ); +} diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index b99591c92b112..0967a70ba57e7 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -25,8 +25,8 @@ import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; -import { useTerminalUiStateStore } from "../terminalUiStateStore"; import { readLocalApi } from "../localApi"; +import { useRightPanelStore } from "../rightPanelStore"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; @@ -90,7 +90,7 @@ describe("sidebar header new thread", () => { stack.defer(() => __setClientSettingsForTests(previousSettings)); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, - boringSidebarEnabled: scenario.mode === "boring", + classicSidebarEnabled: scenario.mode !== "boring", }); const projects = [project("active"), project("idle")].slice(0, scenario.count); const currentProjectRef = { @@ -167,12 +167,12 @@ describe("sidebar render isolation", () => { routeThreadRef, }); const terminal = document.createElement("div"); - terminal.dataset.terminalOwner = "drawer"; + terminal.dataset.terminalOwner = "right-panel"; const terminalInput = document.createElement("textarea"); terminal.append(terminalInput); document.body.append(terminal); stack.defer(() => terminal.remove()); - stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, false)); + stack.defer(() => useRightPanelStore.getState().setTerminalDrawerOpen(routeThreadRef, false)); await using screen = await render( @@ -185,7 +185,7 @@ describe("sidebar render isolation", () => { const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control"; const beforeShortcut = rowRenders(); await userEvent.keyboard(`{${modifier}>}`); - await act(() => useTerminalUiStateStore.getState().setTerminalOpen(routeThreadRef, true)); + await act(() => useRightPanelStore.getState().openTerminal(routeThreadRef, "term-1")); await act(() => terminalInput.focus()); await userEvent.keyboard(`{/${modifier}}`); await act(() => terminalInput.blur()); diff --git a/apps/web/src/components/Sidebar.drag.browser.test.tsx b/apps/web/src/components/Sidebar.drag.browser.test.tsx index 2a5acdd3b1b70..d97d3f7129543 100644 --- a/apps/web/src/components/Sidebar.drag.browser.test.tsx +++ b/apps/web/src/components/Sidebar.drag.browser.test.tsx @@ -40,7 +40,7 @@ it("shows the titled preview inside and outside search results from a collapsed using _environment = installFakeEnvironment([first, second]); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, - boringSidebarEnabled: true, + classicSidebarEnabled: false, onboardingCompletedAt: "2026-01-01T00:00:00.000Z", }); const router = getRouter( @@ -60,6 +60,7 @@ it("shows the titled preview inside and outside search results from a collapsed folder.element().focus(); await userEvent.keyboard("{Enter}"); await expect.element(secondRow).not.toBeInTheDocument(); + await page.getByRole("button", { name: "Search threads" }).click(); await userEvent.fill(page.getByRole("combobox", { name: "Search threads" }), "search-target"); const result = page.getByRole("option", { name: /Thread search-target/ }); await expect.element(result).toBeVisible(); diff --git a/apps/web/src/components/Sidebar.logic.browser.test.tsx b/apps/web/src/components/Sidebar.logic.browser.test.tsx index a323b5abdc094..8835775b8b9cd 100644 --- a/apps/web/src/components/Sidebar.logic.browser.test.tsx +++ b/apps/web/src/components/Sidebar.logic.browser.test.tsx @@ -5,7 +5,7 @@ import { userEvent } from "vite-plus/test/browser"; import { act, fakeTimers, render } from "../../test/render"; import { registerModelPickerContent } from "../modelPickerVisibility"; -import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { useRightPanelStore } from "../rightPanelStore"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS, useSnoozeWakeClock, @@ -81,15 +81,15 @@ describe("useThreadJumpHintsVisible", () => { await userEvent.keyboard(`{/${modifier}}`); }); - it("follows terminal focus and the route thread's terminal while the modifier is held", async () => { + it("terminalOpen context follows the right panel drawer, and terminal focus, while the modifier is held", async () => { using stack = new DisposableStack(); const terminal = document.createElement("div"); - terminal.dataset.terminalOwner = "drawer"; + terminal.dataset.terminalOwner = "right-panel"; const terminalInput = document.createElement("textarea"); terminal.append(terminalInput); document.body.append(terminal); stack.defer(() => terminal.remove()); - stack.defer(() => useTerminalUiStateStore.getState().setTerminalOpen(ROUTE_THREAD_REF, false)); + stack.defer(() => useRightPanelStore.getState().setTerminalDrawerOpen(ROUTE_THREAD_REF, false)); const keybindings = compileResolvedKeybindingsConfig([ { key: "mod+1", command: "thread.jump.1", when: "terminalOpen" }, ]); @@ -104,7 +104,7 @@ describe("useThreadJumpHintsVisible", () => { await userEvent.keyboard(`{${modifier}>}`); await act(() => vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS)); await expect.element(output).toHaveTextContent("hidden"); - await act(() => useTerminalUiStateStore.getState().setTerminalOpen(ROUTE_THREAD_REF, true)); + await act(() => useRightPanelStore.getState().openTerminal(ROUTE_THREAD_REF, "term-1")); await expect.element(output).toHaveTextContent("shown"); await act(() => terminalInput.focus()); await expect.element(output).toHaveTextContent("hidden"); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 76f8c8c30c2d5..2e77a722f5757 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -16,6 +16,9 @@ import { resolveSidebarSweepKeys, resolveSidebarRowStatus, resolveSidebarThreadStatus, + resolveSidebarEnvironmentScope, + summarizeSidebarEnvironmentWork, + sidebarStatusDotClassName, resolveThreadStatusPill, resolveWindowTitleThreadStatus, resolveWorkingStartedAt, @@ -174,6 +177,58 @@ describe("orderItemsByPreferredIds", () => { }); }); +describe("sidebar environment filter", () => { + const laptop = EnvironmentId.make("env-laptop"); + const server = EnvironmentId.make("env-server"); + + it("reads a removed environment as every environment", () => { + const environments = [{ environmentId: laptop }]; + expect(resolveSidebarEnvironmentScope(laptop, environments)).toBe(laptop); + expect(resolveSidebarEnvironmentScope(server, environments)).toBeNull(); + expect(resolveSidebarEnvironmentScope(null, environments)).toBeNull(); + }); + + it("counts approvals and running work per environment, skipping archived and idle threads", () => { + const base = { + hasPendingApprovals: false, + hasPendingUserInput: false, + runtime: null, + archivedAt: null, + }; + const running = { + status: "running" as const, + activeRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "Codex", + lastError: null, + updatedAt: "2026-03-09T10:00:00.000Z", + }; + const work = summarizeSidebarEnvironmentWork([ + { ...base, environmentId: server, hasPendingApprovals: true }, + { ...base, environmentId: server, runtime: running }, + { ...base, environmentId: server, hasPendingUserInput: true, archivedAt: "2026-03-09" }, + { ...base, environmentId: laptop }, + ]); + expect(work.get(server)).toEqual({ needsYou: 1, working: 1 }); + expect(work.has(laptop)).toBe(false); + }); +}); + +describe("sidebarStatusDotClassName", () => { + it("maps each status to its semantic token", () => { + expect(sidebarStatusDotClassName("working", false)).toBe("bg-info"); + expect(sidebarStatusDotClassName("preparing", false)).toBe("bg-info"); + expect(sidebarStatusDotClassName("approval", false)).toBe("bg-warning"); + expect(sidebarStatusDotClassName("input", false)).toBe("bg-warning"); + expect(sidebarStatusDotClassName("limited", false)).toBe("bg-warning"); + expect(sidebarStatusDotClassName("failed", false)).toBe("bg-error"); + expect(sidebarStatusDotClassName("ready", true)).toBe("bg-success"); + expect(sidebarStatusDotClassName("ready", false)).toBe("bg-muted-foreground/40"); + expect(sidebarStatusDotClassName("waiting", true)).toBe("bg-muted-foreground/40"); + expect(sidebarStatusDotClassName("reconnecting", true)).toBe("bg-muted-foreground/40"); + }); +}); + describe("resolveSidebarThreadStatus", () => { const runtime = { status: "running" as const, @@ -435,6 +490,49 @@ describe("resolveThreadStatusPill", () => { }, }; + it.each([ + ["connecting", "connecting", "Connecting"], + ["reconnecting", "reconnecting", "Reconnecting"], + ["offline", "offline", "Offline"], + ["error", "offline", "Offline"], + ["unsupported", "offline", "Offline"], + ["available", "offline", "Offline"], + ["connected", "working", "Working"], + [undefined, "working", "Working"], + ] as const)( + "presents cached running work with connection phase %s", + (connectionPhase, status, label) => { + const thread = { ...baseThread, connectionPhase }; + expect(resolveSidebarThreadStatus(thread)).toBe(status); + expect(resolveThreadStatusPill({ thread })).toMatchObject({ + label, + pulse: status === "working", + }); + expect(thread.runtime.status).toBe("running"); + }, + ); + + it("keeps cached requests and terminal outcomes when the connection is lost", () => { + const thread = { ...baseThread, connectionPhase: "reconnecting" as const }; + expect( + resolveThreadStatusPill({ thread: { ...thread, hasPendingApprovals: true } })?.label, + ).toBe("Pending Approval"); + expect( + resolveThreadStatusPill({ thread: { ...thread, hasPendingUserInput: true } })?.label, + ).toBe("Awaiting Input"); + for (const status of ["failed", "completed", "cancelled", "interrupted", "idle"] as const) { + const online = { + ...baseThread, + runtime: { ...baseThread.runtime, status, activeRunId: null }, + }; + const disconnected = { ...online, connectionPhase: "reconnecting" as const }; + expect(resolveSidebarThreadStatus(disconnected)).toBe(resolveSidebarThreadStatus(online)); + expect(resolveThreadStatusPill({ thread: disconnected })).toEqual( + resolveThreadStatusPill({ thread: online }), + ); + } + }); + it("shows an active thread wait without a pulse and resumes Working when it ends", () => { const blocked = { ...baseThread, blockedOnThreadWait: true }; expect(resolveSidebarThreadStatus(blocked)).toBe("waiting"); @@ -1684,7 +1782,15 @@ describe("resolveSidebarFolderDot", () => { runtime: { ...runtime, status: "failed" as const, lastErrorClass: "usage_limit" as const }, }; + const failed = { ...idle, runtime: { ...runtime, status: "failed" as const } }; + const stopped = { ...idle, runtime: { ...runtime, status: "idle" as const } }; + expect(resolveSidebarFolderDot([idle])).toBeNull(); + expect(resolveSidebarFolderDot([idle, stopped])).toBeNull(); + expect(resolveSidebarFolderDot([failed])).toBe("failed"); + expect(resolveSidebarFolderDot([working, failed])).toBe("failed"); + expect(resolveSidebarFolderDot([unread, failed])).toBe("failed"); + expect(resolveSidebarFolderDot([failed, limited])).toBe("attention"); // A waiting thread stays quiet even with an unread completion, like its row. expect( resolveSidebarFolderDot([{ ...unread, runtime: { ...runtime, status: "idle" as const } }]), diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index f97a6e33fb864..00c16d6baa24e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1,7 +1,15 @@ import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; -import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models"; +import { + resolveThreadConnectionStatus, + resolveThreadWorkingStartedAt, +} from "@t3tools/client-runtime/state/models"; import { isShownUnderParent } from "@t3tools/client-runtime/state/threads"; +import { + resolveThreadNeedsYouReason, + selectNeedsYouThreads, + type NeedsYouReason, +} from "@t3tools/client-runtime/state/thread-needs-you"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests"; import * as React from "react"; @@ -53,8 +61,11 @@ import { isTerminalFocused, subscribeToTerminalFocusChanges } from "../lib/termi import { isPreviewFocused } from "../lib/previewFocus"; import { isModelPickerOpen, subscribeToModelPickerVisibility } from "../modelPickerVisibility"; import { shortcutModifierStore } from "../shortcutModifierState"; -import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; -import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; +import { + selectActiveRightPanel, + selectTerminalDrawerVisible, + useRightPanelStore, +} from "../rightPanelStore"; export function shouldNavigateAfterThreadPark(input: { readonly threadKey: string; @@ -652,6 +663,7 @@ type ThreadStatusInput = Pick< | "interactionMode" | "latestRun" | "runtime" + | "connectionPhase" > & { lastVisitedAt?: string | null | undefined; pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined; @@ -664,10 +676,7 @@ export function threadShortcutContext(routeThreadRef: ScopedThreadRef | null) { terminalFocus: isTerminalFocused(), terminalOpen: routeThreadRef !== null && - selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - routeThreadRef, - ).terminalOpen, + selectTerminalDrawerVisible(useRightPanelStore.getState(), routeThreadRef), previewFocus: isPreviewFocused(), previewOpen: selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) === @@ -726,14 +735,12 @@ function subscribeToThreadJumpHintInputs(listener: () => void): () => void { // The snapshot reads the modifiers; the hold stays silent when it is true across a change. const unsubscribeModifiers = shortcutModifierStore.subscribe(listener); const unsubscribeFocus = subscribeToTerminalFocusChanges(listener); - const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener); const unsubscribeRightPanels = useRightPanelStore.subscribe(listener); const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener); return () => { unsubscribeHold(); unsubscribeModifiers(); unsubscribeFocus(); - unsubscribeTerminals(); unsubscribeRightPanels(); unsubscribeModelPicker(); }; @@ -881,6 +888,9 @@ export function resolveAdjacentThreadId(input: { } export type SidebarThreadStatus = + | "connecting" + | "reconnecting" + | "offline" | "approval" | "input" | "request" @@ -923,19 +933,16 @@ type SidebarThreadStatusInput = Pick< | "pendingGuestMessageCount" | "runtime" | "blockedOnThreadWait" ->; + | "connectionPhase" +> & { + readonly pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"]; +}; export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus { - if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") { - return "approval"; - } - if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") { - return "input"; - } - // A guest is waiting on the owner; the agent's own requests come first. - if ((thread.pendingGuestMessageCount ?? 0) > 0) { - return "request"; - } + const needsYou = resolveThreadNeedsYouReason(thread); + if (needsYou !== null) return needsYou; + const connectionStatus = resolveThreadConnectionStatus(thread); + if (connectionStatus !== null) return connectionStatus; if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) { return "waiting"; } @@ -957,6 +964,74 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si return "ready"; } +/** The stored environment filter, or every environment once that environment is gone. */ +export function resolveSidebarEnvironmentScope( + stored: string | null, + environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>, +): EnvironmentId | null { + return ( + environments.find((environment) => environment.environmentId === stored)?.environmentId ?? null + ); +} + +export interface SidebarEnvironmentWork { + readonly needsYou: number; + readonly working: number; +} + +export type SidebarNeedsYouReason = NeedsYouReason; + +function isSidebarNeedsYouStatus(status: SidebarThreadStatus): status is SidebarNeedsYouReason { + return status === "approval" || status === "input" || status === "request"; +} + +export { selectNeedsYouThreads as selectSidebarNeedsYouThreads }; + +/** The status dot's fill: running is info, waiting on the user warning, failed error, an unseen finish success. */ +export function sidebarStatusDotClassName(status: SidebarThreadStatus, isUnread: boolean): string { + switch (status) { + case "preparing": + case "working": + return "bg-info"; + case "approval": + case "input": + case "request": + case "limited": + return "bg-warning"; + case "failed": + return "bg-error"; + case "ready": + return isUnread ? "bg-success" : "bg-muted-foreground/40"; + case "waiting": + case "connecting": + case "reconnecting": + case "offline": + return "bg-muted-foreground/40"; + } +} + +/** Per environment, the threads waiting on the user and the ones running, so a filter that hides them can say so. */ +export function summarizeSidebarEnvironmentWork( + threads: ReadonlyArray< + SidebarThreadStatusInput & Pick + >, +): ReadonlyMap { + const work = new Map(); + for (const thread of threads) { + if (thread.archivedAt !== null) continue; + const status = resolveSidebarThreadStatus(thread); + const needsYou = isSidebarNeedsYouStatus(status); + const working = status === "working" || status === "preparing"; + if (!needsYou && !working) continue; + const current = work.get(thread.environmentId) ?? { needsYou: 0, working: 0 }; + work.set(thread.environmentId, { + needsYou: current.needsYou + (needsYou ? 1 : 0), + working: current.working + (working ? 1 : 0), + }); + } + return work; +} + /** Sidebar row status: a failure the user has already opened settles to ready, like Done. */ export function resolveSidebarRowStatus( thread: ThreadStatusInput & SidebarThreadStatusInput, @@ -1219,6 +1294,21 @@ export function resolveThreadStatusPill(input: { }; } + const connectionStatus = resolveThreadConnectionStatus(thread); + if (connectionStatus !== null) { + return { + label: + connectionStatus === "connecting" + ? msg("Connecting") + : connectionStatus === "reconnecting" + ? msg("Reconnecting") + : msg("Offline"), + colorClass: "text-sidebar-muted-foreground", + dotClass: "bg-sidebar-muted-foreground", + pulse: false, + }; + } + if ( (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) || thread.runtime?.status === "waiting" diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 86a2d04c53eef..f1e752d255cfe 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -72,6 +72,7 @@ import { CheckIcon, ChevronDownIcon, FolderIcon, + FolderPlusIcon, ListFilterIcon, PlusIcon, SettingsIcon, @@ -141,6 +142,7 @@ import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; import { + useEnvironments, useEnvironmentIdentities, useConnectedEnvironmentIds, useEnvironmentMachines, @@ -200,6 +202,9 @@ import { resolveSidebarDropTarget, resolveSidebarDropVerb, resolveSidebarThreadSection, + resolveSidebarEnvironmentScope, + summarizeSidebarEnvironmentWork, + selectSidebarNeedsYouThreads, resolveSidebarReorderableThreadKeys, searchSidebarThreads, shouldCreateNewThreadInCurrentProject, @@ -256,7 +261,13 @@ import { } from "./ui/combobox"; import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; -import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; +import { + SidebarHeaderIconButton, + SidebarListHeading, + SidebarThreadHeader, +} from "./sidebar/SidebarThreadHeader"; +import { SidebarNeedsYouSection } from "./sidebar/SidebarNeedsYouSection"; +import { SidebarEnvironmentScopeMenu } from "./sidebar/SidebarEnvironmentScopeMenu"; import { TooltipProvider } from "./ui/tooltip"; import { composerDraftHasUserContent, @@ -810,13 +821,13 @@ function isOptimisticDropReleased(input: { } // Build maps in a hook so the compiler can prove they are frozen and cache them. -function useSidebarLookups() { +function useSidebarLookups(environmentScope: EnvironmentId | null) { const gt = useGT(); const projects = useProjects(); const environments = useEnvironmentIdentities(); const serverConfigs = useServerConfigs(); const providerEntriesByEnvironment = useAtomValue(sidebarProviderEntriesAtom); - const projectGroups = useSidebarProjectGroups(); + const projectGroups = useSidebarProjectGroups(environmentScope); const environmentLabelById = new Map( environments.map((environment) => [environment.environmentId, environment.label] as const), ); @@ -909,6 +920,19 @@ function readRouteThreadKey(router: AnyRouter): string | null { export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) { const gt = useGT(); const messages = useMessages(); + const { environments: availableEnvironments } = useEnvironments(); + const environmentIdentities = useEnvironmentIdentities().filter(({ environmentId }) => + availableEnvironments.some( + (environment) => environment.environmentId === environmentId && environment.entry.enabled, + ), + ); + const storedEnvironmentScope = useUiStateStore((store) => store.sidebarEnvironmentScope); + const setPersistedEnvironmentScope = useUiStateStore((store) => store.setSidebarEnvironmentScope); + // A removed environment reads as all; the stored id stays, like a missing project scope. + const environmentScope = resolveSidebarEnvironmentScope( + storedEnvironmentScope, + environmentIdentities, + ); const { projects, serverConfigs, @@ -919,7 +943,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectDisplayNameByKey, projectGroupByScopeKey, projectScopeItems: lookupProjectScopeItems, - } = useSidebarLookups(); + } = useSidebarLookups(environmentScope); const delegatedUnderParent = useDelegatedUnderParent(); const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); @@ -988,7 +1012,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); }, }); - const boringSidebarEnabled = useClientSettings((settings) => settings.boringSidebarEnabled); + const classicSidebarEnabled = useClientSettings((settings) => settings.classicSidebarEnabled); const folderRowsMultiline = useClientSettings((settings) => settings.boringSidebarMultilineRows); const newThreadContext = useHandleNewThread(); // Row callbacks capture only the handler; the rest of the context changes with the route. @@ -1082,6 +1106,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setPersistedProjectScopeKeys(keys); scrollSidebarToTop(sidebarContentRef.current); }; + const setEnvironmentScope = (environmentId: EnvironmentId | null) => { + clearSelection(); + setPersistedEnvironmentScope(environmentId); + scrollSidebarToTop(sidebarContentRef.current); + }; // A scope whose project is gone reads as all projects once every snapshot has // loaded. The stored keys are left alone, so the scope returns with its project. // An archived project's scope reads as all projects, matching the menu. @@ -1098,14 +1127,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const chosenProjectGroups = scopeGroups.filter((project) => chosenProjectScopeKeys.includes(project.projectKey), ); + // Groups already hold only the filtered environment's members, so an environment filter + // without a project scope is every project left in them. const chosenScopeProjectKeys = - chosenProjectGroups.length === 0 + chosenProjectGroups.length === 0 && environmentScope === null ? null : new Set( - chosenProjectGroups.flatMap((project) => - project.memberProjectRefs.map( - (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, - ), + (chosenProjectGroups.length === 0 ? projectGroups : chosenProjectGroups).flatMap( + (project) => + project.memberProjectRefs.map( + (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, + ), ), ); const threads = useQuietThreadShells(); @@ -1157,7 +1189,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (!revealWidensScope) return; clearSelection(); setPersistedProjectScopeKeys([]); - }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); + setPersistedEnvironmentScope(null); + }, [ + clearSelection, + revealWidensScope, + setPersistedProjectScopeKeys, + setPersistedEnvironmentScope, + ]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); const scratchMachineLabelFor = ( @@ -1194,7 +1232,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs); const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys; const threadSearch = useThreadSearch( - connectedEnvironmentIds, + environmentScope === null + ? connectedEnvironmentIds + : connectedEnvironmentIds.filter((environmentId) => environmentId === environmentScope), threadSearchQuery, scopedProjectGroups.length === 0 ? {} @@ -1352,7 +1392,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threads: listedThreads, delegatedUnderParent, routeRowThreadKey, - folderGroups: boringSidebarEnabled + folderGroups: !classicSidebarEnabled ? scopedProjectGroups.length === 0 ? // An archived project keeps a folder for its active threads, below the rest. [...scopeGroups, ...projectGroups.filter((project) => project.archived)] @@ -2993,6 +3033,209 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ? shortcutLabelForCommand(keybindings, "chat.newLocal") : undefined); const newThreadInProjectShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal"); + const needsYouThreads = selectSidebarNeedsYouThreads(threads, delegatedUnderParent); + const projectScopeControls = + projects.length > 0 ? ( + <> + item.label} + isItemEqualToValue={(a, b) => a.value === b.value} + open={projectScopeMenuState.open} + onOpenChange={(open, eventDetails) => { + if (eventDetails.isCanceled) return; + if (open) suppressNextScopeChangeRef.current = false; + dispatchProjectScopeMenu({ type: "open-changed", open }); + }} + onItemHighlighted={(item) => { + highlightedProjectScopeKeyRef.current = item?.value ?? null; + }} + value={selectedProjectScopeItem} + onValueChange={(item, eventDetails) => { + if (suppressNextScopeChangeRef.current) { + suppressNextScopeChangeRef.current = false; + return; + } + if (!item) return; + if (item.value === "all") { + setProjectScopeKeys([]); + } else if (eventDetails.event instanceof MouseEvent && eventDetails.event.shiftKey) { + // Canceling skips Base UI's commit, which would freeze the search query, and its close. + eventDetails.cancel(); + toggleProjectScopeKey(item.value); + } else { + setProjectScopeKeys([item.value]); + } + }} + > + 0 + ? gt("Filter threads by project: {projects}", { + projects: scopedProjectGroups + .map((project) => project.displayName) + .join(", "), + }) + : gt("Filter threads by project") + } + /> + } + > + {scopedProjectGroups.length > 1 ? ( + + {scopedProjectGroups.slice(0, 2).map((project, index) => ( + + + + ))} + + ) : scopedProjectGroups[0] ? ( + + + + ) : ( + + )} + + {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} + closeType === "keyboard"} + > + { + if ( + event.defaultPrevented || + event.nativeEvent.isComposing || + event.keyCode === 229 + ) { + return; + } + const scopeKey = highlightedProjectScopeKeyRef.current; + const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null; + // The thread pin shortcut pins the highlighted project here. + if (project && canPinProject(project) && isProjectPinShortcut(event, keybindings)) { + event.preventDefault(); + event.stopPropagation(); + toggleProjectGroupPin(project); + return; + } + if (event.ctrlKey || event.altKey || event.metaKey) return; + if (event.shiftKey && event.key === "Enter") { + if (!project) return; + event.preventDefault(); + toggleProjectScopeKey(project.projectKey); + return; + } + if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) { + return; + } + if (project) handleProjectSettings(event, project); + }} + onChange={(event) => + dispatchProjectScopeMenu({ + type: "query-changed", + query: event.target.value, + }) + } + /> + + No matching projects. + + + {(item: (typeof projectScopeItems)[number]) => { + const project = projectGroupByScopeKey.get(item.value) ?? null; + const isSelected = project + ? projectScopeKeys.includes(item.value) + : projectScopeKeys.length === 0; + return ( + { + if (project) handleProjectSettings(event, project); + }} + > + + {project ? ( + + ) : ( + + )} + + {item.label} + {project && showProjectEnvironments ? ( + + ) : null} + {project ? ( + toggleProjectGroupPin(project)} + /> + ) : null + } + settings={ + + } + /> + ) : ( + // Keeps "All projects" as tall as the project rows. + + )} + + ); + }} + + + + + + + + ) : null; return ( @@ -3002,217 +3245,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve fixedHeader={ 0} - projectScope={ - item.label} - isItemEqualToValue={(a, b) => a.value === b.value} - open={projectScopeMenuState.open} - onOpenChange={(open, eventDetails) => { - if (eventDetails.isCanceled) return; - if (open) suppressNextScopeChangeRef.current = false; - dispatchProjectScopeMenu({ type: "open-changed", open }); - }} - onItemHighlighted={(item) => { - highlightedProjectScopeKeyRef.current = item?.value ?? null; - }} - value={selectedProjectScopeItem} - onValueChange={(item, eventDetails) => { - if (suppressNextScopeChangeRef.current) { - suppressNextScopeChangeRef.current = false; - return; - } - if (!item) return; - if (item.value === "all") { - setProjectScopeKeys([]); - } else if ( - eventDetails.event instanceof MouseEvent && - eventDetails.event.shiftKey - ) { - // Canceling skips Base UI's commit, which would freeze the search query, and its close. - eventDetails.cancel(); - toggleProjectScopeKey(item.value); - } else { - setProjectScopeKeys([item.value]); - } - }} - > - 0 - ? gt("Filter threads by project: {projects}", { - projects: scopedProjectGroups - .map((project) => project.displayName) - .join(", "), - }) - : gt("Filter threads by project") - } - /> - } - > - {scopedProjectGroups.length > 1 ? ( - - {scopedProjectGroups.slice(0, 2).map((project, index) => ( - - - - ))} - - ) : scopedProjectGroups[0] ? ( - - - - ) : ( - - )} - - {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} - closeType === "keyboard"} - > - { - if ( - event.defaultPrevented || - event.nativeEvent.isComposing || - event.keyCode === 229 - ) { - return; - } - const scopeKey = highlightedProjectScopeKeyRef.current; - const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null; - // The thread pin shortcut pins the highlighted project here. - if ( - project && - canPinProject(project) && - isProjectPinShortcut(event, keybindings) - ) { - event.preventDefault(); - event.stopPropagation(); - toggleProjectGroupPin(project); - return; - } - if (event.ctrlKey || event.altKey || event.metaKey) return; - if (event.shiftKey && event.key === "Enter") { - if (!project) return; - event.preventDefault(); - toggleProjectScopeKey(project.projectKey); - return; - } - if ( - event.key !== "ContextMenu" && - !(event.shiftKey && event.key === "F10") - ) { - return; - } - if (project) handleProjectSettings(event, project); - }} - onChange={(event) => - dispatchProjectScopeMenu({ - type: "query-changed", - query: event.target.value, - }) - } - /> - - No matching projects. - - - {(item: (typeof projectScopeItems)[number]) => { - const project = projectGroupByScopeKey.get(item.value) ?? null; - const isSelected = project - ? projectScopeKeys.includes(item.value) - : projectScopeKeys.length === 0; - return ( - { - if (project) handleProjectSettings(event, project); - }} - > - - {project ? ( - - ) : ( - - )} - - {item.label} - {project && showProjectEnvironments ? ( - - ) : null} - {project ? ( - toggleProjectGroupPin(project)} - /> - ) : null - } - settings={ - - } - /> - ) : ( - // Keeps "All projects" as tall as the project rows. - - )} - - ); - }} - - - - } - onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} @@ -3424,7 +3456,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ? folderRowsMultiline ? "folder-multiline" : "folder" - : isCard + : isCard && projectFolders === null ? "card" : "slim"; return ( @@ -3532,6 +3564,23 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; const from = isContextDrag ? null : (dragState?.activeSection ?? null); const items: ReactNode[] = [ + , + + {projectScopeControls} + , - + + } + /> ); } diff --git a/apps/web/src/components/T3AppIcon.tsx b/apps/web/src/components/T3AppIcon.tsx index 7e3ebef5692b1..20c98d9682495 100644 --- a/apps/web/src/components/T3AppIcon.tsx +++ b/apps/web/src/components/T3AppIcon.tsx @@ -1,5 +1,9 @@ // The production icon, as GitHub shows the T3 Code app, whatever this build's channel. -import appIconUrl from "../../../../assets/prod/t3-black-web-apple-touch-180.png"; +import upstreamAppIconUrl from "../../../../assets/prod/t3-black-web-apple-touch-180.png"; +import standaloneAppIconUrl from "../../../../assets/easydev/easydev-web-apple-touch-180.png"; +import { IS_STANDALONE_BUILD } from "~/projectLinks"; + +const appIconUrl = IS_STANDALONE_BUILD ? standaloneAppIconUrl : upstreamAppIconUrl; export function T3AppIcon(props: { readonly className?: string }) { return ; diff --git a/apps/web/src/components/T3Wordmark.tsx b/apps/web/src/components/T3Wordmark.tsx index d0882a5dd61e3..351eb915e7911 100644 --- a/apps/web/src/components/T3Wordmark.tsx +++ b/apps/web/src/components/T3Wordmark.tsx @@ -1,6 +1,45 @@ import type { SVGProps } from "react"; +import { IS_STANDALONE_BUILD } from "~/projectLinks"; + +// "EasyDev" in Space Grotesk Bold, outlined; the viewBox spans cap height so the y descends below it. +const EASYDEV_WORDMARK_PATH = + "M9.43 100L9.43 0L73.71 0L73.71 17.14L28.29 17.14L28.29 41L69.71 41L69.71 58.14L28.29 58.14L28.29 82.86L74.57 82.86L74.57 100ZM111.14 102Q103.57 102 97.57 99.36Q91.57 96.71 88.07 91.64Q84.57 86.57 84.57 79.29Q84.57 72 88.07 67.07Q91.57 62.14 97.79 59.64Q104 57.14 112 57.14L131.43 57.14L131.43 53.14Q131.43 48.14 128.29 44.93Q125.14 41.71 118.29 41.71Q111.57 41.71 108.29 44.79Q105 47.86 104 52.71L87.43 47.14Q89.14 41.71 92.93 37.21Q96.71 32.71 103.07 29.93Q109.43 27.14 118.57 27.14Q132.57 27.14 140.71 34.14Q148.86 41.14 148.86 54.43L148.86 80.86Q148.86 85.14 152.86 85.14L158.57 85.14L158.57 100L146.57 100Q141.29 100 137.86 97.43Q134.43 94.86 134.43 90.57L134.43 90.43L131.71 90.43Q131.14 92.14 129.14 94.93Q127.14 97.71 122.86 99.86Q118.57 102 111.14 102ZM114.29 87.43Q121.86 87.43 126.64 83.21Q131.43 79 131.43 72L131.43 70.57L113.29 70.57Q108.29 70.57 105.43 72.71Q102.57 74.86 102.57 78.71Q102.57 82.57 105.57 85Q108.57 87.43 114.29 87.43ZM201.14 102Q187.29 102 178.43 96Q169.57 90 167.71 78.86L184.29 74.57Q185.29 79.57 187.64 82.43Q190 85.29 193.5 86.5Q197 87.71 201.14 87.71Q207.43 87.71 210.43 85.5Q213.43 83.29 213.43 80Q213.43 76.71 210.57 74.93Q207.71 73.14 201.43 72L197.43 71.29Q190 69.86 183.86 67.36Q177.71 64.86 174 60.43Q170.29 56 170.29 49Q170.29 38.43 178 32.79Q185.71 27.14 198.29 27.14Q210.14 27.14 218 32.43Q225.86 37.71 228.29 46.29L211.57 51.43Q210.43 46 206.93 43.71Q203.43 41.43 198.29 41.43Q193.14 41.43 190.43 43.21Q187.71 45 187.71 48.14Q187.71 51.57 190.57 53.21Q193.43 54.86 198.29 55.71L202.29 56.43Q210.29 57.86 216.79 60.21Q223.29 62.57 227.07 66.93Q230.86 71.29 230.86 78.71Q230.86 89.86 222.79 95.93Q214.71 102 201.14 102ZM254.29 128.57L254.29 112.86L292.86 112.86Q296.86 112.86 296.86 108.57L296.86 90.71L294.29 90.71Q293.14 93.14 290.71 95.57Q288.29 98 284.14 99.57Q280 101.14 273.57 101.14Q265.29 101.14 259.07 97.36Q252.86 93.57 249.43 86.86Q246 80.14 246 71.43L246 29.14L264 29.14L264 70Q264 78 267.93 82Q271.86 86 279.14 86Q287.43 86 292 80.5Q296.57 75 296.57 65.14L296.57 29.14L314.57 29.14L314.57 112.57Q314.57 119.86 310.29 124.21Q306 128.57 298.86 128.57ZM331.14 100L331.14 83.43L344.29 83.43L344.29 16.57L331.14 16.57L331.14 0L372.29 0Q392.43 0 402.93 10.21Q413.43 20.43 413.43 40.57L413.43 59.43Q413.43 79.57 402.93 89.79Q392.43 100 372.29 100ZM363.14 82.86L372.57 82.86Q384 82.86 389.29 76.86Q394.57 70.86 394.57 60L394.57 40Q394.57 29 389.29 23.07Q384 17.14 372.57 17.14L363.14 17.14ZM462 102Q451.43 102 443.36 97.5Q435.29 93 430.79 84.79Q426.29 76.57 426.29 65.43L426.29 63.71Q426.29 52.57 430.71 44.36Q435.14 36.14 443.14 31.64Q451.14 27.14 461.71 27.14Q472.14 27.14 479.86 31.79Q487.57 36.43 491.86 44.64Q496.14 52.86 496.14 63.71L496.14 69.86L444.57 69.86Q444.86 77.14 450 81.71Q455.14 86.29 462.57 86.29Q470.14 86.29 473.71 83Q477.29 79.71 479.14 75.71L493.86 83.43Q491.86 87.14 488.07 91.5Q484.29 95.86 478 98.93Q471.71 102 462 102ZM444.71 56.43L477.86 56.43Q477.29 50.29 472.93 46.57Q468.57 42.86 461.57 42.86Q454.29 42.86 450 46.57Q445.71 50.29 444.71 56.43ZM527 100L504.43 29.14L523.57 29.14L540 86.86L542.57 86.86L559 29.14L578.14 29.14L555.57 100Z"; +const EASYDEV_MARK_UPPER_PATH = "M119.5 232L119.5 178L256 99L391.5 178L391.5 334L352 357Z"; +const EASYDEV_MARK_LOWER_PATH = "M119.5 282L119.5 334L256 413L302.4 385.9Z"; + +function EasyDevWordmark(props: SVGProps) { + return ( + + + + ); +} + +function EasyDevMark(props: SVGProps) { + return ( + + + + + + + ); +} + +/** The brand at icon size: the T3 wordmark upstream, the EasyDev mark in standalone builds. */ +export function BrandGlyph(props: SVGProps) { + return IS_STANDALONE_BUILD ? : ; +} + export function T3Wordmark(props: SVGProps) { + if (IS_STANDALONE_BUILD) return ; return ( {}} onActiveTerminalChange={() => {}} onCloseTerminal={props.onCloseTerminal} - onHeightChange={() => {}} onAddTerminalContext={() => {}} keybindings={props.keybindings ?? []} /> @@ -266,7 +263,6 @@ function setup(originalStatus: "starting" | "exited" = "exited") { fixture.runWrite = () => Promise.resolve({ _tag: "Success" }); fixture.metadata.clear(); useRightPanelStore.setState(useRightPanelStore.getInitialState()); - useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState()); return { original, other }; } diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 54ae776e18559..7b4612c6cdfa1 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1,5 +1,4 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; -import { workspaceAreaProps } from "../lib/workspaceFocus"; import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { msg, T, useGT, useMessages } from "gt-react"; import { m } from "../i18n/messages"; @@ -38,7 +37,6 @@ import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; import { - type PointerEvent as ReactPointerEvent, type ReactNode, useEffect, useContext, @@ -72,11 +70,7 @@ import { terminalDeleteShortcutData, terminalNavigationShortcutData, } from "../keybindings"; -import { - DEFAULT_THREAD_TERMINAL_HEIGHT, - MAX_TERMINALS_PER_GROUP, - type ThreadTerminalGroup, -} from "../types"; +import { MAX_TERMINALS_PER_GROUP, type ThreadTerminalGroup } from "../types"; import { readLocalApi } from "~/localApi"; import { confirmTerminalClose } from "~/lib/terminalCloseConfirm"; import { useClientSettings } from "../hooks/useSettings"; @@ -94,7 +88,6 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview"; import { terminalInputWriter } from "./terminal/terminalInputWriter"; import { useAtomCommand } from "../state/use-atom-command"; import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; -import { observeResize } from "../lib/observeResize"; import { threadShortcutContext } from "./Sidebar.logic"; import { consumePendingTerminalFocus, @@ -108,51 +101,6 @@ import { TYPOGRAPHY_ADVANCED_STORAGE_KEY, } from "../appearanceFonts"; -const MIN_DRAWER_HEIGHT = 180; -const MAX_DRAWER_HEIGHT_RATIO = 0.75; - -interface DrawerLayout { - viewportHeight: number; - chatColumnHeight?: number; - headerHeight?: number; - composerHeight?: number; -} - -function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number { - const windowCap = Math.max( - MIN_DRAWER_HEIGHT, - Math.floor(input.viewportHeight * MAX_DRAWER_HEIGHT_RATIO), - ); - if (input.chatColumnHeight === undefined) return windowCap; - // The composer overlays the timeline, so flex layout cannot reserve its - // height; without this cap a tall drawer pushes it into the header. - return Math.min( - windowCap, - Math.max(0, input.chatColumnHeight - (input.headerHeight ?? 0) - (input.composerHeight ?? 0)), - ); -} - -const DRAG_HEIGHT_PROPERTY = "--terminal-drawer-drag-height"; - -function clampDrawerHeight(height: number, maxHeight: number): number { - const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT; - return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight); -} - -function chatColumnOf(drawer: HTMLElement | null): HTMLElement | null { - return drawer?.closest("[data-chat-column]") ?? null; -} - -function readDrawerLayout(column: HTMLElement | null): Omit { - const viewportHeight = typeof window === "undefined" ? 0 : window.innerHeight; - if (!column) return { viewportHeight }; - return { - viewportHeight, - chatColumnHeight: column.clientHeight, - headerHeight: column.querySelector("[data-chat-header]")?.offsetHeight ?? 0, - }; -} - function writeSystemMessage( terminal: Pick, message: string, @@ -1223,16 +1171,12 @@ function TerminalSessionViewport({ } interface ThreadTerminalDrawerProps { - mode?: "drawer" | "panel"; threadRef: ScopedThreadRef; threadId: ThreadId; cwd: string; worktreePath?: string | null; runtimeEnv?: Record; visible?: boolean; - height: number; - /** Space the chat column keeps for the composer overlay; only read in drawer mode. */ - composerHeight?: number; terminalIds: string[]; activeTerminalId: string; terminalGroups: ThreadTerminalGroup[]; @@ -1246,7 +1190,6 @@ interface ThreadTerminalDrawerProps { closeShortcutLabel?: string | undefined; onActiveTerminalChange: (terminalId: string) => void; onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; - onHeightChange: (height: number) => void; onAddTerminalContext: (selection: TerminalContextSelection) => void; keybindings: ResolvedKeybindingsConfig; terminalLabelsById?: ReadonlyMap; @@ -1486,15 +1429,12 @@ function TerminalSidebarGroup({ } export default function ThreadTerminalDrawer({ - mode = "drawer", threadRef, threadId, cwd, worktreePath, runtimeEnv, visible = true, - height, - composerHeight = 0, terminalIds, activeTerminalId, terminalGroups, @@ -1508,7 +1448,6 @@ export default function ThreadTerminalDrawer({ closeShortcutLabel, onActiveTerminalChange, onCloseTerminal, - onHeightChange, onAddTerminalContext, keybindings, terminalLabelsById, @@ -1517,27 +1456,11 @@ export default function ThreadTerminalDrawer({ const gt = useGT(); const messages = useMessages(); const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); - const terminalArea = workspaceAreaProps("terminal", 5, gt("Terminal")); - const isPanel = mode === "panel"; const [advancedTypography] = useLocalStorage( TYPOGRAPHY_ADVANCED_STORAGE_KEY, false, Schema.Boolean, ); - const drawerRef = useRef(null); - const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null)); - const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight }); - const drawerHeight = clampDrawerHeight(height, maxDrawerHeight); - // A drag only writes the drawer's style; the store hears the height once, at - // pointerup. The custom property outranks the rendered height while it is set. - const resizeStateRef = useRef<{ - pointerId: number; - startY: number; - startHeight: number; - height: number; - drawer: HTMLElement | null; - } | null>(null); - const normalizedTerminalIds = (() => { const normalizedIds: string[] = []; const seen = new Set(); @@ -1709,123 +1632,13 @@ export default function ThreadTerminalDrawer({ }); }; - const handleResizePointerDown = (event: ReactPointerEvent) => { - if (event.button !== 0) return; - event.preventDefault(); - event.currentTarget.setPointerCapture(event.pointerId); - resizeStateRef.current = { - pointerId: event.pointerId, - startY: event.clientY, - startHeight: drawerHeight, - height: drawerHeight, - drawer: event.currentTarget.parentElement, - }; - }; - - const handleResizePointerMove = (event: ReactPointerEvent) => { - const resizeState = resizeStateRef.current; - if (!resizeState || resizeState.pointerId !== event.pointerId) return; - event.preventDefault(); - const clampedHeight = clampDrawerHeight( - resizeState.startHeight + (resizeState.startY - event.clientY), - maxDrawerHeight, - ); - if (clampedHeight === resizeState.height) { - return; - } - resizeState.height = clampedHeight; - resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${clampedHeight}px`); - }; - - const handleResizePointerEnd = (event: ReactPointerEvent) => { - const resizeState = resizeStateRef.current; - if (!resizeState || resizeState.pointerId !== event.pointerId) return; - resizeStateRef.current = null; - if (event.currentTarget.hasPointerCapture(event.pointerId)) { - event.currentTarget.releasePointerCapture(event.pointerId); - } - resizeState.drawer?.style.removeProperty(DRAG_HEIGHT_PROPERTY); - // A drag that ends where it started keeps the stored preference, which may - // be taller than the capped height the drag started from. - if (resizeState.height === resizeState.startHeight || resizeState.height === height) return; - onHeightChange(resizeState.height); - }; - - const drawerLayoutRef = useRef(drawerLayout); - const updateDrawerLayout = useEffectEvent( - (column: HTMLElement | null, source: "window" | "column") => { - const layout = readDrawerLayout(column); - const previous = drawerLayoutRef.current; - const heightBudgetChanged = - layout.viewportHeight !== previous.viewportHeight || - layout.chatColumnHeight !== previous.chatColumnHeight || - layout.headerHeight !== previous.headerHeight; - // The column also reports width-only changes, such as every frame of a - // right panel drag; the surface refits itself for those. - if (!heightBudgetChanged && source === "column") return; - drawerLayoutRef.current = layout; - const resizeState = resizeStateRef.current; - if (resizeState) { - const liveHeight = clampDrawerHeight( - resizeState.height, - resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }), - ); - if (liveHeight !== resizeState.height) { - resizeState.height = liveHeight; - resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${liveHeight}px`); - } - } - if (heightBudgetChanged) setDrawerLayout(layout); - }, - ); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the drawer before visible paint and observes window and chat column resizes while visible - useLayoutEffect(() => { - if (!visible) { - return; - } - // The column and window may have resized while the drawer was hidden and - // not listening, so measure before the first visible paint. - const column = isPanel ? null : chatColumnOf(drawerRef.current); - const onWindowResize = () => updateDrawerLayout(column, "window"); - onWindowResize(); - const header = column?.querySelector("[data-chat-header]"); - const stopObserving = column - ? observeResize(header ? [column, header] : column, () => - updateDrawerLayout(column, "column"), - ) - : undefined; - window.addEventListener("resize", onWindowResize); - return () => { - stopObserving?.(); - window.removeEventListener("resize", onWindowResize); - }; - }, [isPanel, visible]); - - const resizeHandle = isPanel ? null : ( -
- ); - if (normalizedTerminalIds.length === 0) { return (