diff --git a/.gitattributes b/.gitattributes index 24860868b59bc..ab74efd46bf7f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,7 +3,8 @@ # Batch files need CRLF for cmd.exe to parse them reliably. *.cmd text eol=crlf *.bat text eol=crlf -# GitHub's and Expo's GraphQL schemas and the operations graphqlgen writes from them. +# GitHub's, Linear's and Expo's GraphQL schemas and the operations graphqlgen writes from them. packages/source-control-github/schema/** linguist-generated +packages/issue-tracker-linear/schema/** linguist-generated apps/server/schema/** linguist-generated **/*.graphql.ts linguist-generated diff --git a/.github/actions/drop-checkout-credentials/action.yml b/.github/actions/drop-checkout-credentials/action.yml new file mode 100644 index 0000000000000..f9a60340e1fe5 --- /dev/null +++ b/.github/actions/drop-checkout-credentials/action.yml @@ -0,0 +1,38 @@ +name: Drop checkout credentials +description: Removes the token actions/checkout leaves behind, so later steps can run dependency and build scripts. + +# checkout keeps the token in a file under RUNNER_TEMP that .git/config includes, so +# both go. `persist-credentials: false` fails in this repo: its cleanup runs `git +# submodule foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules). +runs: + using: composite + steps: + - name: Drop checkout credentials + shell: bash + run: | + # Status 1 means no match; any other failure stops the step. + lookup() { + local status=0 + git -C "$dir" config --local "$@" || status=$? + if [ "$status" -gt 1 ]; then exit "$status"; fi + } + for dir in . .trusted; do + [ -e "$dir/.git" ] || continue + lookup --get-regexp '^includeif\..*\.path$' | while read -r key file; do + rm -f "$file" + git -C "$dir" config --local --unset-all "$key" + done + lookup --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do + git -C "$dir" config --local --unset-all "$key" + done + remaining="$(lookup --get-regexp 'extraheader|includeif')" + if [ -n "$remaining" ]; then + echo "::error::checkout credentials are still configured in $dir" + exit 1 + fi + done + rm -f "$RUNNER_TEMP"/git-credentials-*.config + if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then + echo "::error::a checkout credential file is still present" + exit 1 + fi diff --git a/.github/actions/eas-local-build/action.yml b/.github/actions/eas-local-build/action.yml new file mode 100644 index 0000000000000..847c8e0117492 --- /dev/null +++ b/.github/actions/eas-local-build/action.yml @@ -0,0 +1,188 @@ +name: EAS local build +description: Installs the toolchain and mobile dependencies, then runs `eas build --local` on this runner. + +inputs: + platform: + description: android or ios + required: true + profile: + description: eas.json build profile + required: true + environment: + description: EAS environment to pull, preview or production + required: true + expo-token: + description: Expo token for that environment + required: true + output: + description: Path the build artifact is written to + required: true + cache: + description: "false for untrusted code: no sticky disk and no EAS cache, so nothing it writes reaches trusted builds" + default: "true" + sourcemaps-r2: + description: R2 credentials for the eas-build-on-success source map upload; EAS secrets don't reach local builds + default: "" + +runs: + using: composite + steps: + - name: Prepare Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + env: + CACHE_NAME: ${{ inputs.environment == 'production' && 'store' || 'preview' }} + run: | + cache="$HOME/.cache/t3-android-$CACHE_NAME" + { + echo "GRADLE_USER_HOME=$cache/gradle" + echo "CCACHE_DIR=$cache/ccache" + echo "CCACHE_MAXSIZE=5G" + # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. + echo "CCACHE_COMPILERCHECK=%compiler% -v" + echo "pnpm_config_store_dir=$cache/pnpm-store" + # eas build --local copies the project here. A fixed path keeps + # ccache keys stable, and the same disk as the store lets pnpm hardlink. + echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" + echo "CCACHE_BASEDIR=$cache/eas-build" + # CMake (3.17+) reads these, and AGP passes Gradle's environment through. + echo "CMAKE_C_COMPILER_LAUNCHER=ccache" + echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" + } >> "$GITHUB_ENV" + + - name: Mount Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 + with: + key: ${{ github.repository }}-android-${{ inputs.environment == 'production' && 'store' || 'preview' }}-build + path: ~/.cache/t3-android-${{ inputs.environment == 'production' && 'store' || 'preview' }} + + - name: Configure Gradle and ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" + rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" + # No daemon: nothing should hold the sticky disk open when it is committed. + printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" + sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources + sudo apt-get update -qq && sudo apt-get install -y -qq ccache + ccache --zero-stats + + # Matches the EAS build image in eas.json. + - name: Select Xcode 27.1 + if: inputs.platform == 'ios' + shell: bash + run: | + xcode=/Applications/Xcode_27.1.app + if [ ! -d "$xcode" ]; then + ls -d /Applications/Xcode*.app + echo "::error::Xcode 27.1 is not on this runner." + exit 1 + fi + sudo xcode-select -s "$xcode/Contents/Developer" + xcodebuild -version + echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" + + # EAS's credentials step fails to import the distribution certificate without it. + - name: Install Apple WWDR G3 intermediate + if: inputs.platform == 'ios' + shell: bash + run: | + curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer + sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true + security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep labl + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - name: Enable corepack + shell: bash + run: | + npm install --global corepack@latest + corepack enable + pnpm --version + + # EAS commands load app.config.ts, whose plugins must resolve. Keep install + # scripts: some download native assets that the build's fingerprint check hashes. + - name: Install mobile dependencies + shell: bash + run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... + + - name: Setup Java + if: inputs.platform == 'android' + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + with: + distribution: temurin + java-version: 17 + + - name: Setup EAS + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + with: + eas-version: latest + eas-cache: ${{ inputs.cache }} + token: ${{ inputs.expo-token }} + # npm, not pnpm: this only installs eas-cli into the action's own + # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's + # ignored build script (no allowBuilds config outside the repo). + packager: npm + + - name: Build tools + if: inputs.platform == 'ios' + shell: bash + run: | + command -v pod || sudo gem install cocoapods --no-document + command -v fastlane || brew install fastlane + pod --version + fastlane --version | tail -1 + + # EAS commands skip dotenv, and the Android fingerprint hashes this file. + - name: Pull ${{ inputs.environment }} environment variables + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + ENVIRONMENT: ${{ inputs.environment }} + PLATFORM: ${{ inputs.platform }} + run: | + eas env:pull "$ENVIRONMENT" --non-interactive + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from "node:fs"; + import { parseEnv } from "node:util"; + const env = parseEnv(readFileSync(".env.local", "utf8")); + const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; + if (!googleServicesFile && process.env.PLATFORM === "android") { + throw new Error(`T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the ${process.env.ENVIRONMENT} environment`); + } + if (googleServicesFile) { + appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); + } + NODE + + - name: Build + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + MOBILE_SOURCEMAPS_R2: ${{ inputs.sourcemaps-r2 }} + PLATFORM: ${{ inputs.platform }} + PROFILE: ${{ inputs.profile }} + OUTPUT: ${{ inputs.output }} + run: | + if [ "$PLATFORM" = "ios" ]; then + # A real path: /var -> /private/var symlinks break the expo-widgets bundle step. + export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" + fi + eas build --local --platform "$PLATFORM" --profile "$PROFILE" --non-interactive --output "$OUTPUT" + + - name: Report ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + { + echo '```' + ccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml new file mode 100644 index 0000000000000..2086d004b295c --- /dev/null +++ b/.github/actions/record-build-tag/action.yml @@ -0,0 +1,57 @@ +name: Record build tag +description: Pushes the tag that tells later runs a build for this fingerprint exists. + +inputs: + tag: + description: Tag name, without refs/tags/ + required: true + message: + description: Annotated tag message; empty makes a lightweight tag + default: "" + replace: + description: "true replaces an existing tag; otherwise an existing tag counts as recorded" + default: "false" + token: + description: Token with contents write + required: true + +runs: + using: composite + steps: + - name: Record build tag + shell: bash + env: + TAG: ${{ inputs.tag }} + MESSAGE: ${{ inputs.message }} + REPLACE: ${{ inputs.replace }} + GH_TOKEN: ${{ inputs.token }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). + for attempt in 1 2 3; do + if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then + old="$(printf '%s\n' "$refs" | while read -r sha ref; do + if [ "$ref" = "refs/tags/$TAG" ]; then echo "$sha"; fi + done)" + if [ -n "$old" ] && [ "$REPLACE" != "true" ]; then + echo "$TAG exists." + exit 0 + fi + if [ -n "$MESSAGE" ]; then + git tag -f -a "$TAG" -m "$MESSAGE" + else + git tag -f "$TAG" + fi + # An empty lease means the tag must not exist yet. + if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then + exit 0 + fi + fi + if [ "$attempt" = 3 ]; then + echo "::error::Could not push $TAG." + exit 1 + fi + sleep $((attempt * 15)) + done diff --git a/.github/fork/upstream-tag b/.github/fork/upstream-tag index f0b8a9a13245b..b24b9847b7995 100644 --- a/.github/fork/upstream-tag +++ b/.github/fork/upstream-tag @@ -1 +1 @@ -v0.1.10-nightly.20261116.4774 +v0.1.11-nightly.20261117.4825 diff --git a/.github/scripts/mobile-ios-preview-record.cjs b/.github/scripts/mobile-ios-preview-record.cjs new file mode 100644 index 0000000000000..3f18fe51e4260 --- /dev/null +++ b/.github/scripts/mobile-ios-preview-record.cjs @@ -0,0 +1,32 @@ +const { readFileSync } = require("node:fs"); + +function readClient(value, now = Date.now()) { + try { + const record = JSON.parse(value); + return typeof record?.link === "string" && Date.parse(record.expiresAt) > now + ? record.link + : ""; + } catch { + return ""; + } +} + +function createRecord(link, profile) { + const expiration = /ExpirationDate<\/key>\s*([^<]+)<\/date>/.exec(profile)?.[1]; + if (!expiration || !Number.isFinite(Date.parse(expiration))) { + throw new Error("The provisioning profile has no valid ExpirationDate."); + } + return JSON.stringify({ link, expiresAt: new Date(expiration).toISOString() }); +} + +if (require.main === module) { + if (process.argv[2] === "read") { + process.stdout.write(readClient(readFileSync(0, "utf8"))); + } else if (process.argv[2] === "create") { + process.stdout.write(createRecord(process.argv[3], readFileSync(process.argv[4], "utf8"))); + } else { + throw new Error("Expected read or create."); + } +} + +module.exports = { createRecord, readClient }; diff --git a/.github/scripts/mobile-ios-preview-record.test.cjs b/.github/scripts/mobile-ios-preview-record.test.cjs new file mode 100644 index 0000000000000..16750e47a1616 --- /dev/null +++ b/.github/scripts/mobile-ios-preview-record.test.cjs @@ -0,0 +1,17 @@ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { createRecord, readClient } = require("./mobile-ios-preview-record.cjs"); + +test("only clients with an unexpired provisioning profile are reused", () => { + const link = "https://expo.dev/accounts/pingdotgg/projects/t3-code/builds/client"; + const profile = + "ExpirationDate2027-01-01T00:00:00Z"; + const record = createRecord(link, profile); + assert.equal(readClient(record, Date.parse("2026-12-31T00:00:00Z")), link); + assert.equal(readClient(record, Date.parse("2027-01-01T00:00:00Z")), ""); + assert.equal(readClient(record, Date.parse("2027-01-02T00:00:00Z")), ""); + for (const invalid of [link, "{}", "null", JSON.stringify({ link, expiresAt: "invalid" })]) { + assert.equal(readClient(invalid, 0), ""); + } + assert.throws(() => createRecord(link, ""), /ExpirationDate/); +}); diff --git a/.github/scripts/mobile-preview-comment.cjs b/.github/scripts/mobile-preview-comment.cjs index e4876b0842eaa..217f12c586ef9 100644 --- a/.github/scripts/mobile-preview-comment.cjs +++ b/.github/scripts/mobile-preview-comment.cjs @@ -1,21 +1,25 @@ -// The Android half of the mobile preview comment. The android job writes the fingerprint and -// the update; the android-build job adds the client's install link a few minutes later. Each -// run merges what it knows into the state kept in the comment's first line. -const MARKER = "mobile-preview-android"; const PROJECT_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454"; const APP_SCHEME = "t3-code"; function readState(body) { - const match = new RegExp(`^`).exec(body ?? ""); + const match = /^/.exec(body ?? ""); if (!match) return null; try { - const state = JSON.parse(match[1]); + const parsed = JSON.parse(match[2]); + const state = match[1] ? { [match[1]]: parsed } : parsed; const text = (value) => (typeof value === "string" ? value : ""); - return { - fingerprint: text(state.fingerprint), - client: text(state.client), - group: text(state.group), - }; + return Object.fromEntries( + ["android", "ios"] + .filter((platform) => state?.[platform]) + .map((platform) => [ + platform, + { + fingerprint: text(state[platform].fingerprint), + client: text(state[platform].client), + group: text(state[platform].group), + }, + ]), + ); } catch { return null; } @@ -27,6 +31,7 @@ function readState(body) { * the comment now shows. */ function mergeState(previous, next) { + if (!next.client && !next.group) return previous; const buildOnly = Boolean(next.client) && !next.group; if ( buildOnly && @@ -46,22 +51,23 @@ function mergeState(previous, next) { } function render(state, runUrl) { - const qr = `https://qr.expo.dev/eas-update?appScheme=${APP_SCHEME}&projectId=${PROJECT_ID}&groupId=${state.group}`; + const platforms = ["android", "ios"]; + const cells = (value) => platforms.map((platform) => value(state[platform])); const rows = [ - ``, - "🤖 Android preview", + ``, + "🚀 Mobile preview", "", - "  | 🤖 Android", - "--- | ---", - `Fingerprint | ${state.fingerprint || "n/a"}`, - `Dev client | ${state.client ? `[Install](${state.client})` : `Building on Blacksmith ([run](${runUrl})); this comment gets the install link when it finishes`}`, + "  | 🤖 Android | 🍎 iOS", + "--- | --- | ---", + `Fingerprint | ${cells((entry) => entry?.fingerprint || "n/a").join(" | ")}`, + `Dev client | ${cells((entry) => (entry?.client ? `[Install](${entry.client})` : entry?.fingerprint ? `Client unavailable ([build run](${runUrl}))` : "n/a")).join(" | ")}`, + `Update Details | ${cells((entry) => (entry?.group ? `[Update Permalink](https://expo.dev/projects/${PROJECT_ID}/updates/${entry.group})` : "n/a")).join(" | ")}`, + `Update QR | ${cells((entry) => { + if (!entry?.group) return "n/a"; + const qr = `https://qr.expo.dev/eas-update?appScheme=${APP_SCHEME}&projectId=${PROJECT_ID}&groupId=${entry.group}`; + return ``; + }).join(" | ")}`, ]; - if (state.group) { - rows.push( - `Update Details | [Update Permalink](https://expo.dev/projects/${PROJECT_ID}/updates/${state.group})`, - `Update QR | `, - ); - } return rows.join("\n"); } @@ -80,39 +86,64 @@ async function github(path, init = {}) { `GitHub ${init.method ?? "GET"} ${path}: ${response.status} ${await response.text()}`, ); } - return response.json(); + return response.status === 204 ? null : response.json(); } -async function main() { - const repository = process.env.GITHUB_REPOSITORY; - const pr = process.env.PR; - if (!repository || !pr || !process.env.GH_TOKEN) { +async function main({ env = process.env, request = github } = {}) { + const repository = env.GITHUB_REPOSITORY; + const pr = env.PR; + if (!repository || !pr || !env.GH_TOKEN) { throw new Error("GITHUB_REPOSITORY, PR and GH_TOKEN are required."); } - const runUrl = `${process.env.GITHUB_SERVER_URL}/${repository}/actions/runs/${process.env.GITHUB_RUN_ID}`; - let existing = null; - for (let page = 1; existing === null; page++) { - const comments = await github( + if (!env.ANDROID_FINGERPRINT && !env.IOS_FINGERPRINT) return; + if (env.PR_HEAD_SHA) { + const pull = await request(`/repos/${repository}/pulls/${pr}`); + if (pull.head.sha !== env.PR_HEAD_SHA) return; + } + const runUrl = `${env.GITHUB_SERVER_URL}/${repository}/actions/runs/${env.GITHUB_RUN_ID}`; + const previews = []; + for (let page = 1; ; page++) { + const comments = await request( `/repos/${repository}/issues/${pr}/comments?per_page=100&page=${page}`, ); - // Only this workflow's own comment: anyone can post the marker, and nobody else's is editable. - existing = - comments.find( + previews.push( + ...comments.filter( (comment) => - comment.user?.login === "github-actions[bot]" && readState(comment.body) !== null, - ) ?? null; + comment.user?.login === "github-actions[bot]" && + (readState(comment.body) !== null || + comment.body?.startsWith( + ``, + )), + ), + ); if (comments.length < 100) break; } - const state = mergeState(readState(existing?.body), { - fingerprint: process.env.FINGERPRINT ?? "", - client: process.env.CLIENT ?? "", - group: process.env.GROUP ?? "", - }); + const existing = + previews.find((comment) => comment.body.startsWith("\nx'), - { - fingerprint: "", - client: "", - group: "", - }, + { android: { fingerprint: "", client: "", group: "" } }, ); }); + +test("publishing consolidates platform comments and preserves unrelated comments", async () => { + const android = { fingerprint, client: "https://expo.dev/android", group: "android-group" }; + const ios = { + fingerprint: "ios-fingerprint", + client: "https://expo.dev/ios", + group: "ios-group", + }; + const comments = new Map([ + [ + 1, + { + id: 1, + user: { login: "github-actions[bot]" }, + body: ``, + }, + ], + [ + 2, + { + id: 2, + user: { login: "github-actions[bot]" }, + body: ``, + }, + ], + [ + 4, + { + id: 4, + user: { login: "github-actions[bot]" }, + body: "\nOld Expo preview", + }, + ], + [ + 3, + { + id: 3, + user: { login: "contributor" }, + body: ``, + }, + ], + ]); + await main({ + env: { + GITHUB_REPOSITORY: "pingdotgg/t3code", + PR: "1", + GH_TOKEN: "test", + ANDROID_FINGERPRINT: fingerprint, + ANDROID_GROUP: "new-group", + }, + request: async (path, init = {}) => { + if (!init.method) return [...comments.values()]; + const id = Number(path.split("/").at(-1)); + if (init.method === "DELETE") comments.delete(id); + else if (init.method === "PATCH") comments.get(id).body = JSON.parse(init.body).body; + else assert.fail("an existing preview should be reused"); + }, + }); + assert.equal(comments.size, 2); + assert.deepEqual(readState(comments.get(1).body), { + android: { ...android, group: "new-group" }, + ios, + }); + assert.equal(comments.has(2), false); + assert.equal(comments.has(4), false); + assert.equal(comments.get(3).user.login, "contributor"); + await main({ + env: { + GITHUB_REPOSITORY: "pingdotgg/t3code", + PR: "1", + GH_TOKEN: "test", + ANDROID_FINGERPRINT: fingerprint, + PR_HEAD_SHA: "old-head", + }, + request: async (path) => { + assert.equal(path, "/repos/pingdotgg/t3code/pulls/1"); + return { head: { sha: "new-head" } }; + }, + }); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6bfb648fe368c..40c84a71ad84b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,6 +110,12 @@ jobs: - name: Check generated Expo GraphQL operations run: vp run --filter t3 generate --check + - name: Check generated Linear GraphQL operations + run: vp run --filter @t3tools/issue-tracker-linear generate --check + + - name: Check i18n catalogs + run: vp run i18n:check + - name: Check run: vp check @@ -326,7 +332,7 @@ jobs: run: python3 -B .github/scripts/stage-preview-bundle.test.py - name: Test release checks - run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/test-delta.test.cjs + run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs - name: Finish installing browser secret helper build libraries timeout-minutes: 5 diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 13ca814defd7e..890bd0c2aecd9 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -1,8 +1,8 @@ name: Mobile EAS Preview (Fork) # EAS previews for fork PRs. This runs the PR's code with an Expo token: the -# app config and plugins run on this runner, the iOS client builds on EAS and -# the Android one on Blacksmith (android-build), with preview signing credentials. The label is the maintainer's sign-off +# app config and plugins run on this runner; both clients build on Blacksmith +# with preview signing credentials. The label is the maintainer's sign-off # that they reviewed that code, so it covers exactly the commit it was applied # to: this pins that commit and consumes the label before running anything. A # later push deploys nothing until the label is applied again. @@ -30,6 +30,12 @@ jobs: contents: read pull-requests: write outputs: + ios_group: ${{ steps.ios_update.outputs.group }} + ios_client: ${{ steps.ios_client.outputs.link }} + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} + ios_build: ${{ steps.ios_client.outputs.build }} + ios_fingerprint: ${{ steps.ios_client.outputs.fingerprint }} build: ${{ steps.client.outputs.build }} fingerprint: ${{ steps.client.outputs.fingerprint }} env: @@ -81,40 +87,20 @@ jobs: fetch-depth: 0 # No sparse-checkout: see mobile-eas-preview.yml. - # The comment script comes from main, not from the PR. + # Scripts and actions come from main, not from the PR. - name: Checkout trusted scripts if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: path: .trusted - sparse-checkout: .github/scripts + sparse-checkout: | + .github/scripts + .github/actions - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials if: steps.expo-token.outputs.present == 'true' - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.trusted/.github/actions/drop-checkout-credentials # No caches: pull_request_target saves them under main's scope, where # trusted workflows with other secrets would restore what PR code wrote. @@ -140,8 +126,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: - # Pinned and installed with npm for the same reasons as mobile-eas-preview.yml. - eas-version: 21.8.0 + eas-version: latest eas-cache: false token: ${{ secrets.EXPO_PREVIEW_TOKEN }} packager: npm @@ -164,23 +149,40 @@ jobs: } NODE - - name: Deploy with fingerprint check + - id: ios_client + name: Find the iOS client for this fingerprint if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action/continuous-deploy-fingerprint@5273c2136bd09c2a341fe3340d3e767ce5a13015 # v9.0.2 + working-directory: apps/mobile + shell: bash env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - RUNNER_DEBUG: "1" - # The action only comments for pull_request events; this hook gives - # it the PR under pull_request_target. Without it, it skips the comment. - EXPO_TEST_GITHUB_PULL: ${{ github.event.pull_request.number }} - with: - profile: preview:dev - branch: pr-${{ github.event.pull_request.number }} - # Android is below: its client builds on Blacksmith (android-build). - platform: ios - environment: preview - working-directory: apps/mobile - github-token: ${{ secrets.GITHUB_TOKEN }} + run: | + hash="$(eas env:exec --non-interactive preview "npx expo-updates fingerprint:generate --platform ios" | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')" + echo "fingerprint=$hash" >> "$GITHUB_OUTPUT" + tag="mobile-ios-preview-build/$hash" + link="" + if git fetch --quiet origin "refs/tags/$tag:refs/tags/$tag" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$tag" | node "$GITHUB_WORKSPACE/.trusted/.github/scripts/mobile-ios-preview-record.cjs" read)" + fi + if [ -z "$link" ]; then + link="$(eas build:list --platform ios --build-profile preview:dev --runtime-version "$hash" --status finished --limit 5 --json --non-interactive \ + | sed -n '/^\[/,$p' \ + | jq -r --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" '[.[] | select((.expirationDate // "9999") > $now)][0] | select(. != null) | "https://expo.dev/accounts/pingdotgg/projects/t3-code/builds/\(.id)"')" + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + if [ -z "$link" ]; then echo "build=true" >> "$GITHUB_OUTPUT"; fi + + - id: ios_update + name: Publish the iOS update + if: steps.expo-token.outputs.present == 'true' + working-directory: apps/mobile + shell: bash + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + PR: ${{ github.event.pull_request.number }} + run: | + group="$(eas update --auto --branch "pr-$PR" --platform ios --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" + echo "group=$group" >> "$GITHUB_OUTPUT" # Android, as in mobile-eas-preview.yml: the same fingerprint command the Expo # action runs. A client built for a same-repo PR (its tag) or by EAS is reused. @@ -218,16 +220,6 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" - - name: Comment - if: steps.expo-token.outputs.present == 'true' - env: - GH_TOKEN: ${{ github.token }} - PR: ${{ github.event.pull_request.number }} - FINGERPRINT: ${{ steps.client.outputs.fingerprint }} - CLIENT: ${{ steps.client.outputs.link }} - GROUP: ${{ steps.update.outputs.group }} - run: node .trusted/.github/scripts/mobile-preview-comment.cjs - # The reviewed commit's Android client, built cold: no sticky disk, because PR # code could leave Gradle or ccache state that trusted builds would restore, and # no build record tag, so nobody else is served an APK a fork's code built. @@ -240,6 +232,8 @@ jobs: permissions: contents: read pull-requests: write + outputs: + client: ${{ steps.build.outputs.link }} env: APP_VARIANT: preview NODE_OPTIONS: --max-old-space-size=8192 @@ -254,92 +248,100 @@ jobs: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 - # The comment script comes from main, not from the PR. + # Scripts and actions come from main, not from the PR. - name: Checkout trusted scripts uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: path: .trusted - sparse-checkout: .github/scripts + sparse-checkout: | + .github/scripts + .github/actions - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.trusted/.github/actions/drop-checkout-credentials - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + # Cold: no sticky disk or EAS cache that trusted builds would restore. + - name: Build + uses: ./.trusted/.github/actions/eas-local-build with: - node-version-file: package.json + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk + cache: "false" - - name: Enable corepack + - id: build + name: Upload + working-directory: apps/mobile + shell: bash + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - name: Install mobile dependencies - run: pnpm install --frozen-lockfile --filter=@t3tools/mobile... + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" - - name: Setup Java - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + ios-build: + name: iOS preview client + needs: preview + if: needs.preview.outputs.ios_build == 'true' + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + pull-requests: write + outputs: + client: ${{ steps.build.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + FINGERPRINT: ${{ needs.preview.outputs.ios_fingerprint }} + steps: + - name: Checkout reviewed commit + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - distribution: temurin - java-version: 17 + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 - - name: Setup EAS - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + # Scripts and actions come from main, not from the PR. + - name: Checkout trusted scripts + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - eas-version: latest - eas-cache: false - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm + path: .trusted + sparse-checkout: | + .github/scripts + .github/actions - - name: Pull preview environment variables - working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - run: | - eas env:pull preview --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (googleServicesFile) { - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - } - NODE + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.trusted/.github/actions/drop-checkout-credentials + + # Cold: no sticky disk or EAS cache that trusted builds would restore. + - name: Build + uses: ./.trusted/.github/actions/eas-local-build + with: + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa + cache: "false" - id: build - name: Build and upload + name: Upload working-directory: apps/mobile shell: bash env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | - eas build --local --platform android --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.apk" - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then echo "::error::eas upload returned no install link" @@ -347,9 +349,32 @@ jobs: fi echo "link=$link" >> "$GITHUB_OUTPUT" + comment: + name: Mobile preview comment + needs: [preview, android-build, ios-build] + if: always() && !cancelled() && needs.preview.result == 'success' + runs-on: blacksmith-2vcpu-ubuntu-2404 + concurrency: + group: mobile-preview-comment-${{ github.event.pull_request.number }} + cancel-in-progress: false + permissions: + contents: read + pull-requests: write + steps: + - name: Checkout comment script + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + sparse-checkout: .github/scripts + - name: Comment env: GH_TOKEN: ${{ github.token }} PR: ${{ github.event.pull_request.number }} - CLIENT: ${{ steps.build.outputs.link }} - run: node .trusted/.github/scripts/mobile-preview-comment.cjs + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + ANDROID_FINGERPRINT: ${{ needs.preview.outputs.fingerprint }} + ANDROID_GROUP: ${{ needs.preview.outputs.group }} + ANDROID_CLIENT: ${{ needs.android-build.outputs.client || needs.preview.outputs.client }} + IOS_FINGERPRINT: ${{ needs.preview.outputs.ios_fingerprint }} + IOS_GROUP: ${{ needs.preview.outputs.ios_group }} + IOS_CLIENT: ${{ needs.ios-build.outputs.client || needs.preview.outputs.ios_client }} + run: node .github/scripts/mobile-preview-comment.cjs diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index b46e090434f58..53061f25e9c48 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -5,35 +5,40 @@ on: types: [opened, reopened, synchronize, labeled] jobs: - preview: + ios: name: EAS Preview (iOS) - # Fork PRs deploy one reviewed commit per label through mobile-eas-preview-fork.yml. if: | 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') runs-on: blacksmith-8vcpu-ubuntu-2404 concurrency: - group: mobile-eas-preview-${{ github.event.pull_request.number }} + group: mobile-eas-preview-ios-${{ github.event.pull_request.number }} cancel-in-progress: true permissions: contents: read pull-requests: write + outputs: + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} + build: ${{ steps.client.outputs.build }} + fingerprint: ${{ steps.client.outputs.fingerprint }} env: APP_VARIANT: preview NODE_OPTIONS: --max-old-space-size=8192 MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} steps: - id: expo-token name: Check for EXPO_PREVIEW_TOKEN - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | if [ -n "$EXPO_TOKEN" ]; then echo "present=true" >> "$GITHUB_OUTPUT" else echo "present=false" >> "$GITHUB_OUTPUT" - echo "EXPO_PREVIEW_TOKEN is not available; skipping EAS preview." + echo "EXPO_PREVIEW_TOKEN is not available; skipping the iOS preview." fi - name: Checkout @@ -41,10 +46,11 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 - # No sparse-checkout here: it makes actions/checkout fetch with - # --filter=blob:none, and eas-cli archives the project via - # `git clone --depth 1 file://`, which fails (exit 128) - # when the partial clone can't serve the unfetched blobs. + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + if: steps.expo-token.outputs.present == 'true' + uses: ./.github/actions/drop-checkout-credentials - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' @@ -68,25 +74,15 @@ jobs: if: steps.expo-token.outputs.present == 'true' uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: - # eas-cli 22 renamed `project` to `app` in build JSON, and - # continuous-deploy-fingerprint still reads `build.project.ownerAccount`. - # Unpin once https://github.com/expo/expo-github-action/issues/358 is fixed. - eas-version: 21.8.0 + eas-version: latest token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - # npm, not pnpm: this only installs eas-cli into the action's own - # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's - # ignored build script (no allowBuilds config outside the repo). packager: npm - name: Pull preview environment variables if: steps.expo-token.outputs.present == 'true' working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | eas env:pull preview --non-interactive - # EAS Update disables dotenv loading. Keep the downloaded native config - # in its process environment so Android build and OTA fingerprints match. node --input-type=module <<'NODE' import { appendFileSync, readFileSync } from "node:fs"; import { parseEnv } from "node:util"; @@ -97,27 +93,40 @@ jobs: } NODE - - name: Deploy with fingerprint check + # The same command the Expo action runs, so this is the runtime version the update gets. + - id: client + name: Find the client for this fingerprint if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action/continuous-deploy-fingerprint@5273c2136bd09c2a341fe3340d3e767ce5a13015 # v9.0.2 - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - # The Expo action otherwise suppresses the EAS command's failure output. - RUNNER_DEBUG: "1" - with: - profile: preview:dev - branch: pr-${{ github.event.pull_request.number }} - # Android is the android job below: its client builds on Blacksmith. - platform: ios - environment: preview - working-directory: apps/mobile - github-token: ${{ secrets.GITHUB_TOKEN }} - - # Android publishes its own update and comment, because the Expo action can only - # find a client that EAS built. A fingerprint with no client is built by - # android-build with `eas build --local` on Blacksmith (about 4 minutes warm, - # against about 40 on EAS) and recorded as a mobile-android-preview-build/ - # tag whose message is the install link. Clients EAS built earlier still count. + working-directory: apps/mobile + shell: bash + run: | + hash="$(eas env:exec --non-interactive preview "npx expo-updates fingerprint:generate --platform ios" | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')" + echo "fingerprint=$hash" >> "$GITHUB_OUTPUT" + tag="mobile-ios-preview-build/$hash" + link="" + if git fetch --quiet origin "refs/tags/$tag:refs/tags/$tag" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$tag" | node "$GITHUB_WORKSPACE/.github/scripts/mobile-ios-preview-record.cjs" read)" + fi + if [ -z "$link" ]; then + # A client EAS built before this job existed; expired ones are gone. + link="$(eas build:list --platform ios --build-profile preview:dev --runtime-version "$hash" --status finished --limit 5 --json --non-interactive \ + | sed -n '/^\[/,$p' \ + | jq -r --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" '[.[] | select((.expirationDate // "9999") > $now)][0] | select(. != null) | "https://expo.dev/accounts/pingdotgg/projects/t3-code/builds/\(.id)"')" + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + if [ -z "$link" ]; then echo "build=true" >> "$GITHUB_OUTPUT"; fi + echo "ios fingerprint \`$hash\`: ${link:-no client yet, building on Blacksmith}" >> "$GITHUB_STEP_SUMMARY" + + - id: update + name: Publish the update + if: steps.expo-token.outputs.present == 'true' + working-directory: apps/mobile + shell: bash + run: | + group="$(eas update --auto --branch "pr-$PR" --platform ios --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" + echo "group=$group" >> "$GITHUB_OUTPUT" + + # Preview build tags store the install link for each fingerprint; older EAS clients also count. android: name: EAS Preview (Android) if: | @@ -132,6 +141,8 @@ jobs: contents: read pull-requests: write outputs: + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} build: ${{ steps.client.outputs.build }} fingerprint: ${{ steps.client.outputs.fingerprint }} env: @@ -158,32 +169,10 @@ jobs: with: fetch-depth: 0 - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials if: steps.expo-token.outputs.present == 'true' - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' @@ -258,14 +247,6 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" - - name: Comment - if: steps.expo-token.outputs.present == 'true' - env: - FINGERPRINT: ${{ steps.client.outputs.fingerprint }} - CLIENT: ${{ steps.client.outputs.link }} - GROUP: ${{ steps.update.outputs.group }} - run: node .github/scripts/mobile-preview-comment.cjs - android-build: name: Android preview client needs: android @@ -276,9 +257,12 @@ jobs: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-android-preview-build-${{ needs.android.outputs.fingerprint }} cancel-in-progress: false + queue: max permissions: contents: write # pushes the build record tag pull-requests: write + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} env: APP_VARIANT: preview NODE_OPTIONS: --max-old-space-size=8192 @@ -302,154 +286,169 @@ jobs: echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" fi - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials - - name: Prepare build directories - if: steps.record.outputs.built != 'true' - run: | - cache="$HOME/.cache/t3-android-preview" - { - echo "GRADLE_USER_HOME=$cache/gradle" - echo "CCACHE_DIR=$cache/ccache" - echo "CCACHE_MAXSIZE=5G" - # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. - echo "CCACHE_COMPILERCHECK=%compiler% -v" - echo "pnpm_config_store_dir=$cache/pnpm-store" - # eas build --local copies the project here. A fixed path keeps - # ccache keys stable, and the same disk as the store lets pnpm hardlink. - echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" - echo "CCACHE_BASEDIR=$cache/eas-build" - echo "CMAKE_C_COMPILER_LAUNCHER=ccache" - echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" - } >> "$GITHUB_ENV" - - - name: Mount build cache + - name: Build if: steps.record.outputs.built != 'true' - uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 + uses: ./.github/actions/eas-local-build with: - key: ${{ github.repository }}-android-preview-build - path: ~/.cache/t3-android-preview + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk - - name: Configure Gradle and ccache + # `eas upload` hosts the APK on EAS and returns the page testers install from. + - id: build + name: Upload if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash run: | - mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" - rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" - # No daemon: nothing should hold the sticky disk open when it is committed. - printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" - sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources - sudo apt-get update -qq && sudo apt-get install -y -qq ccache - ccache --zero-stats + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - name: Setup Node + # The tag is the record later runs look up; its message is the install link. + - name: Record build if: steps.record.outputs.built != 'true' + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + message: ${{ steps.build.outputs.link }} + token: ${{ github.token }} + + ios-build: + name: iOS preview client + needs: ios + if: needs.ios.outputs.build == 'true' + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + concurrency: + # One build per fingerprint; a second PR with the same one finds the tag. + group: mobile-ios-preview-build-${{ needs.ios.outputs.fingerprint }} + cancel-in-progress: false + queue: max + permissions: + contents: write # pushes the build record tag + pull-requests: write + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} + BUILD_TAG: mobile-ios-preview-build/${{ needs.ios.outputs.fingerprint }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Setup Node uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: node-version-file: package.json - - name: Enable corepack - if: steps.record.outputs.built != 'true' + - id: record + name: Check build record run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" + if [ -n "$link" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$link" >> "$GITHUB_OUTPUT" + fi + fi - - name: Setup Java - if: steps.record.outputs.built != 'true' - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 17 + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials - - name: Setup EAS + - name: Build if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + uses: ./.github/actions/eas-local-build with: - eas-version: latest - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm - - - name: Pull preview environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: | - eas env:pull preview --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (googleServicesFile) { - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - } - NODE + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa - # `eas upload` hosts the APK on EAS and returns the page testers install from. + # EAS hosts the signed client and returns its install page. - id: build - name: Build and upload + name: Upload if: steps.record.outputs.built != 'true' working-directory: apps/mobile shell: bash run: | - eas build --local --platform android --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.apk" - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then echo "::error::eas upload returned no install link" exit 1 fi echo "link=$link" >> "$GITHUB_OUTPUT" - { - echo "### Android preview client for \`$FINGERPRINT\`: $link" - echo '```' - ccache --show-stats - echo '```' - } >> "$GITHUB_STEP_SUMMARY" + echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - # The tag is the record later runs look up; its message is the install link. - - name: Record build + # The tag stores the install link and provisioning-profile expiry. + - id: profile + name: Read the provisioning profile if: steps.record.outputs.built != 'true' env: LINK: ${{ steps.build.outputs.link }} - GH_TOKEN: ${{ github.token }} run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git tag -a "$BUILD_TAG" -m "$LINK" - # Only this step has the token; the checkout's copy was removed before the build. - git push "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "refs/tags/$BUILD_TAG" + profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" + unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" + security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" + record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" + echo "record=$record" >> "$GITHUB_OUTPUT" + + # Replaces an expired record for the same fingerprint. + - name: Record build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + message: ${{ steps.profile.outputs.record }} + replace: "true" + token: ${{ github.token }} + + comment: + name: Mobile preview comment + needs: [android, ios, android-build, ios-build] + if: always() && !cancelled() && (needs.android.result == 'success' || needs.ios.result == 'success') + runs-on: blacksmith-2vcpu-ubuntu-2404 + concurrency: + group: mobile-preview-comment-${{ github.event.pull_request.number }} + cancel-in-progress: false + permissions: + contents: read + pull-requests: write + steps: + - name: Checkout comment script + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + sparse-checkout: .github/scripts - name: Comment env: GH_TOKEN: ${{ github.token }} PR: ${{ github.event.pull_request.number }} - CLIENT: ${{ steps.build.outputs.link || steps.record.outputs.link }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + ANDROID_FINGERPRINT: ${{ needs.android.outputs.fingerprint }} + ANDROID_GROUP: ${{ needs.android.outputs.group }} + ANDROID_CLIENT: ${{ needs.android-build.outputs.client || needs.android.outputs.client }} + IOS_FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} + IOS_GROUP: ${{ needs.ios.outputs.group }} + IOS_CLIENT: ${{ needs.ios-build.outputs.client || needs.ios.outputs.client }} run: node .github/scripts/mobile-preview-comment.cjs diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index cdabb1e4b7ca3..fe4d7456acdf4 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -7,10 +7,8 @@ name: Mobile EAS Production # runner, with corepack pinning pnpm 10.24 in eas.json, local == build. # # Every merge reconciles native fingerprints and publishes matching OTAs. -# Android store builds run here with `eas build --local` on Blacksmith (the -# android job). iOS builds run on EAS unless the MOBILE_IOS_LOCAL_BUILDS -# repository variable is `true`, which moves them to the ios job the same way. -# Local builds never appear in `eas build:list`, so each finished local build +# Store builds run here with `eas build --local` on Blacksmith (the android and +# ios jobs). Local builds never appear in `eas build:list`, so each finished build # pushes a mobile-android-build// or # mobile-ios-build/// tag that the reconcile reads. # iOS prereleases use the testflight profile (3.0.0); App Store binaries use @@ -253,17 +251,9 @@ jobs: echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version." } >> "$GITHUB_STEP_SUMMARY" - - name: Build and submit iOS (manual) - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.platform != 'android' && vars.MOBILE_IOS_LOCAL_BUILDS != 'true' - working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - MOBILE_BUILD_PROFILE: ${{ inputs.profile || 'production' }} - run: eas build --platform ios --profile "$MOBILE_BUILD_PROFILE" --auto-submit --non-interactive --no-wait - - id: ios_manual name: Queue iOS build (manual) - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.platform != 'android' && vars.MOBILE_IOS_LOCAL_BUILDS == 'true' + if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.platform != 'android' working-directory: apps/mobile env: EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} @@ -351,7 +341,6 @@ jobs: working-directory: apps/mobile env: EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - IOS_LOCAL_BUILDS: ${{ vars.MOBILE_IOS_LOCAL_BUILDS == 'true' }} run: | failed=0 message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))" @@ -374,19 +363,16 @@ jobs: latest_version="$(eas build:list --platform "$platform" --build-profile "$profile" --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')" # Local builds (the android and ios jobs) record each build as a tag; # EAS records still count for builds made before that. - tag_prefix="" if [ "$platform" = "android" ]; then tag_prefix="mobile-android-build" - elif [ "$IOS_LOCAL_BUILDS" = "true" ]; then + else tag_prefix="mobile-ios-build/$profile" fi - if [ -n "$tag_prefix" ]; then - if [ -n "$(git tag -l "$tag_prefix/*/$hash")" ]; then - finished=$((finished + 1)) - fi - if [ -n "$(git tag -l "$tag_prefix/$version/*")" ]; then - latest_version="$version" - fi + if [ -n "$(git tag -l "$tag_prefix/*/$hash")" ]; then + finished=$((finished + 1)) + fi + if [ -n "$(git tag -l "$tag_prefix/$version/*")" ]; then + latest_version="$version" fi if [ "$finished" -gt 0 ]; then @@ -441,23 +427,14 @@ jobs: echo ":building_construction: android: building and submitting $version in the Android store build job ($reason)" >> "$GITHUB_STEP_SUMMARY" continue fi - if [ "$platform" = "ios" ] && [ "$IOS_LOCAL_BUILDS" = "true" ]; then - { - echo "ios_build=true" - echo "ios_profile=$profile" - echo "ios_fingerprint=$hash" - echo "ios_version=$version" - echo "ios_sha=$(git rev-parse HEAD)" - } >> "$GITHUB_OUTPUT" - echo ":building_construction: ios/$profile: building and submitting $version in the iOS store build job ($reason)" >> "$GITHUB_STEP_SUMMARY" - continue - fi - if eas build --platform "$platform" --profile "$profile" --auto-submit --non-interactive --no-wait; then - echo ":building_construction: $platform: scheduled production build and submission for $version ($reason)" >> "$GITHUB_STEP_SUMMARY" - else - failed=1 - echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY" - fi + { + echo "ios_build=true" + echo "ios_profile=$profile" + echo "ios_fingerprint=$hash" + echo "ios_version=$version" + echo "ios_sha=$(git rev-parse HEAD)" + } >> "$GITHUB_OUTPUT" + echo ":building_construction: ios/$profile: building and submitting $version in the iOS store build job ($reason)" >> "$GITHUB_STEP_SUMMARY" done exit "$failed" @@ -476,9 +453,9 @@ jobs: fi done - # `eas build --local` on Blacksmith, ARM-only, without release lint (see the - # production profile in eas.json), with Gradle, ccache, and pnpm state on a - # sticky disk. Its own concurrency group keeps later OTAs from waiting on it. + # ARM-only, without release lint (see the production profile in eas.json), + # with Gradle, ccache, and pnpm state on a sticky disk. Its own concurrency + # group keeps later OTAs from waiting on it. android: name: Android store build needs: production @@ -503,20 +480,9 @@ jobs: ref: ${{ needs.production.outputs.android_sha }} fetch-depth: 0 - # Dependency scripts and the build run in this job; only Record build gets a token. - # persist-credentials: false would clean up via `git submodule foreach`, which fails on .repos gitlinks. + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - git config --local --unset-all http.https://github.com/.extraheader || true - { git config --local --name-only --get-regexp '^includeif\.' || true; } | while read -r key; do - path=$(git config --local --get "$key") - git config --local --unset-all "$key" - case "$path" in "$RUNNER_TEMP"/*) rm -f "$path" ;; esac - done - if git config --local --get-regexp '^(http\..*\.extraheader|includeif\.)'; then - echo "::error::Checkout credentials are still configured" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials # A queued run can follow a build of the same fingerprint; manual runs always build. - id: record @@ -529,111 +495,22 @@ jobs: echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" fi - - name: Prepare build directories - if: steps.record.outputs.built != 'true' - run: | - cache="$HOME/.cache/t3-android-store" - { - echo "GRADLE_USER_HOME=$cache/gradle" - echo "CCACHE_DIR=$cache/ccache" - echo "CCACHE_MAXSIZE=5G" - # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. - echo "CCACHE_COMPILERCHECK=%compiler% -v" - echo "pnpm_config_store_dir=$cache/pnpm-store" - # eas build --local copies the project here. A fixed path keeps - # ccache keys stable, and the same disk as the store lets pnpm hardlink. - echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" - echo "CCACHE_BASEDIR=$cache/eas-build" - # CMake (3.17+) reads these, and AGP passes Gradle's environment through. - echo "CMAKE_C_COMPILER_LAUNCHER=ccache" - echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" - } >> "$GITHUB_ENV" - - - name: Mount build cache - if: steps.record.outputs.built != 'true' - uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 - with: - key: ${{ github.repository }}-android-store-build - path: ~/.cache/t3-android-store - - - name: Configure Gradle and ccache - if: steps.record.outputs.built != 'true' - run: | - mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" - rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" - # No daemon: nothing should hold the sticky disk open when it is committed. - printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" - sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources - sudo apt-get update -qq && sudo apt-get install -y -qq ccache - ccache --zero-stats - - - name: Setup Node - if: steps.record.outputs.built != 'true' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - # EAS commands load app.config.ts, whose plugins must resolve. Keep install - # scripts: some download native assets that the build's fingerprint check hashes. - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... - - - name: Setup Java - if: steps.record.outputs.built != 'true' - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 17 - - - name: Setup EAS + - name: Build if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + uses: ./.github/actions/eas-local-build with: - eas-version: latest - token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - packager: npm - - - name: Pull production environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: | - eas env:pull production --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (!googleServicesFile) { - throw new Error("T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the production environment"); - } - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - NODE - - - name: Build + platform: android + profile: production + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.aab + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - name: Check ABIs if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - env: - # EAS secret variables don't reach local builds; the eas-build-on-success - # hook needs these to upload the bundle's source map. - MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} run: | - eas build --local --platform android --profile production --non-interactive --output "$RUNNER_TEMP/t3code.aab" abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" - { - echo "### Android $BUILD_TAG" - echo "- ABIs: \`$abis\`" - echo '```' - ccache --show-stats - echo '```' - } >> "$GITHUB_STEP_SUMMARY" + echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then echo "::error::Expected only ARM native libraries in the AAB, found $abis" exit 1 @@ -658,30 +535,16 @@ jobs: # pushed, the next merge rebuilds with a new build number; nothing is lost. - name: Record build if: steps.record.outputs.built != 'true' - env: - GH_TOKEN: ${{ github.token }} + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + token: ${{ github.token }} + + - name: Summarize + if: steps.record.outputs.built != 'true' run: | - sha="$(git rev-parse HEAD)" - # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). - for attempt in 1 2 3; do - if gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$BUILD_TAG" >/dev/null 2>&1; then - echo "$BUILD_TAG exists." - break - fi - if gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$BUILD_TAG" -f sha="$sha" >/dev/null; then - break - fi - if [ "$attempt" = 3 ]; then - echo "::error::Submitted, but could not create $BUILD_TAG; the next merge will rebuild." - exit 1 - fi - sleep $((attempt * 15)) - done echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" - # Off unless the MOBILE_IOS_LOCAL_BUILDS repository variable is `true`; the - # production job only sets ios_build then. Xcode 27.1 matches the EAS build - # image in eas.json. # No sticky disk: it mounts ext4 and only works on Linux runners. ios: name: iOS store build @@ -708,20 +571,9 @@ jobs: ref: ${{ needs.production.outputs.ios_sha }} fetch-depth: 0 - # Dependency scripts and the build run in this job; only Record build gets a token. - # persist-credentials: false would clean up via `git submodule foreach`, which fails on .repos gitlinks. + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - git config --local --unset-all http.https://github.com/.extraheader || true - { git config --local --name-only --get-regexp '^includeif\.' || true; } | while read -r key; do - path=$(git config --local --get "$key") - git config --local --unset-all "$key" - case "$path" in "$RUNNER_TEMP"/*) rm -f "$path" ;; esac - done - if git config --local --get-regexp '^(http\..*\.extraheader|includeif\.)'; then - echo "::error::Checkout credentials are still configured" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials # A queued run can follow a build of the same fingerprint; manual runs always build. - id: record @@ -734,78 +586,16 @@ jobs: echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" fi - - name: Select Xcode 27.1 - if: steps.record.outputs.built != 'true' - run: | - xcode=/Applications/Xcode_27.1.app - if [ ! -d "$xcode" ]; then - ls -d /Applications/Xcode*.app - echo "::error::Xcode 27.1 is not on this runner." - exit 1 - fi - sudo xcode-select -s "$xcode/Contents/Developer" - xcodebuild -version - echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" - - # EAS's credentials step fails to import the distribution certificate without it. - - name: Install Apple WWDR G3 intermediate - if: steps.record.outputs.built != 'true' - run: | - curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer - sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true - security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep -m1 labl - - - name: Setup Node - if: steps.record.outputs.built != 'true' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - # EAS commands load app.config.ts, whose plugins must resolve. Keep install - # scripts: some download native assets that the build's fingerprint check hashes. - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... - - - name: Setup EAS - if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 - with: - eas-version: latest - token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - packager: npm - - - name: Build tools - if: steps.record.outputs.built != 'true' - run: | - command -v pod || sudo gem install cocoapods --no-document - command -v fastlane || brew install fastlane - pod --version - fastlane --version | tail -1 - - - name: Pull production environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas env:pull production --non-interactive - - name: Build if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - env: - # EAS secret variables don't reach local builds; the eas-build-on-success - # hook needs these to upload the bundle's source map. - MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - run: | - # A real path: /var -> /private/var symlinks break the expo-widgets bundle step. - export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" - eas build --local --platform ios --profile "$PROFILE" --non-interactive --output "$RUNNER_TEMP/t3code.ipa" + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: ${{ env.PROFILE }} + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.ipa + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - name: Submit to App Store Connect if: steps.record.outputs.built != 'true' @@ -816,23 +606,12 @@ jobs: # pushed, the next merge rebuilds with a new build number; nothing is lost. - name: Record build if: steps.record.outputs.built != 'true' - env: - GH_TOKEN: ${{ github.token }} + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + token: ${{ github.token }} + + - name: Summarize + if: steps.record.outputs.built != 'true' run: | - sha="$(git rev-parse HEAD)" - # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). - for attempt in 1 2 3; do - if gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$BUILD_TAG" >/dev/null 2>&1; then - echo "$BUILD_TAG exists." - break - fi - if gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$BUILD_TAG" -f sha="$sha" >/dev/null; then - break - fi - if [ "$attempt" = 3 ]; then - echo "::error::Submitted, but could not create $BUILD_TAG; the next merge will rebuild." - exit 1 - fi - sleep $((attempt * 15)) - done echo ":rocket: ios: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/AGENTS.md b/AGENTS.md index 7c9930fdb51a4..295aa96ea41ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ The most common defect in this repo is a change that works on the path you teste - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. - **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real. +- **Languages.** User-facing text ships in every locale: translate new keys in `apps/{web,mobile}/src/i18n/translations` after `vp run i18n:generate` (`vp run i18n:check` gates it) and in `apps/marketing/src/i18n`. - **Docs.** Check whether the change makes existing guidance inaccurate. Apply the [documentation rules](#documentation) before adding anything. ## Dev servers diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 97554fd823205..0daa6f14cf5c4 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.9", + "version": "0.1.10", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index aca3b4fc7fe66..9cc3a187e83f3 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -54,6 +55,7 @@ import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts"; import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts"; import * as DesktopIpc from "../ipc/DesktopIpc.ts"; @@ -72,6 +74,179 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as PreviewManager from "../preview/Manager.ts"; +interface StubbedDesktop { + readonly localEnvironmentEnabled: boolean; + readonly environment: Partial; + readonly fileSystem: Layer.Layer; + readonly record: (event: string) => Effect.Effect; + readonly windowStarted: Deferred.Deferred; + readonly registerLinuxUrlHandler: Effect.Effect; + readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; + readonly flushRendererHistory?: Effect.Effect; + readonly tokenRequested?: Deferred.Deferred; +} + +const runStubbedDesktop = (stub: StubbedDesktop) => + Effect.gen(function* () { + const quitting = yield* Ref.make(false); + const runApp = DesktopApp.program + .pipe( + Effect.provide(NodeCrypto.layer), + Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { + resolveUserDataPath: Effect.succeed("/isolated/userdata"), + configure: stub.record("identity"), + } as DesktopAppIdentity.DesktopAppIdentity["Service"]), + Effect.provideService(ElectronApp.ElectronApp, { + setPath: () => Effect.void, + whenReady: stub.record("ready"), + } as unknown as ElectronApp.ElectronApp["Service"]), + Effect.provideService(ElectronDialog.ElectronDialog, { + showErrorBox: () => Effect.die("unexpected fatal startup error"), + } as unknown as ElectronDialog.ElectronDialog["Service"]), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + platform: "linux", + isDevelopment: false, + isPackaged: true, + stateDir: "/isolated/userdata", + configuredBackendPort: Option.some(3773), + defaultDesktopSettings: { serverExposureMode: "local-only" }, + ...stub.environment, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { + linux: null, + linuxPasswordStoreCommandLine: "basic", + }), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), + updates: Stream.empty, + }), + Effect.provideService(DesktopAppSettings.DesktopAppSettings, { + load: Effect.void, + get: Effect.succeed({ + localEnvironmentEnabled: stub.localEnvironmentEnabled, + serverExposureMode: "local-only", + }), + } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), + Effect.provideService(DesktopLifecycle.DesktopLifecycle, { + register: Effect.void, + relaunch: () => Effect.void, + }), + Effect.provideService(DesktopClerk.DesktopClerk, { + configure: Effect.void, + } as DesktopClerk.DesktopClerk["Service"]), + Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { + selectedStorageBackend: Effect.succeedNone, + } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), + Effect.provideService(PreviewPasskeys.PreviewPasskeys, { + configure: Effect.void, + } as PreviewPasskeys.PreviewPasskeys["Service"]), + Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { + configure: stub.record("menu"), + }), + Effect.provideService(DesktopUpdates.DesktopUpdates, { + configure: Effect.void, + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { + register: stub.registerLinuxUrlHandler, + }), + ) + .pipe( + Effect.provideService(ElectronProtocol.ElectronProtocol, { + registerDesktopProtocol: () => Effect.void, + } as unknown as ElectronProtocol.ElectronProtocol["Service"]), + Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { + load: () => Effect.void, + } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), + Effect.provideService(DesktopSnapShot.DesktopSnapShot, { + initialize: Effect.void, + } as DesktopSnapShot.DesktopSnapShot["Service"]), + Effect.provideService(DesktopState.DesktopState, { + quitting, + } as DesktopState.DesktopState["Service"]), + Effect.provideService(DesktopWindow.DesktopWindow, { + ensureMain: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + createMainIfBackendReady: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + Effect.provideService(DesktopBackendPool.DesktopBackendPool, { + primary: Effect.succeed({ + start: stub.record("backend"), + currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), + }), + list: Effect.succeed(stub.backends ?? []), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Effect.provideService(DesktopServerExposure.DesktopServerExposure, { + configureFromSettings: () => Effect.succeed({ mode: "local-only" }), + backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), + } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), + Effect.provideService(DesktopWslBackend.DesktopWslBackend, { + reconcile: Effect.void, + } as DesktopWslBackend.DesktopWslBackend["Service"]), + Effect.provideService(DesktopAppActivation.DesktopAppActivation, { + start: Effect.void, + } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), + Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { + shutdown: stub.flushRendererHistory ?? Effect.void, + } as DesktopRendererHistory.DesktopRendererHistory["Service"]), + ); + return yield* runApp.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), + Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), + Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), + Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), + Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), + Layer.mock(DesktopIpc.DesktopIpc, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { + getBearerToken: stub + .record("token") + .pipe( + Effect.andThen( + stub.tokenRequested + ? Deferred.succeed(stub.tokenRequested, undefined) + : Effect.void, + ), + Effect.as("token"), + ), + }), + Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), + Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), + Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), + Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), + Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), + Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), + Layer.mock(ElectronMenu.ElectronMenu, {}), + Layer.mock(ElectronShell.ElectronShell, {}), + Layer.mock(ElectronTheme.ElectronTheme, {}), + Layer.mock(ElectronWindow.ElectronWindow, {}), + Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(PreviewManager.PreviewManager, { + isBrowserPartition: () => { + throw new Error("unexpected browser partition lookup"); + }, + }), + stub.fileSystem, + Layer.mock(NetService.NetService, {}), + Path.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ), + Effect.forkScoped, + ); + }); + it.effect.each([false, true])( "stops backends together before flushing history and cancels Linux registration, stop defect=%s", (stopDefect) => @@ -85,178 +260,42 @@ it.effect.each([false, true])( const releaseStops = yield* Deferred.make(); const historyStarted = yield* Deferred.make(); const releaseHistory = yield* Deferred.make(); - const quitting = yield* Ref.make(false); const tokenRequested = yield* Deferred.make(); const events: string[] = []; - const record = (event: string) => - Effect.sync(() => { - events.push(event); - }); - const runApp = DesktopApp.program - .pipe( - Effect.provide(NodeCrypto.layer), - Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { - resolveUserDataPath: Effect.succeed("/isolated/userdata"), - configure: record("identity"), - } as DesktopAppIdentity.DesktopAppIdentity["Service"]), - Effect.provideService(ElectronApp.ElectronApp, { - setPath: () => Effect.void, - whenReady: record("ready"), - } as unknown as ElectronApp.ElectronApp["Service"]), - Effect.provideService(ElectronDialog.ElectronDialog, { - showErrorBox: () => Effect.die("unexpected fatal startup error"), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - Effect.provideService(DesktopEnvironment.DesktopEnvironment, { - platform: "linux", - isDevelopment: false, - isPackaged: true, - stateDir: "/isolated/userdata", - configuredBackendPort: Option.some(3773), - defaultDesktopSettings: { serverExposureMode: "local-only" }, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { - linux: null, - linuxPasswordStoreCommandLine: "basic", - }), - Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { - installIntoProcess: Effect.succeed(true), - awaitDiscovery: Effect.succeed(true), - awaitUserShellDiscovery: Effect.succeed(true), - updates: Stream.empty, + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: true, + environment: {}, + fileSystem: FileSystem.layerNoop({}), + record: (event) => + Effect.sync(() => { + events.push(event); }), - Effect.provideService(DesktopAppSettings.DesktopAppSettings, { - load: Effect.void, - get: Effect.succeed({ - localEnvironmentEnabled: true, - serverExposureMode: "local-only", - }), - } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), - Effect.provideService(DesktopLifecycle.DesktopLifecycle, { - register: Effect.void, - relaunch: () => Effect.void, - }), - Effect.provideService(DesktopClerk.DesktopClerk, { - configure: Effect.void, - } as DesktopClerk.DesktopClerk["Service"]), - Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { - selectedStorageBackend: Effect.succeedNone, - } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), - Effect.provideService(PreviewPasskeys.PreviewPasskeys, { - configure: Effect.void, - } as PreviewPasskeys.PreviewPasskeys["Service"]), - Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { - configure: record("menu"), - }), - Effect.provideService(DesktopUpdates.DesktopUpdates, { - configure: Effect.void, - } as unknown as DesktopUpdates.DesktopUpdates["Service"]), - Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { - register: Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), - ), - }), - ) - .pipe( - Effect.provideService(ElectronProtocol.ElectronProtocol, { - registerDesktopProtocol: () => Effect.void, - } as unknown as ElectronProtocol.ElectronProtocol["Service"]), - Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { - load: () => Effect.void, - } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), - Effect.provideService(DesktopSnapShot.DesktopSnapShot, { - initialize: Effect.void, - } as DesktopSnapShot.DesktopSnapShot["Service"]), - Effect.provideService(DesktopState.DesktopState, { - quitting, - } as DesktopState.DesktopState["Service"]), - Effect.provideService(DesktopWindow.DesktopWindow, { - ensureMain: record("window").pipe( - Effect.andThen(Deferred.succeed(windowStarted, undefined)), - ), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Effect.provideService(DesktopBackendPool.DesktopBackendPool, { - primary: Effect.succeed({ - start: record("backend"), - currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), - }), - list: Effect.succeed([ - { - stop: () => - Deferred.succeed(firstStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), - ), - }, - { - stop: () => - Deferred.succeed(secondStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - ), - }, - ]), - } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), - Effect.provideService(DesktopServerExposure.DesktopServerExposure, { - configureFromSettings: () => Effect.succeed({ mode: "local-only" }), - backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), - } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), - Effect.provideService(DesktopWslBackend.DesktopWslBackend, { - reconcile: Effect.void, - } as DesktopWslBackend.DesktopWslBackend["Service"]), - Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, - } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), - Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { - shutdown: Deferred.succeed(historyStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseHistory)), - Effect.asVoid, - ), - } as DesktopRendererHistory.DesktopRendererHistory["Service"]), - ); - const app = yield* runApp.pipe( - Effect.provide( - Layer.mergeAll( - Layer.mock(BrowserImport.BrowserImport, {}), - Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), - Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), - Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), - Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), - Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), - Layer.mock(DesktopIpc.DesktopIpc, {}), - Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { - getBearerToken: record("token").pipe( - Effect.andThen(Deferred.succeed(tokenRequested, undefined)), - Effect.as("token"), + windowStarted, + tokenRequested, + registerLinuxUrlHandler: Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRegistration)), + Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), + ), + backends: [ + { + stop: () => + Deferred.succeed(firstStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), ), - }), - Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), - Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), - Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), - Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), - Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), - Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), - Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), - Layer.mock(ElectronMenu.ElectronMenu, {}), - Layer.mock(ElectronShell.ElectronShell, {}), - Layer.mock(ElectronTheme.ElectronTheme, {}), - Layer.mock(ElectronWindow.ElectronWindow, {}), - Layer.mock(MacPermissions.MacPermissions, {}), - Layer.mock(PreviewManager.PreviewManager, { - isBrowserPartition: () => { - throw new Error("unexpected browser partition lookup"); - }, - }), - FileSystem.layerNoop({}), - Layer.mock(NetService.NetService, {}), - Path.layer, - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), - ), - ), + }, + { + stop: () => + Deferred.succeed(secondStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + ), + }, + ], + flushRendererHistory: Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseHistory)), + Effect.asVoid, ), - Effect.forkScoped, - ); + }); yield* Deferred.await(registrationStarted); yield* Deferred.await(windowStarted); yield* Deferred.await(tokenRequested); @@ -283,3 +322,53 @@ it.effect.each([false, true])( assert.isTrue(yield* Deferred.isDone(registrationStopped)); }).pipe(Effect.provide(DesktopShutdown.layer)), ); + +it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ + path, + baseDir, + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), +); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index f69bf965d0058..56fe979cf8c67 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -15,6 +15,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; @@ -301,6 +302,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ); if (!settings.localEnvironmentEnabled) { + // The backend config refreshes the launcher when the local environment runs; an update may move the app. + yield* DesktopCliShim.install; if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index ab57d5db32372..565a50f193e0f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -29,6 +29,7 @@ const layerShellEnvironment = (prepared = true) => installIntoProcess: Effect.succeed(prepared), awaitDiscovery: Effect.succeed(prepared), awaitUserShellDiscovery: Effect.succeed(prepared), + discoveryFinished: Effect.succeed(true), updates: Stream.empty, }); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 60b72deb293a5..fe65edd0ee1e9 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,3 +1,4 @@ +import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; @@ -110,6 +111,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(startFileDrag); yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 9e5c7296a3a03..d8652bd199713 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -142,3 +142,5 @@ export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-stor export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; + +export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts new file mode 100644 index 0000000000000..04b75c9be98a1 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -0,0 +1,51 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { vi } from "vite-plus/test"; + +const { startDrag, getFileIcon } = vi.hoisted(() => ({ + startDrag: vi.fn(), + getFileIcon: vi.fn(async () => "file-icon"), +})); +vi.mock("electron", () => ({ app: { getFileIcon } })); + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import { startFileDrag } from "./fileDrag.ts"; + +it.effect("only drags existing absolute paths from the Mac host environment and app window", () => + Effect.gen(function* () { + startDrag.mockClear(); + getFileIcon.mockClear(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const filePath = path.join(stateDir, "file with spaces.txt"); + yield* fs.writeFileString(filePath, "file"); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), "host\n"); + const run = (environmentId: string, target: string, platform = "darwin", sender = 1) => + startFileDrag.handler({ environmentId, path: target }, { sender: { id: sender } }).pipe( + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + path, + stateDir, + platform, + } as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ); + assert.isFalse(yield* run("remote", filePath)); + assert.isFalse(yield* run("host", "relative.txt")); + assert.isFalse(yield* run("host", `${filePath}:12`)); + assert.isFalse(yield* run("host", filePath, "linux")); + assert.isFalse(yield* run("host", filePath, "darwin", 2)); + assert.strictEqual(startDrag.mock.calls.length, 0); + assert.isTrue(yield* run("host", filePath)); + assert.deepEqual(startDrag.mock.calls, [[{ file: filePath, icon: "file-icon" }]]); + yield* fs.remove(path.join(stateDir, "environment-id")); + assert.isFalse(yield* run("host", filePath)); + assert.strictEqual(startDrag.mock.calls.length, 1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts new file mode 100644 index 0000000000000..9701dfafcda32 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -0,0 +1,36 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Electron from "electron"; + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import { makeIpcMethod } from "../DesktopIpc.ts"; +import { getHostEnvironmentId } from "./localEnvironment.ts"; + +export const startFileDrag = makeIpcMethod({ + channel: IpcChannels.START_FILE_DRAG_CHANNEL, + payload: Schema.Struct({ environmentId: Schema.String, path: Schema.String }), + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin" || !environment.path.isAbsolute(input.path)) return false; + const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); + if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; + const window = yield* (yield* ElectronWindow.ElectronWindow).main; + if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(input.path))) return false; + return yield* Effect.promise(async () => { + try { + const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); + window.value.webContents.startDrag({ file: input.path, icon }); + return true; + } catch { + return false; + } + }); + }), +}); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index de202529c4113..b256025eff844 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -10,6 +10,7 @@ import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -26,6 +27,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; @@ -235,6 +237,7 @@ describe("installRelayTelemetryEnabled", () => { const relayTelemetryEnabled = ( env: NodeJS.ProcessEnv, policy?: Parameters[0], + loginShellEnv: NodeJS.ProcessEnv = {}, ) => Effect.gen(function* () { const listeners = new Map(); @@ -244,21 +247,47 @@ describe("installRelayTelemetryEnabled", () => { removeAllListeners: (channel) => void listeners.delete(channel), on: (channel, listener) => void listeners.set(channel, listener), }; + let discoveryFinished = false; + const ask = () => { + const event = { returnValue: undefined as unknown }; + listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); + return event.returnValue; + }; yield* installRelayTelemetryEnabled().pipe( Effect.provideService(HostProcess.Environment, env), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.sync(() => discoveryFinished), + updates: Stream.empty, + }), Effect.provide( Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)), ), ); - const event = { returnValue: undefined as unknown }; - listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); - return event.returnValue; + const beforeDiscovery = ask(); + // The login shell's values land in the process env after startup has installed handlers. + Object.assign(env, loginShellEnv); + discoveryFinished = true; + return { beforeDiscovery, afterDiscovery: ask() }; }).pipe(Effect.scoped); it.effect("reads the desktop host opt-out before returning the renderer policy", () => Effect.gen(function* () { - assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" })); - assert.isTrue(yield* relayTelemetryEnabled({})); + assert.deepEqual(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }), { + beforeDiscovery: false, + afterDiscovery: false, + }); + // Undecided until the login shell is read, so the renderer asks again instead of opting out. + assert.deepEqual(yield* relayTelemetryEnabled({}), { + beforeDiscovery: null, + afterDiscovery: true, + }); + assert.deepEqual( + yield* relayTelemetryEnabled({}, undefined, { T3CODE_TELEMETRY_ENABLED: "false" }), + { beforeDiscovery: null, afterDiscovery: false }, + ); }), ); @@ -269,14 +298,14 @@ describe("installRelayTelemetryEnabled", () => { organization: "Example Corp", limits, }); - assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false }))); - assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false }))); + const after = function* (...args: Parameters) { + return (yield* relayTelemetryEnabled(...args)).afterDiscovery; + }; + assert.isFalse(yield* after({}, policy({ telemetry: false }))); + assert.isTrue(yield* after({}, policy({ webhookTasks: false }))); // A policy that cannot be read fails closed. assert.isFalse( - yield* relayTelemetryEnabled( - {}, - new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }), - ), + yield* after({}, new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })), ); }), ); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 38887ec71d906..2545cb9dc5390 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -34,6 +34,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronApp from "../../electron/ElectronApp.ts"; @@ -82,22 +83,28 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ /** * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read, - * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. + * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. Until the login + * shell's environment (which may opt out) is known, answer null so the renderer asks again. */ export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")( function* () { const ipc = yield* DesktopIpc.DesktopIpc; - const enabled = - isRelayTracingEnabled(yield* HostProcess.Environment) && - (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( - Effect.map((found) => found?.document.limits?.telemetry !== false), - Effect.orElseSucceed(() => false), - )); + const env = yield* HostProcess.Environment; + const policyAllows = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( + Effect.map((found) => found?.document.limits?.telemetry !== false), + Effect.orElseSucceed(() => false), + ); + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; yield* ipc.handleSync( DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL, - result: Schema.Boolean, - handler: () => Effect.succeed(enabled), + result: Schema.NullOr(Schema.Boolean), + handler: () => + shellEnvironment.discoveryFinished.pipe( + Effect.map((known) => + !policyAllows || !isRelayTracingEnabled(env) ? false : known ? true : null, + ), + ), }), ); }, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 432577917a3ea..564ada478ff9a 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -16,14 +16,11 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Electron from "electron"; import * as NetService from "@t3tools/shared/Net"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel"; -import serverPackageJson from "../../server/package.json" with { type: "json" }; import * as DesktopIpc from "./ipc/DesktopIpc.ts"; import * as ElectronApp from "./electron/ElectronApp.ts"; @@ -109,24 +106,15 @@ const layerDesktopEnvironment = Layer.unwrap( }), ); -const resolveDesktopSshCliRunner = ( - environment: DesktopEnvironment.DesktopEnvironment["Service"], -): RemoteT3RunnerOptions => { - const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); - if (environment.isDevelopment && devRemoteEntryPath !== undefined) { - return { - nodeScriptPath: devRemoteEntryPath, - nodeEngineRange: serverPackageJson.engines.node, - }; - } - return { archiveVersion: environment.appVersion }; -}; - const layerDesktopSshEnvironment = Layer.unwrap( Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; + const env = yield* HostProcess.Environment; return DesktopSshEnvironment.layer({ - resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)), + // Per connect: the login shell's environment is installed after this layer is built. + resolveCliRunner: Effect.sync(() => + DesktopSshEnvironment.resolveDesktopSshCliRunner(environment, env), + ), resolveLauncherId: yield* Effect.cached( DesktopSshEnvironment.readOrCreateLauncherId( environment.path.join(environment.stateDir, "ssh-launcher-id"), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ba9c17aae2695..b4b15f6a7a4eb 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -111,8 +111,10 @@ contextBridge.exposeInMainWorld("desktopBridge", { } return result as ReturnType; }, - getRelayTelemetryEnabled: () => - ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true, + getRelayTelemetryEnabled: () => { + const enabled = ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL); + return enabled === null ? null : enabled === true; + }, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), @@ -255,6 +257,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), + 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), checkSystemPermission: (pane: string) => diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 7808682dfd82b..f082020a5dec1 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -355,6 +355,7 @@ describe("DesktopShellEnvironment", () => { NODE_EXTRA_CA_CERTS: "/cached/ca.pem", SSL_CERT_FILE: "/cached/cert.pem", SSL_CERT_DIR: "/cached/certs", + T3CODE_TELEMETRY_ENABLED: "false", SSH_AUTH_SOCK: "/stale.sock", NODE_OPTIONS: "--bad", }, @@ -394,6 +395,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); assert.equal(env.SSL_CERT_FILE, ""); assert.equal(env.SSL_CERT_DIR, "/cached/certs"); + assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false"); assert.equal(env.SSH_AUTH_SOCK, "/current.sock"); assert.isUndefined(env.NODE_OPTIONS); assert.equal(yield* fs.readFileString(cachePath), contents); @@ -711,6 +713,8 @@ describe("DesktopShellEnvironment", () => { Effect.gen(function* () { assert.isTrue(yield* service.awaitDiscovery); assert.equal(env.PATH, "/usr/bin"); + // The user's shell may still opt out of telemetry, so discovery has not settled. + assert.isFalse(yield* service.discoveryFinished); // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await. const published = yield* service.updates.pipe( Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"), diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 351150aa4b987..6d84b87e6fcc6 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -6,6 +6,7 @@ import { mergePathValues, readUserLoginShell, setWindowsPath, + windowsEnvironmentValueCommand, } from "@t3tools/shared/shell"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; @@ -92,6 +93,8 @@ export class DesktopShellEnvironment extends Context.Service< readonly awaitDiscovery: Effect.Effect; /** Whether the user's own login shell, not a fallback, gave the PATH a new terminal gets. */ readonly awaitUserShellDiscovery: Effect.Effect; + /** Whether discovery has settled (the user's shell answered or retries ran out), without waiting. */ + readonly discoveryFinished: Effect.Effect; readonly updates: Stream.Stream; } >()("@t3tools/desktop/shell/DesktopShellEnvironment") {} @@ -121,6 +124,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", ] as const; @@ -232,7 +236,7 @@ const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, - `$value = [Environment]::GetEnvironmentVariable('${name}')`, + windowsEnvironmentValueCommand(name), "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }", `Write-Output '${endMarker(name)}'`, ]; @@ -547,6 +551,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { config.env[name] = shellEnvironment[name]; @@ -650,6 +655,7 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", + "T3CODE_TELEMETRY_ENABLED", ] as const; /** @public */ @@ -671,6 +677,7 @@ export const make = Effect.gen(function* () { const changes = yield* PubSub.unbounded(); const latest = yield* Ref.make>(Option.none()); const discovered = yield* Deferred.make(); + const settledDiscovery = yield* Deferred.make(); const publish = Effect.fn("desktop.shellEnvironment.publish")(function* ( patch: ShellEnvironmentPatch, discovered = false, @@ -740,6 +747,7 @@ export const make = Effect.gen(function* () { ), ), ), + Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)), ); const installIntoProcess = yield* Effect.cached( Effect.gen(function* () { @@ -795,6 +803,7 @@ export const make = Effect.gen(function* () { Effect.andThen(Deferred.await(discovered)), Effect.map(({ fromUserShell }) => fromUserShell), ), + discoveryFinished: Deferred.isDone(settledDiscovery), updates, }); }); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts new file mode 100644 index 0000000000000..b94958a633156 --- /dev/null +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts @@ -0,0 +1,47 @@ +import * as NodePath from "@effect/platform-node/NodePath"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as DesktopConfig from "../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { resolveDesktopSshCliRunner } from "./DesktopSshEnvironment.ts"; + +const packagedEnvironment = DesktopEnvironment.DesktopEnvironment.pipe( + Effect.provide( + DesktopEnvironment.layer({ + dirname: "/Applications/T3 Code.app/Contents/Resources/app.asar/dist-electron", + homeDirectory: "/Users/alice", + platform: "darwin", + processArch: "arm64", + appVersion: "0.0.22", + appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar", + isPackaged: true, + resourcesPath: "/Applications/T3 Code.app/Contents/Resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(NodeServices.layer, NodePath.layerPosix, DesktopConfig.layerTest({})), + ), + ), + ), +); + +describe("resolveDesktopSshCliRunner", () => { + it.effect("downloads the remote runner from the release mirror", () => + Effect.gen(function* () { + const environment = yield* packagedEnvironment; + + const runner = resolveDesktopSshCliRunner(environment, { + [CLI_RELEASE_BASE_URL_ENV]: "https://mirror.example.com/t3code", + }); + + assert.deepStrictEqual(runner, { + archiveVersion: "0.0.22", + releaseBaseUrl: "https://mirror.example.com/t3code", + }); + }), + ); +}); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 0693c16cc15fd..fd749b663cd2d 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -3,6 +3,7 @@ import type { DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentTarget, } from "@t3tools/contracts"; +import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as NetService from "@t3tools/shared/Net"; import * as SshAuth from "@t3tools/ssh/auth"; import { resolveSshTarget } from "@t3tools/ssh/command"; @@ -27,6 +28,10 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as Option from "effect/Option"; +import serverPackageJson from "../../../server/package.json" with { type: "json" }; + +import type * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; @@ -74,6 +79,24 @@ export interface DesktopSshEnvironmentLayerOptions { readonly resolveLauncherId?: Effect.Effect; } +export const resolveDesktopSshCliRunner = ( + environment: DesktopEnvironment.DesktopEnvironment["Service"], + env: NodeJS.ProcessEnv, +): SshTunnel.RemoteT3RunnerOptions => { + const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); + if (environment.isDevelopment && devRemoteEntryPath !== undefined) { + return { + nodeScriptPath: devRemoteEntryPath, + nodeEngineRange: serverPackageJson.engines.node, + }; + } + const releaseBaseUrl = env[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined; + return { + archiveVersion: environment.appVersion, + ...(releaseBaseUrl === undefined ? {} : { releaseBaseUrl }), + }; +}; + // Remote servers record this ID as their owner, so it has to outlive restarts, // updates and edits to a saved connection. Without a stored one there is none. export const readOrCreateLauncherId = Effect.fn("desktop.ssh.readOrCreateLauncherId")( diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index e2bfabe32762c..3b0582e8131b7 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -93,6 +93,7 @@ describe("DesktopTelemetryPublisher", () => { installIntoProcess: Effect.succeed(true), awaitDiscovery: Effect.succeed(true), awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), updates: Stream.make({ version: 1, type: "shellEnvironment", diff --git a/apps/mobile/assets/icons/issue.png b/apps/mobile/assets/icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/assets/icons/issue.png differ diff --git a/apps/mobile/assets/icons/issue@2x.png b/apps/mobile/assets/icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/assets/icons/issue@2x.png differ diff --git a/apps/mobile/assets/icons/issue@3x.png b/apps/mobile/assets/icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/assets/icons/issue@3x.png differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.57.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.57.tgz deleted file mode 100644 index 0ea560bd32ef1..0000000000000 Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.57.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz new file mode 100644 index 0000000000000..06f9fc0fa91b9 Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz differ diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 9367ade408e95..756c69e52176b 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -8,6 +8,8 @@ import "react-native-gesture-handler"; import { LogBox } from "react-native"; import { featureFlags } from "react-native-screens"; +// Before any GT module initializes: GT validates locales with Intl APIs that Hermes lacks. +import "./src/i18n/intl-polyfills"; import App from "./src/App"; // Enables iOS FormSheet sizing for nested native stacks in non-fitToContents sheets. diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 736f7cd3019f0..1208f3176935d 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -126,7 +126,7 @@ class T3WorkspaceNavigationView( private val onTabSelected by EventDispatcher() private val onNewThread by EventDispatcher() private val onOverlayChange by EventDispatcher() - var tabs by mutableStateOf(listOf("threads", "pullRequests", "usage", "settings")) + var tabs by mutableStateOf(listOf("threads", "pullRequests", "issues", "usage", "settings")) var selectedTab by mutableStateOf("threads") var rail by mutableStateOf(false) var floating by mutableStateOf(false) @@ -415,6 +415,7 @@ class T3WorkspaceNavigationView( private fun tabTitle(tab: String) = when (tab) { "threads" -> "Chats" "pullRequests" -> "Pulls" + "issues" -> "Issues" "usage" -> "Usage" else -> "Settings" } @@ -427,6 +428,7 @@ class T3WorkspaceNavigationView( when (tab) { "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests + "issues" -> R.drawable.t3_issues "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml new file mode 100644 index 0000000000000..14de69947215f --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec index c32f88b0dacb3..ed5fd7f091dba 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec @@ -15,6 +15,6 @@ Pod::Spec.new do |s| s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', } - s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] } + s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png', 'Resources/Icons/issue*.png'] } s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' end diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift index 6732f2dae2f18..065eba4331036 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift @@ -20,6 +20,10 @@ final class T3ScrollEdgeBleedView: ExpoView { /// React Native's clipping, saved while bleeding. React Native only rewrites it when the /// `overflow` style changes, so it stays off while bleeding. private var containerClipped: Bool? + /// The bar's side is read from the root view controller, whose traits can settle after this + /// view's own during a fold; with no size change after that, nothing else would recheck. + private weak var observedWindow: UIWindow? + private var windowTraitRegistration: (any UITraitChangeRegistration)? required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -38,9 +42,33 @@ final class T3ScrollEdgeBleedView: ExpoView { override func didMoveToWindow() { super.didMoveToWindow() + observeWindowTraits() if window == nil { detach() } else { setNeedsLayout() } } + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + setNeedsLayout() + } + + private func observeWindowTraits() { + guard observedWindow !== window else { return } + if let observedWindow, let windowTraitRegistration { + observedWindow.unregisterForTraitChanges(windowTraitRegistration) + } + observedWindow = window + windowTraitRegistration = nil + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), let window { + windowTraitRegistration = window.registerForTraitChanges( + UITraitCollection.systemTraitsAffectingVerticalBarEdge + ) { [weak self] (_: UIWindow, _: UITraitCollection) in + self?.setNeedsLayout() + } + } + #endif + } + override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) setNeedsLayout() diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 78fd2ec1fe379..9df738d37fa67 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -40,7 +40,7 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private let composeButton = UIButton(type: .system) private lazy var tabBarTrailing = tabBar.trailingAnchor.constraint(equalTo: trailingAnchor) private var itemsByTab: [String: UITabBarItem] = [:] - var tabs = ["threads", "pullRequests", "usage", "settings"] { + var tabs = ["threads", "pullRequests", "issues", "usage", "settings"] { didSet { if tabs != oldValue { updateItems() } } } var selectedTab = "threads" { didSet { updateSelection() } } @@ -109,10 +109,11 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "usage": "Usage", "settings": "Settings"] + let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"] + let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] for (tab, label) in labels { - let icon = tab == "pullRequests" ? pullRequestIcon : UIImage(systemName: symbols[tab] ?? "circle") + let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) item.accessibilityLabel = label item.accessibilityIdentifier = "workspace-tab-\(tab)" diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png new file mode 100644 index 0000000000000..1e55bbd87a57f Binary files /dev/null and b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png differ diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml new file mode 100644 index 0000000000000..8125e99ad560e --- /dev/null +++ b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml @@ -0,0 +1,4 @@ + + diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 2b64c26759cf2..9ce17bea845de 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -135,7 +135,7 @@ "react-native-pdf-jsi": "6.1.0", "react-native-reanimated": "4.7.1", "react-native-safe-area-context": "~5.11.1", - "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.57.tgz", + "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.58.tgz", "react-native-svg": "15.16.1", "react-native-webview": "14.0.1", "react-native-worklets": "0.13.1", diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index fcdd4bc19a4c0..25e30320799d9 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -37,6 +37,11 @@ import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequest import { PullRequestLabelsScreen } from "./features/pull-requests/PullRequestLabelsScreen"; import { PullRequestEditScreen } from "./features/pull-requests/PullRequestEditScreen"; import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen"; +import { IssueAssigneesScreen } from "./features/issues/IssueAssigneesScreen"; +import { IssueEditScreen } from "./features/issues/IssueEditScreen"; +import { IssueLabelsScreen } from "./features/issues/IssueLabelsScreen"; +import { IssueFilterSearchScreen } from "./features/issues/IssueFilterSearchScreen"; +import { IssueRouteScreen } from "./features/issues/IssueRouteScreen"; import { RenderErrorBoundary, RenderFailureView, @@ -99,6 +104,10 @@ import { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsD import { SettingsProviderAccountsRouteScreen } from "./features/settings/SettingsProviderAccountsRouteScreen"; import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen"; import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; +import { + SettingsIssueTrackerRouteScreen, + SettingsSourceControlProviderRouteScreen, +} from "./features/settings/SettingsSourceControlDetailRouteScreens"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; @@ -191,7 +200,15 @@ const SETTINGS_SCREENS = { SettingsEnvironmentSourceControl: createNativeStackScreen({ screen: SettingsEnvironmentSourceControlRouteScreen, linking: "settings/source-control", - options: settingsPage("Source control"), + options: settingsPage("Source control & issues"), + }), + SettingsSourceControlProvider: createNativeStackScreen({ + screen: SettingsSourceControlProviderRouteScreen, + options: settingsPage("Provider"), + }), + SettingsIssueTracker: createNativeStackScreen({ + screen: SettingsIssueTrackerRouteScreen, + options: settingsPage("Issue tracker"), }), SettingsEnvironmentAgentBehavior: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, @@ -570,6 +587,27 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestEditScreen, options: sheetRoute({ detent: 0.75, androidFit: true }), }), + Issue: createNativeStackScreen({ + screen: IssueRouteScreen, + linking: "issues/:environmentId/:projectId/:tracker/:scope/:issueKey", + options: pageRoute({ duoMinimize: "never" }), + }), + IssueEdit: createNativeStackScreen({ + screen: IssueEditScreen, + options: sheetRoute({ detent: 0.75, androidFit: true }), + }), + IssueLabels: createNativeStackScreen({ + screen: IssueLabelsScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueAssignees: createNativeStackScreen({ + screen: IssueAssigneesScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueFilterSearch: createNativeStackScreen({ + screen: IssueFilterSearchScreen, + options: SEARCH_SHEET_ROUTE, + }), Thread: createNativeStackScreen({ screen: ThreadRouteScreen, linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] }, diff --git a/apps/mobile/src/components/ComposerSurface.tsx b/apps/mobile/src/components/ComposerSurface.tsx new file mode 100644 index 0000000000000..7cabdfd5faa92 --- /dev/null +++ b/apps/mobile/src/components/ComposerSurface.tsx @@ -0,0 +1,283 @@ +import { useState, type ReactNode } from "react"; +import { I18nManager, Platform, type ViewStyle } from "react-native"; +import Animated, { + FadeIn, + type LayoutAnimationFunction, + ReduceMotion, + useAnimatedStyle, + useDerivedValue, + useSharedValue, + withTiming, +} from "react-native-reanimated"; + +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout"; +import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar"; +import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider"; +import { compactEditorInsets } from "../features/threads/compactEditorInsets"; +import { + useDeviceType, + useDuoBottomBarInset, + useNativeLayoutMetrics, +} from "../native/native-layout-metrics"; +import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; +import { MOBILE_TYPOGRAPHY } from "../lib/typography"; +import { useUniwindTheme } from "../lib/useUniwindTheme"; +import { GlassSurface } from "./ui/GlassSurface"; + +const COLLAPSED_EDITOR_DEFAULT_INSET = 6; +// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is +// descender (0.31em) + half x-height (0.504em) above the line bottom. +const LOWERCASE_MIDLINE_EM = 0.562; + +function lowercaseMidline(text: ScaledTextRole): number { + return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize; +} + +function collapsedEditorInset(text: ScaledTextRole): number { + const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body); + return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); +} + +const EXPANDED_EDITOR_INSET = 14; +// Room under the expanded editor for the toolbar row. +const EXPANDED_EDITOR_BOTTOM = 52; + +export function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) { + const [contentSize, setContentSize] = useState({ width: 0, height: 0 }); + const [compactWidth, setCompactWidth] = useState(0); + const contentHeight = contentSize.height; + const rowWidth = useSharedValue(0); + const editorX = useSharedValue(0); + const editorWidth = useSharedValue(0); + const inset = + Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text); + const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset); + const height = Math.max( + minimum, + Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset), + ); + // A line that fits the expanded editor may still overflow its compact slot. + // Compare its measured width too so widening cannot trigger a collapse loop. + const isExpanded = + value.length > 0 && + (contentHeight > text.lineHeight * 1.5 || + (compactWidth > 0 && contentSize.width > compactWidth)); + const compactRowHeight = Math.max(44, minimum); + const compactBottom = (compactRowHeight - minimum) / 2; + const isRTL = I18nManager.isRTL; + const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM; + const expansion = useDerivedValue(() => { + const target = isExpanded ? 1 : 0; + return animate + ? withTiming(target, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : target; + }); + const editorStyle = useAnimatedStyle(() => { + const compactInsets = compactEditorInsets({ + slotX: editorX.value, + slotWidth: editorWidth.value, + rowWidth: rowWidth.value, + isRTL, + }); + const progress = expansion.value; + // Hanging from the row top lets the text ride the growing edge and ignore the stale + // height measured while it still wrapped in the compact slot. Layout props only: + // Reanimated applies transforms frames ahead of layout, which tore the text from its frame. + return { + position: "absolute", + overflow: "hidden", + // The compact slot is unknown until its first layout, so the editor would draw over the + button. + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0, + height, + top: compactBottom * (1 - progress), + left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress, + // Snapping the far edge keeps the line from rewrapping while the near edge moves. + right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right, + }; + }); + const containerStyle = useAnimatedStyle(() => ({ + height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value, + })); + return { + isExpanded, + containerStyle, + // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted. + // An entering animation hides it from its first frame, which a shared-value opacity cannot. + toolbarControlsEntering: + animate && isExpanded + ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2) + .duration(COMPOSER_TRANSITION_DURATION_MS / 2) + .reduceMotion(ReduceMotion.System) + : undefined, + editorStyle, + onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => { + rowWidth.set(event.nativeEvent.layout.width); + }, + onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => { + // The expanded toolbar gives this slot to the model control. Keep the + // compact geometry for the return transition, rather than recording zero. + if (!isExpanded) { + editorX.set(event.nativeEvent.layout.x); + editorWidth.set(event.nativeEvent.layout.width); + setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8)); + } + }, + editorProps: { + singleLineCentered: !isExpanded, + scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4, + contentInsetVertical: inset, + onContentSizeChange: (size: { width: number; height: number }) => { + setContentSize(size); + }, + style: { flex: 1 }, + }, + }; +} + +export const COMPOSER_TRANSITION_DURATION_MS = 220; +// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar. +const composerHeightTransition: LayoutAnimationFunction = (values) => { + "worklet"; + const timing = { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }; + return { + initialValues: { + originX: values.targetOriginX, + originY: values.currentOriginY, + width: values.targetWidth, + height: values.currentHeight, + }, + animations: { + originX: values.targetOriginX, + originY: withTiming(values.targetOriginY, timing), + width: values.targetWidth, + height: withTiming(values.targetHeight, timing), + }, + }; +}; +const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition; +// Share of the one-row composer the draft keeps; a long model name truncates first. +export const INLINE_EDITOR_MIN_WIDTH = "40%"; +const INLINE_EDITOR_HEIGHT = 36; + +const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface); + +export function ComposerSurface(props: { + readonly children: ReactNode; + readonly style: ViewStyle; + readonly animateLayout?: boolean; +}) { + const colors = useUniwindTheme(); + const targetBorderRadius = + typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0; + const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android"; + const animatedBorderRadius = useDerivedValue(() => + shouldAnimate + ? withTiming(targetBorderRadius, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : targetBorderRadius, + ); + const borderCurve = props.style.borderCurve; + const animatedShapeStyle = useAnimatedStyle(() => ({ + borderRadius: animatedBorderRadius.value, + ...(borderCurve ? { borderCurve } : {}), + })); + const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined; + + // Animate every native frame or glass and content jump to final height inside the clip. + return ( + + + {null} + + + {props.children} + + + ); +} + +/** Space below the composer pill, inside the bottom inset it is given. */ +export const COMPOSER_BOTTOM_GUTTER = 6; + +/** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */ +export function useComposerChrome() { + const { layout } = useAdaptiveWorkspaceLayout(); + const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView; + const sidebarWorkspaceTabs = useSidebarWorkspaceTabs(); + const deviceType = useDeviceType(); + const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad"; + return { + usesLargeControls, + controlSize: usesLargeControls ? ("large" as const) : ("regular" as const), + borderRadius: usesLargeControls ? 31 : 27, + paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2, + }; +} + +/** + * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates: + * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area. + */ +export function useComposerBottomInset() { + const insets = useSafeAreaInsets(); + const windowMetrics = useNativeLayoutMetrics(); + const { layout } = useAdaptiveWorkspaceLayout(); + const bottomBarInset = useDuoBottomBarInset(); + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker"; + // A pushed screen temporarily inherits the outgoing tab bar's safe area. + // Use the window edge so hiding that bar cannot move the composer mid-push. + const bottomSafeArea = + Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom; + // The pill already adds its own gutter; iPad and Duo align its edge with the native bar. + const alignedBottomInset = + bottomBarInset ?? + (Platform.OS === "ios" && Platform.isPad + ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0) + : undefined); + // The Duo's floating sidebar pill ends three points below the composer's usual gutter. + return Math.max( + 0, + (alignedBottomInset !== undefined + ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER + : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0), + ); +} + +/** The editor's text style: the composer's scaled role in the theme's foreground color. */ +export function useComposerTextStyle(text: ScaledTextRole) { + return { ...text, color: useUniwindTheme()["--color-foreground"] }; +} diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 4a5a16298b956..5333af3ea577a 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -1,6 +1,7 @@ import type { Icon } from "@tabler/icons-react-native/types"; /* Package-root imports eagerly register the entire Tabler icon set in Metro. */ import IconAdjustmentsHorizontal from "@tabler/icons-react-native/IconAdjustmentsHorizontal"; +import IconAlarm from "@tabler/icons-react-native/IconAlarm"; import IconAlignLeft from "@tabler/icons-react-native/IconAlignLeft"; import IconAlertCircle from "@tabler/icons-react-native/IconAlertCircle"; import IconAlertTriangle from "@tabler/icons-react-native/IconAlertTriangle"; @@ -149,6 +150,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, "arrow.branch": IconGitBranch, "arrow.left": IconArrowLeft, "arrow.right": IconArrowRight, @@ -189,6 +191,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "circle.inset.filled": IconCircleDot, "circle.dashed.inset.filled": IconCircleDot, "calendar.badge.clock": IconCalendarClock, + alarm: IconAlarm, clock: IconClock, timer: IconClock, "face.smiling": IconMoodPlus, @@ -302,6 +305,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon @@ -313,6 +317,7 @@ const SF_ICON_LOOKUP: Partial< | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx index 146a9ccb305e7..896765db5d233 100644 --- a/apps/mobile/src/components/ui/AppSymbol.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.tsx @@ -4,6 +4,7 @@ import IconGitCommit from "@tabler/icons-react-native/IconGitCommit"; import IconGitPullRequestClosed from "@tabler/icons-react-native/IconGitPullRequestClosed"; import IconGitPullRequestDraft from "@tabler/icons-react-native/IconGitPullRequestDraft"; import type { SFSymbol } from "expo-symbols"; +import IconCircleDot from "@tabler/icons-react-native/IconCircleDot"; import IconGitPullRequest from "@tabler/icons-react-native/IconGitPullRequest"; import IconFileDiff from "@tabler/icons-react-native/IconFileDiff"; import IconRobot from "@tabler/icons-react-native/IconRobot"; @@ -23,6 +24,7 @@ const CUSTOM_ICONS = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, robot: IconRobot, }; diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx index 9042893f0fc5f..7ad9e7f6de177 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx @@ -52,7 +52,21 @@ vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children })); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, - AppTextInput: () => null, + AppTextInput: ({ + accessibilityLabel, + value, + onChangeText, + }: { + accessibilityLabel: string; + value: string; + onChangeText: (value: string) => void; + }) => ( + onChangeText(event.currentTarget.value)} + /> + ), })); vi.mock("../../components/ui/FrostedCutout", () => ({ FrostedCutout: () => null })); vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); @@ -113,3 +127,40 @@ it("does not show another feature's error as a pairing failure", () => { // Leaving the form must not wipe an error that belongs to another screen. expect(harness.pendingConnectionError).toBe("Could not send the message."); }); + +it("splits a pasted pairing link and preserves the code during address edits", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + vi.stubGlobal("__DEV__", false); + harness.pendingConnectionError = null; + const container = document.createElement("div"); + const root = createRoot(container); + + try { + act(() => root.render()); + const address = container.querySelector('input[aria-label="Address"]')!; + const code = container.querySelector('input[aria-label="Code"]')!; + const enter = (input: HTMLInputElement, value: string) => { + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + value, + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + }; + + enter(code, "manual-code"); + enter(address, " http://100.82.53.91:3773/pair#token=test-pairing-code\n"); + expect(address.value).toBe("http://100.82.53.91:3773"); + expect(code.value).toBe("test-pairing-code"); + + enter(code, "replacement-code"); + for (const value of ["", "100.82.53.92:3773", "http://100.82.53.92:3773/"]) { + enter(address, value); + expect(address.value).toBe(value); + expect(code.value).toBe("replacement-code"); + } + } finally { + act(() => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 8c1c21b195980..48de9023e49d8 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -102,7 +102,13 @@ function PairingForm({ }; const handleHostChange = (value: string) => { - setHostInput(value); + const pairing = parsePairingUrl(value); + if (pairing.code) { + setHostInput(pairing.host); + setCodeInput(pairing.code); + } else { + setHostInput(value); + } clearError(); }; diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx index 2d29be6d8b5ec..8957f95c8a97e 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx @@ -219,6 +219,7 @@ function setup(integrated = false) { const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex: data.rows.length - 1, targetFileId, focusIndex: -1, isIos: true, diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 7b97db21e62be..2da16a0c5b0f8 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -7,7 +7,7 @@ import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSi import type { ThreadMoveDestination } from "../threads/threadOrder"; import type { LegendListRef } from "@legendapp/list/react-native"; import { AnimatedLegendList } from "@legendapp/list/reanimated"; -import { THREAD_SIDEBAR_ROW_LAYOUT } from "../threads/threadListAnimations"; +import { THREAD_LIST_ROW_LAYOUT } from "../threads/threadListAnimations"; import { type EnvironmentProject, type EnvironmentThreadShell, @@ -762,7 +762,7 @@ export function HomeScreen(props: HomeScreenProps) { { settleLaunchSplashHomeRows(); diff --git a/apps/mobile/src/features/home/home-route-visibility.test.tsx b/apps/mobile/src/features/home/home-route-visibility.test.tsx index dae399420944a..1dba3c32a0dc3 100644 --- a/apps/mobile/src/features/home/home-route-visibility.test.tsx +++ b/apps/mobile/src/features/home/home-route-visibility.test.tsx @@ -41,6 +41,7 @@ function setup() { presented: true, selectedThreadKey: "env-1:thread-1", selectedPullRequestKey: null, + selectedIssueKey: null, }; return { registry, diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index 6f26a97d53b53..40c7c58f15f31 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -236,6 +236,8 @@ interface ThreadSwipeableProps { /** Omitted uses Delete only with the built-in Delete secondary action; otherwise it uses primary. */ readonly fullSwipeAction?: "delete" | "primary"; readonly fullSwipeWidth: number; + /** The list animates item layout; collapse in one step so its transition moves siblings once. */ + readonly listAnimatesLayout?: boolean; readonly onDelete: () => void; readonly onSwipeableClose?: (methods: SwipeableMethods) => void; readonly onSwipeableWillOpen?: (methods: SwipeableMethods) => void; @@ -249,6 +251,8 @@ interface ThreadSwipeableProps { readonly threadTitle: string; } +const COLLAPSED_ROW_STYLE = { height: 0, overflow: "hidden" } as const; + export function ThreadSwipeable(props: ThreadSwipeableProps) { const swipeableRef = useRef(null); const hasSecondaryAction = props.secondaryAction !== null; @@ -269,6 +273,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { ); const contentRef = useRef(content); const [isDismissing, setIsDismissing] = useState(false); + const [collapsedInList, setCollapsedInList] = useState(false); const dismissing = useSharedValue(false); const rowHeight = useSharedValue(0); const rowWidth = useSharedValue(props.fullSwipeWidth); @@ -278,6 +283,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { const primaryAction = props.primaryAction; const onDelete = props.onDelete; const onSwipeableClose = props.onSwipeableClose; + const listAnimatesLayout = props.listAnimatesLayout === true; const restoreRow = useCallback(() => { if (!mountedRef.current) return; @@ -294,6 +300,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { dismissing.set(false); })(swipeableRef.current); setIsDismissing(false); + setCollapsedInList(false); }, [actionOpacity, collapse, dismissing, fallbackTranslation]); const finishDismiss = useCallback((id?: number) => { @@ -302,6 +309,14 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { pendingDismissRef.current = null; pending.resolve(); }, []); + const collapseInList = useCallback( + (id: number) => { + if (!mountedRef.current || pendingDismissRef.current?.id !== id) return; + setCollapsedInList(true); + finishDismiss(id); + }, + [finishDismiss], + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the row's Reanimated animations and settles a pending dismissal on unmount useLayoutEffect(() => { @@ -346,6 +361,12 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { translation.set( withTiming(Math.min(translation.value, -rowWidth.value), timing, (finished) => { if (!finished) return; + // LegendList re-measures rows only on React commits, so a UI-thread height animation + // reaches it in late jumps. Collapse through React and let its transition move rows. + if (listAnimatesLayout) { + runOnJS(collapseInList)(id); + return; + } collapse.set( withTiming(1, { ...timing, duration: 180 }, (collapsed) => { if (collapsed) runOnJS(finishDismiss)(id); @@ -354,7 +375,15 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { }), ); }, - [actionOpacity, collapse, dismissing, finishDismiss, rowWidth], + [ + actionOpacity, + collapse, + collapseInList, + dismissing, + finishDismiss, + listAnimatesLayout, + rowWidth, + ], ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this row's animated dismissal in the module-level thread dismissal registry useLayoutEffect( @@ -503,45 +532,47 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { ); return ( - - { - rowHeight.set(layout.height); - setMeasuredRowHeight(layout.height); - rowWidth.set(layout.width); - }} - > - + + { + rowHeight.set(layout.height); + setMeasuredRowHeight(layout.height); + rowWidth.set(layout.width); + }} > - { - /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */ - props.children(close) - /* oxlint-enable react/refs */ - } - - - + + { + /* oxlint-disable react/refs -- The render callback receives a close/open handler; only invoking that handler accesses the ref. */ + props.children(close) + /* oxlint-enable react/refs */ + } + + + + ); } diff --git a/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx b/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx new file mode 100644 index 0000000000000..6d182964084a7 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx @@ -0,0 +1,106 @@ +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useAtom } from "@effect/atom-react"; +import { + issueAssigneeHeld, + issueAssigneesAfterPicks, + issuePicksAfterFailedWrite, + issuePicksFor, + issueWriteAfterPicks, + noIssuePicks, +} from "@t3tools/client-runtime/issue-selection"; +import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection"; +import type { IssueAssigneeCandidate } from "@t3tools/contracts"; +import { useEffect, useState } from "react"; + +import * as Dialog from "../../components/ui/Dialog"; +import { issueEnvironment, refreshIssueLists } from "../../state/issues"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation"; +import { IssueCandidatesSheet } from "./IssueCandidatesSheet"; +import { issueParamsKey, issueTarget, type IssueParams } from "./issueParams"; +import { issueAssigneePicksFamily } from "./issuePicks"; +import { issueCommandError, useIssueAccess } from "./issuePresentation"; + +export function IssueAssigneesScreen({ route }: StaticScreenProps) { + const navigation = useNavigation(); + const target = issueTarget(route.params); + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data; + const access = useIssueAccess(route.params, detail); + const result = useEnvironmentQuery(issueEnvironment.candidates(target)); + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false }); + const [query, setQuery] = useState(""); + // The atom carries a closed sheet's picks to the next one; this sheet's own live here. + const [stored, setStored] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params))); + // Picks against an older read are dropped once, when the sheet opens. + const [picks, setPicks] = useState(() => + detail ? issuePicksFor(stored, detail, false) : noIssuePicks(), + ); + const own = detail ? issuePicksFor(picks, detail, true) : noIssuePicks(); + // What was last sent is read from the atom, so a write that fails while this sheet is open is + // sent again when it closes. + const current = { ...own, written: stored.basis === detail ? stored.written : null }; + const draft = current.draft; + const allowed = access?.assignees === true; + const held = (candidate: IssueAssigneeCandidate) => + detail ? issueAssigneeHeld(detail, candidate) : false; + const needle = query.trim().toLowerCase(); + const candidates = (result.data?.assignees ?? []).filter((candidate) => + `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle), + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed + useEffect( + () => + navigation.addListener("beforeRemove", () => { + if (!detail) return; + const assignees = issueWriteAfterPicks( + issueAssigneesAfterPicks(detail, draft), + detail.assignees.map((actor) => actor.login), + current.written, + ); + if (assignees === null) return; + const sent = { ...current, written: assignees }; + setStored(sent); + void update({ ...target, input: { ...target.input, assignees } }).then((response) => { + const failure = issueCommandError(response); + if (failure === null) return refreshIssueLists(target.environmentId); + // Picks made after this write was sent are kept. + setStored((latest) => issuePicksAfterFailedWrite(latest, sent)); + Dialog.alert("Couldn't change assignees", failure); + }); + }), + [navigation, detail, draft, current, setStored, update, target], + ); + return ( + ({ + key: candidate.id, + title: candidate.login, + ...(candidate.name ? { subtitle: candidate.name } : {}), + leading: , + // Sent when the sheet closes; a failure puts the tracker's answer back. + selected: isSelected(draft, candidate.id, held(candidate)), + }))} + allowed={allowed} + notice={ + detail && !allowed + ? (access?.blocked ?? "Changing assignees needs triage access on this tracker.") + : null + } + pending={result.isPending && !result.data} + loadError={result.data ? null : result.error} + onRetry={result.refresh} + truncated={result.data?.truncated === true} + onToggle={(id) => { + const candidate = candidates.find((entry) => entry.id === id); + if (candidate) { + setPicks({ ...current, draft: toggleSelection(draft, id, candidate, held(candidate)) }); + } + }} + /> + ); +} diff --git a/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx new file mode 100644 index 0000000000000..e4d859e2e5d71 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx @@ -0,0 +1,120 @@ +import { LegendList } from "@legendapp/list/react-native"; +import type { ReactNode } from "react"; +import { Platform, View } from "react-native"; + +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { EmptyState } from "../../components/ui/EmptyState"; +import { SelectionRow } from "../../components/ui/SelectionRow"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { PullRequestSearchSheet } from "../pull-requests/PullRequestSearchSheet"; + +interface Candidate { + readonly key: string; + readonly title: string; + readonly subtitle?: string; + readonly leading: ReactNode; + readonly selected: boolean; +} + +/** The searchable checklist behind the label and assignee pickers. */ +export function IssueCandidatesSheet(props: { + readonly title: string; + readonly noun: "labels" | "people"; + readonly query: string; + readonly onQueryChange: (query: string) => void; + readonly candidates: ReadonlyArray; + readonly allowed: boolean; + readonly notice: string | null; + readonly pending: boolean; + readonly loadError: string | null; + readonly onRetry: () => void; + readonly truncated: boolean; + readonly onToggle: (key: string) => void; +}) { + const searching = props.query.trim().length > 0; + return ( + + {({ paddingBottom }) => ( + candidate.key} + extraData={props.candidates} + estimatedItemSize={64} + recycleItems + className="flex-1" + contentInsetAdjustmentBehavior="automatic" + automaticallyAdjustKeyboardInsets={Platform.OS === "ios"} + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"} + keyboardShouldPersistTaps="handled" + showsVerticalScrollIndicator={false} + contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }} + ListHeaderComponent={ + props.notice ? ( + + {props.notice} + {props.loadError && props.candidates.length > 0 ? ( + + + + + + + + ); +} diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index be674b66520d2..b99591c92b112 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -6,6 +6,7 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell import { DEFAULT_CLIENT_SETTINGS, EnvironmentId, + type LocalApi, ProjectId, ThreadId, type ScopedThreadRef, @@ -25,6 +26,7 @@ import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/en import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { readLocalApi } from "../localApi"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; @@ -42,6 +44,7 @@ vi.mock("../hooks/useThreadRouteTarget", { spy: true }); vi.mock("./sidebar/SidebarThreadRow", { spy: true }); vi.mock("../state/session", { spy: true }); vi.mock("../state/use-orchestration-command", { spy: true }); +vi.mock("../localApi", { spy: true }); vi.mock(import("../state/server"), async (original) => { const { Atom } = await import("effect/reactivity"); const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings"); @@ -261,6 +264,45 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread menu", () => { + it("tells the menu whether the keyboard opened it", async () => { + const activeProject = project("active"); + const thread = threadShell(activeProject.id, 0); + const threadRef = { environmentId: activeProject.environmentId, threadId: thread.id }; + const show = vi.fn().mockResolvedValue(null); + vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi); + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue([thread]); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef: threadRef, + }); + await using screen = await render( + + + , + ); + const row = screen.getByText("Thread 0").first(); + await expect.element(row).toBeInTheDocument(); + row.element().closest("[data-sidebar-row]")!.focus(); + await userEvent.keyboard("{Shift>}{F10}{/Shift}"); + await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(1)); + expect(show.mock.lastCall?.[2]).toBe("keyboard"); + await userEvent.click(row, { button: "right" }); + await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(2)); + expect(show.mock.lastCall?.[2]).toBe("mouse"); + }); +}); + describe("sidebar settled pagination", () => { it("keeps the viewport in place when showing more settled threads", async () => { using stack = new DisposableStack(); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 4380b80109446..2fa0d608b1f1d 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1509,6 +1509,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal: { observedKey: "environment-test:other", pendingKey: null }, routeKey: hiddenKey, + routeKeyInPlace: false, isSearching: false, scopedProjectKeys, delegatedUnderParent: new Set(), @@ -1523,6 +1524,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal: { observedKey: hiddenKey, pendingKey: null }, routeKey: hiddenKey, + routeKeyInPlace: false, isSearching: false, scopedProjectKeys, delegatedUnderParent: new Set(), @@ -1539,6 +1541,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal, routeKey, + routeKeyInPlace: false, isSearching: false, scopedProjectKeys, delegatedUnderParent: new Set(), @@ -1553,6 +1556,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal: { observedKey: hiddenKey, pendingKey: hiddenKey }, routeKey: hiddenKey, + routeKeyInPlace: false, isSearching: true, scopedProjectKeys, delegatedUnderParent: new Set(), diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 58cb50ae04e4e..e6cdb90d5c86d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -55,6 +55,7 @@ import { } from "@t3tools/client-runtime/environment"; import { AuthOrchestrationOperateScope, + type ContextMenuSource, ProjectId, type ScopedThreadRef, type ThreadId, @@ -1112,6 +1113,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ? null : scopedThreadKey(resolveListedAncestorThreadRef(routeThreadRef, threads)); const isSearchingThreads = threadSearchQuery.trim().length > 0; + // The open draft's first send names its thread in place; a finalized draft reached by + // navigation resolves through its redirect instead, and still reveals. + const routeKeyInPlace = routeDraftThread?.promotedTo != null; // History, the palette and links can open a thread the scope hides or the list // scrolled away; a remount starts at the top, so each mount scrolls to the open @@ -1120,6 +1124,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const { widensScope: revealWidensScope } = resolveSidebarRouteReveal({ reveal: routeReveal, routeKey: routeRowThreadKey, + routeKeyInPlace, isSearching: isSearchingThreads, scopedProjectKeys: chosenScopeProjectKeys, delegatedUnderParent, @@ -1143,7 +1148,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve clearSelection(); setPersistedProjectScopeKeys([]); }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); - const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey); + const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); const scratchMachineLabelFor = ( thread: Pick, @@ -1246,7 +1251,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve void handleNewThread(scopeProjectRef(group.environmentId, group.id)); }); const handleProjectFolderContextMenu = useStableCallback( - (group: SidebarProjectSnapshot, position: { x: number; y: number }) => { + ( + group: SidebarProjectSnapshot, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => { const api = readLocalApi(); if (!api) return; void (async () => { @@ -1265,6 +1274,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve { id: "project-settings", label: "Project settings", icon: "settings" }, ], position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2279,7 +2289,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleMultiSelectContextMenu = useStableCallback( - async (position: { x: number; y: number }) => { + async (position: { x: number; y: number }, source: ContextMenuSource) => { const api = readLocalApi(); if (!api) return; const selectedThreadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; @@ -2377,6 +2387,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ], position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -2530,7 +2541,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleDraftContextMenu = useStableCallback( - (draftId: DraftId, position: { x: number; y: number }) => { + (draftId: DraftId, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); const session = useComposerDraftStore.getState().getDraftSession(draftId); @@ -2552,6 +2563,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve hasProject: projectGroup != null, }), position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2581,14 +2593,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleThreadContextMenu = useStableCallback( - (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { + (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); if (!api) return; const threadKey = scopedThreadKey(threadRef); const selectionState = useThreadSelectionStore.getState(); if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { - await handleMultiSelectContextMenu(position); + await handleMultiSelectContextMenu(position, source); return; } const thread = threadByKeyRef.current.get(threadKey); @@ -2655,6 +2667,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve snoozePresets, }), position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index a7b7da0a6b53b..5217b068f9a35 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -8,7 +8,7 @@ import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; -import { BackgroundThreadContext } from "./chat/backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -229,7 +229,9 @@ export function ThreadRouteView({ className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh" inert={background} > - {view} + + {view} + {background ? null : redirect} ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index f9990ea7d0c45..7632d01b5f907 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -208,6 +208,8 @@ vi.mock("../hooks/useSettings", async () => { return { useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) => select(DEFAULT_CLIENT_SETTINGS), + ensureClientSettingsHydrated: async () => {}, + getClientSettings: () => DEFAULT_CLIENT_SETTINGS, }; }); diff --git a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx index 667c19fe4718c..c320bdef82563 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx @@ -149,6 +149,19 @@ describe("citation comment caret", () => { await userEvent.keyboard("!"); expect(input.value).toBe(`${comment}!`); }); + + it("saves with Tab then Enter after typing a comment", async () => { + using _source = setup(); + const onSave = vi.fn(() => true); + await using _screen = await mount(undefined, onSave); + await vi.waitFor(() => expect(document.activeElement).toBe(textarea())); + + await userEvent.keyboard("agreed"); + await userEvent.keyboard("{Tab}"); + await userEvent.keyboard("{Enter}"); + + expect(onSave).toHaveBeenCalledWith("agreed"); + }); }); describe("citation comment popup position", () => { diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index cdd8e1249cfc7..570c44fb1fb3c 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -117,6 +117,8 @@ export function AssistantCitationCommentEditor({ + void session.start(target)} + onStop={() => void session.stop()} + onCancel={() => session.cancel()} + onSkipPostProcessing={() => session.skipPostProcessing()} + /> + + + ); +} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 5d0238fb1f3af..53e575bd5bc99 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -1,3 +1,4 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; import { useAssetUrlState } from "../../assets/assetUrls"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { @@ -42,6 +43,7 @@ interface MarkdownFileLinkProps { threadRef?: ScopedThreadRef | undefined; onOpen?: (() => Promise>) | undefined; onOpenInPanel: (panelPath: string, line: number | undefined) => void; + resolveDragPath: () => Promise; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; onOpenInBrowser?: (() => Promise>) | undefined; @@ -73,7 +75,9 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ onReveal, revealLabel, resolveCopyPaths, + resolveDragPath, }: MarkdownFileLinkProps) { + const nativeDrag = useNativeFileDrag(environmentId, resolveDragPath); const handleOpenInEditor = () => { if (!onOpen) { return; @@ -328,6 +332,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ render={ hasPrimaryAction ? ( } @@ -362,6 +367,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ ) : ( } @@ -418,6 +424,7 @@ function areMarkdownFileLinkPropsEqual( previous.onOpenMedia === next.onOpenMedia && previous.onReveal === next.onReveal && previous.resolveCopyPaths === next.resolveCopyPaths && + previous.resolveDragPath === next.resolveDragPath && previous.revealLabel === next.revealLabel ); } diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 448e6f90a8ed0..ac3316d17b169 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -1254,6 +1254,21 @@ describe("MessagesTimeline citations", () => { ); }); + it("moves focus to the cited response so screen readers follow it", async () => { + await using _screen = await renderTimeline( + [ + message("A question", {}, "question"), + message("the cited answer", { role: "assistant" }, "cited"), + ], + { citationRequest: CITATION_REQUEST, citationHistory: { _tag: "found" } }, + ); + await vi.waitFor(() => { + const cited = document.querySelector("[data-citation-highlighted]"); + expect(cited?.textContent).toContain("the cited answer"); + expect(cited?.contains(document.activeElement)).toBe(true); + }); + }); + it("opens the superseded attempt that folds the cited response", async () => { const runId = RunId.make("run-steered"); const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({ @@ -2083,7 +2098,7 @@ it("renders automatic compaction as one live divider that finishes with its reas await expect .element( screen.getByRole("separator", { - name: "Context automatically compacted before cache expiry 899K → 19K tokens", + name: "Auto-compacted before cache expiry 899K → 19K tokens", }), ) .toBeVisible(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 1cd8066dbcd32..f834c7cc355b9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -686,7 +686,7 @@ describe("deriveMessagesTimelineRows", () => { active: true, label: "Compacting before the cache expires…", }, - "Context automatically compacted before cache expiry", + "Auto-compacted before cache expiry", ], ["onReturn", { kind: "working", compacting: true }, "Context compacted before sending"], [undefined, { kind: "context-compaction", active: true }, undefined], diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index e9a884fde6a17..87bacfd7ca2a2 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -548,13 +548,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const flatModels = (() => { const out: ModelPickerItem[] = []; + const seenKeys = new Set(); for (const [instanceId, models] of modelOptionsByInstance) { const entry = entryByInstanceId.get(instanceId); if (!entry) { continue; } for (const model of models) { + const key = modelPickerModelKey(instanceId, model.slug); if ( + seenKeys.has(key) || !shouldIncludeModelPickerOption({ entry, option: model, @@ -564,6 +567,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ) { continue; } + seenKeys.add(key); out.push({ slug: model.slug, name: model.name, diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index da9d7d50a5396..cc246a1f9967c 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -232,7 +232,7 @@ describe("open in editor announcement", () => { using _timers = fakeTimers(); const regions = () => [...document.querySelectorAll('body > [aria-live="polite"]')]; const spoken = async () => { - await act(async () => vi.runAllTimers()); + await act(async () => vi.advanceTimersByTime(250)); return regions() .map((region) => region.textContent) .join(""); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx index bf196f52542c2..06bb36a34c07f 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -4,6 +4,7 @@ import { ProviderInstanceId, type ModelSelection, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -176,6 +177,73 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo await expect.element(search).not.toBeInTheDocument(); }); +it("lists a model reported twice by one provider once, with contiguous jump shortcuts", async () => { + const instanceId = ProviderInstanceId.make("claude"); + const entries = deriveProviderInstanceEntries([ + { + instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }, + ]); + const options = new Map([ + [ + instanceId, + ["a", "b", "c", "c", "d", "d"].map((slug) => ({ + slug, + name: `Model ${slug.toUpperCase()}`, + })), + ], + ]); + const keybindings = compileResolvedKeybindingsConfig( + ([1, 2, 3, 4, 5, 6] as const).map((index) => ({ + key: `mod+${index}`, + command: `modelPicker.jump.${index}` as const, + when: "modelPickerOpen", + })), + ); + + await using screen = await render( + {}} + />, + ); + await screen.getByRole("button", { name: "Choose model" }).click(); + await expect.element(page.getByRole("option", { name: /Model A/ })).toBeVisible(); + await vi.waitFor(() => + expect( + page + .getByRole("option") + .elements() + .map((row) => [ + row.textContent?.match(/Model [A-Z]/)?.[0], + row.querySelector("kbd")?.textContent?.slice(-1), + ]), + ).toEqual([ + ["Model A", "1"], + ["Model B", "2"], + ["Model C", "3"], + ["Model D", "4"], + ]), + ); +}); + it("opens on the active provider when every favorite belongs to a disabled provider", async () => { const entries = deriveProviderInstanceEntries( ["Codex", "Claude"].map((name) => ({ diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx index 8781327b5e8ad..4f4daf7c798b4 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx @@ -1,11 +1,18 @@ import { RegistryContext } from "@effect/atom-react"; import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads"; -import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentId, + MessageId, + OrchestrationV2DispatchCommandError, + ThreadId, +} from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { formatComposerContextReference, toComposerContextId, } from "@t3tools/shared/composerContextReferences"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity"; @@ -16,6 +23,7 @@ import { page } from "vite-plus/test/browser"; const state = vi.hoisted(() => ({ threadState: null as unknown as Atom.Writable>, workflow: null as unknown, + commandResult: undefined as unknown, })); vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({ @@ -66,7 +74,7 @@ vi.mock(import("../../state/threads"), async (importOriginal) => { vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({ ...(await importOriginal()), - useAtomCommand: (() => async () => undefined) as never, + useAtomCommand: (() => async () => state.commandResult) as never, })); vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({ @@ -80,12 +88,14 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/th import { act, render as renderUi } from "../../../test/render"; import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures"; +import { ToastProvider } from "../ui/toast"; import { QueuedRunsControl } from "./QueuedRunsControl"; import { ExpandedImageDialog } from "./ExpandedImageDialog"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; function setup() { state.workflow = null; + state.commandResult = undefined; } const baseProps = { @@ -399,3 +409,37 @@ it("does not re-render while assistant text streams into the thread", async () = await act(() => registry.set(state.threadState, thread("Hello there", true))); expect(renders).toBeGreaterThan(settled); }); + +it("tells the user why Send now was rejected", async () => { + setup(); + const reason = "Target run run:active is stopping and cannot be steered."; + state.workflow = { + activeRun: { id: "run:active" }, + canPromoteToSteer: true, + queuedRuns: [ + { + run: { id: "run:queued", userMessageId: "message:queued" }, + text: "Follow up", + attachments: [], + }, + ], + }; + state.commandResult = AsyncResult.failure( + Cause.fail( + new OrchestrationV2DispatchCommandError({ + commandId: CommandId.make("command:promote"), + commandType: "queued-message.promote-to-steer", + message: reason, + detail: reason, + }), + ), + ); + await using _screen = await renderUi( + + + , + ); + + await page.getByRole("button", { name: "Send now" }).click(); + await vi.waitFor(() => expect(page.getByText(reason).element()).toBeVisible()); +}); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 8972bf468448b..49cbc8f050eea 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -1,4 +1,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { @@ -34,6 +38,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { isImageAttachment, type ChatImageAttachment, type ChatMessage } from "../../types"; import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; +import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { GuestMessageName } from "./guestMessageStyle"; @@ -168,19 +173,27 @@ export function QueuedRunsControl({ if (!canSendRun(freshContext) || steerInFlightRef.current) return; steerInFlightRef.current = true; setBusyRunId(queuedRunId); - if (workflow?.canSendNow) { - await resume({ - environmentId: props.environmentId, - input: { threadId: props.threadId, runId: queuedRunId }, - }); - } else if (activeRun !== null) { - await promote({ - environmentId: props.environmentId, - input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, - }); - } + const result = workflow?.canSendNow + ? await resume({ + environmentId: props.environmentId, + input: { threadId: props.threadId, runId: queuedRunId }, + }) + : activeRun !== null + ? await promote({ + environmentId: props.environmentId, + input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, + }) + : null; steerInFlightRef.current = false; setBusyRunId(null); + if (result?._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Could not send queued message", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } }; useImperativeHandle(ref, () => ({ diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 5ba6985e19d21..6b8de5aca8ecc 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -1,6 +1,7 @@ import type { EditorId, EnvironmentId, + IssueTrackerKind, PreviewAnnotationPayload, ProjectId, ResolvedKeybindingsConfig, @@ -19,6 +20,7 @@ import { PersistentThreadTerminalPanel, type PersistentThreadTerminalPanelProps, } from "../PersistentThreadTerminals"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; import { pullRequestPanelContext } from "../pullRequest/pullRequestDetail.logic"; import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; import { PullRequestDetailGhost } from "../pullRequest/PullRequestGhosts"; @@ -77,6 +79,7 @@ export function RightPanelSurfaceContent(props: { readonly onCloseSurface: (surface: RightPanelSurface) => void; readonly terminal: RightPanelTerminalProps; readonly pullRequest: RightPanelPullRequestProps; + readonly issuesSupported: boolean; readonly files: RightPanelFileProps; readonly sideChatParentPanel: SideChatParentPanel; }) { @@ -171,6 +174,40 @@ export function RightPanelSurfaceContent(props: { /> ); } + case "issue": + if (!props.pullRequest.capabilityKnown) return ; + if (!props.issuesSupported) { + return ( + + ); + } + return ( + { + useRightPanelStore.getState().openPullRequest(threadRef, { + projectId: reference.projectId, + repository: reference.repository, + number: reference.number, + ...(reference.host ? { host: reference.host } : {}), + }); + }} + /> + ); case "pull-requests": return ; case "side-chat": diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsx index d2489e6ce2993..2691b8dafbb41 100644 --- a/apps/web/src/components/chat/SkillInlineText.tsx +++ b/apps/web/src/components/chat/SkillInlineText.tsx @@ -8,6 +8,7 @@ import { useRightPanelStore } from "~/rightPanelStore"; import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip"; import { ContextChipPopover } from "../contextChipParts"; import { Button } from "../ui/button"; +import { PopoverClose } from "../ui/popover"; import { ModelMentionChip } from "./ModelMentionChip"; function SkillInlineText(props: { @@ -135,9 +136,12 @@ export function SkillChipPopover(props: {

{props.label}

{props.description || "No description is available for this skill."}

{props.onViewInstructions ? ( - + ) : null} diff --git a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx index 07f16c8794e98..826b335469d09 100644 --- a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx +++ b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx @@ -1,6 +1,6 @@ import type { SnapShotSource } from "@t3tools/contracts"; -import { ImageIcon, TextIcon } from "lucide-react"; -import { Suspense } from "react"; +import { CheckIcon, CopyIcon, ImageIcon, TextIcon } from "lucide-react"; +import { Suspense, useRef, useState } from "react"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { cn } from "../../lib/utils"; @@ -8,6 +8,10 @@ import { RenderErrorBoundary } from "../RenderErrorBoundary"; import { Button } from "../ui/button"; import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + ANCHORED_COPY_TOAST_TIMEOUT_MS, + showAnchoredCopyErrorToast, +} from "../ui/anchoredCopyToast"; import { HighlightedTokens } from "./HighlightedTokens"; export const SNAP_SHOT_ATTACHMENT_FRAME_CLASS = @@ -71,14 +75,64 @@ function snapShotIncludesAccessibility(source: SnapShotSource): boolean { return Boolean(source.accessibility || source.accessibleText?.trim()); } +export function SnapShotCopyButton({ + onCopy, + side = "top", +}: { + onCopy: () => Promise; + side?: "top" | "right" | "bottom" | "left"; +}) { + const ref = useRef(null); + const [copied, setCopied] = useState(false); + + return ( + + { + event.stopPropagation(); + void onCopy().then( + () => { + setCopied(true); + setTimeout(() => setCopied(false), ANCHORED_COPY_TOAST_TIMEOUT_MS); + }, + (error: unknown) => + showAnchoredCopyErrorToast( + ref, + error instanceof Error ? error : new Error(String(error)), + ), + ); + }} + size="xs" + variant="ghost-muted" + /> + } + > + {copied ? ( + + Copy snapshot + + ); +} + export function SnapShotContentsButton({ source, className, side = "top", + onCopySnapshot, }: { source: SnapShotSource; className?: string; side?: "top" | "right" | "bottom" | "left"; + onCopySnapshot?: (() => Promise) | undefined; }) { const includesAccessibility = snapShotIncludesAccessibility(source); const ContentsIcon = includesAccessibility ? TextIcon : ImageIcon; @@ -111,7 +165,14 @@ export function SnapShotContentsButton({
- Accessibility data +
+ Accessibility data + {onCopySnapshot && ( +
+ +
+ )} +
{accessibilityDetails ? ( Promise) | undefined; className?: string; }) { return ( @@ -157,7 +220,11 @@ export function SnapShotAttachmentDetails({
{source.appName} - +
{source.windowTitle || "Captured window"} diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index 50b50273ba965..d89bea79080da 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -129,7 +129,7 @@ export function SubagentTooltipContent(props: { showBadge={showInstanceBadge && entry?.accentColor !== undefined} badgeContent="none" badgeClassName="h-2 min-w-2 px-0" - iconClassName="size-3 shrink-0 grayscale opacity-60" + iconClassName="size-3 shrink-0 opacity-60" /> ) : ( diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx new file mode 100644 index 0000000000000..327b8a0afa3fb --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -0,0 +1,43 @@ +import { threadIssueKeyOf, type ThreadIssueLink } from "@t3tools/contracts"; +import type { MouseEvent as ReactMouseEvent } from "react"; + +import { cn } from "~/lib/utils"; + +import { IssueGlyph } from "../issue/issuePresentation"; +import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, +} from "./threadDetailsPanelStyles"; + +/** + * The thread details panel's issue rows, one per linked issue, beside the pull request rows. A + * row names the issue as it was when linked and opens it in the right panel, which reads its + * live state. + */ +export function ThreadDetailsIssueRows({ + links, + onOpenLink, +}: { + links: ReadonlyArray; + onOpenLink: (event: ReactMouseEvent, link: ThreadIssueLink) => void; +}) { + if (links.length === 0) return null; + return ( + <> + {links.map((link) => ( + onOpenLink(event, link)} + > + + + {link.displayKey}: {link.title} + + + ))} + + ); +} diff --git a/apps/web/src/components/chat/ThreadFindBar.tsx b/apps/web/src/components/chat/ThreadFindBar.tsx index 466cd929a7580..5ef0485ff4f50 100644 --- a/apps/web/src/components/chat/ThreadFindBar.tsx +++ b/apps/web/src/components/chat/ThreadFindBar.tsx @@ -1,9 +1,13 @@ -import { useEffect, useRef, type KeyboardEvent } from "react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; import { cn } from "~/lib/utils"; -import { formatThreadFindCount } from "./threadFind"; +import { + formatThreadFindCount, + nextThreadFindAnnouncement, + type ThreadFindAnnouncement, +} from "./threadFind"; import { THREAD_DETAILS_CARD_GAP } from "./threadDetailsCardLayout"; interface ThreadFindBarProps { @@ -14,6 +18,10 @@ interface ThreadFindBarProps { readonly status: "loading" | "error" | null; readonly onRetry: () => void; readonly activeIndex: number; + /** Bumped by each user search or step; background refreshes keep it. */ + readonly navigationId: number; + /** Whether the label shows the outcome of `navigationId`: a count or a failure. */ + readonly settled: boolean; readonly focusRequestId: number; readonly onQueryChange: (query: string) => void; readonly onNext: () => void; @@ -37,8 +45,6 @@ export function ThreadFindBar(props: ThreadFindBarProps) { props.open, ]); - if (!props.open) return null; - const hasQuery = props.query.trim().length > 0; const noResults = hasQuery && !props.status && props.matchCount === 0; let label = ""; @@ -47,6 +53,17 @@ export function ThreadFindBar(props: ThreadFindBarProps) { } if (props.status === "loading") label = "Searching…"; if (props.status === "error") label = "Search failed"; + const [storedAnnouncement, setAnnouncement] = useState(null); + const announcement = nextThreadFindAnnouncement(storedAnnouncement, { + navigationId: props.navigationId, + text: label, + settled: props.settled || props.status === "loading", + provisional: props.status !== null, + }); + if (announcement !== storedAnnouncement) setAnnouncement(announcement); + + if (!props.open) return null; + const navigationDisabled = props.matchCount === 0 || props.status === "loading" || props.counting === true; const handleKeyDown = (event: KeyboardEvent) => { @@ -87,8 +104,11 @@ export function ThreadFindBar(props: ThreadFindBarProps) { onKeyDown={handleKeyDown} /> + + {announcement.text} + event.preventDefault()} type="button" > -
{items.map((item, index) => { const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`; const activeDistance = diff --git a/apps/web/src/components/chat/TimelineRowParts.tsx b/apps/web/src/components/chat/TimelineRowParts.tsx index 549b9c7a422f9..c881b845dd21a 100644 --- a/apps/web/src/components/chat/TimelineRowParts.tsx +++ b/apps/web/src/components/chat/TimelineRowParts.tsx @@ -41,14 +41,22 @@ export function TimelineRowTimestamp({ ); } -export function ActivityShimmerOverlay({ children }: { children: ReactNode }) { +export function ActivityShimmerOverlay({ + children, + className, +}: { + children: ReactNode; + className?: string; +}) { return ( - {children} + + {children} + ); diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 3fee2134c3f58..7cd57ed18c0c1 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,3 +1,4 @@ +import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { @@ -102,7 +103,7 @@ const MEDIA_EDGE_CLASS_NAME = "relative after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:ring-1 after:ring-inset after:ring-black/9 dark:after:ring-white/12"; const BUBBLE_CHIP_CLASS_NAME = - "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]"; + "[&_[data-slot=context-chip]]:[--context-chip-message-ink:var(--context-chip-message)]"; function UserFileCard({ file, @@ -597,6 +598,25 @@ function UserTimelineRow({ row }: { row: Extract { + const image = userImages.find((candidate) => candidate.id === id); + const record = resolvedContext.records + .map(asKnownContextRecord) + .find((candidate) => candidate?.kind === "image" && candidate.attachmentId === id); + if (!image?.previewUrl || record?.kind !== "image") + throw new Error("Snapshot is no longer available."); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ctx.activeThreadEnvironmentId, messageId: row.message.id }, + records: [{ ...record, ...(image.source ? { source: image.source } : {}) }], + }); + if (!fragment) throw new Error("The snapshot is too large to copy."); + await copySnapshotToClipboard( + image.previewUrl, + formatComposerContextReference(record), + fragment, + ); + }; const onBodyCopyCapture = (event: React.ClipboardEvent) => { if (resolvedContext.records.length === 0 || !event.clipboardData) return; const selection = window.getSelection(); @@ -661,7 +681,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(userImages, image.id); + const preview = buildExpandedImagePreview(userImages, image.id, copySnapshot); if (preview) onImageExpand(preview); }} onOpenFile={onFileOpen} @@ -737,7 +757,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(regularImages, image.id); + const preview = buildExpandedImagePreview(regularImages, image.id, copySnapshot); if (!preview) return; ctx.onImageExpand(preview); }} @@ -772,7 +792,10 @@ function UserTimelineRow({ row }: { row: Extract )} {image.previewUrl && image.source?.kind === "snap-shot" ? ( - + copySnapshot(image.id)} + /> ) : null}
))} diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 39801a908b952..e345472b1f972 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -1,3 +1,5 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isSvgAttachment } from "@t3tools/shared/image"; import { useRenderedAppearance } from "../../hooks/useTheme"; @@ -68,11 +70,15 @@ function UserMessageMentionChip(props: { copyMarkdown: string; }) { const ctx = use(TimelineRowCtx); + const nativeDrag = useNativeFileDrag(ctx.activeThreadEnvironmentId, () => + resolvePathLinkTarget(props.record.path, ctx.workspaceRoot ?? ""), + ); return ( } aria-label={`Preview ${props.record.path}`} diff --git a/apps/web/src/components/chat/backgroundThread.ts b/apps/web/src/components/chat/backgroundThread.ts index b3dfee09a663c..e402bc5e62165 100644 --- a/apps/web/src/components/chat/backgroundThread.ts +++ b/apps/web/src/components/chat/backgroundThread.ts @@ -5,3 +5,6 @@ import { createContext } from "react"; * parent's panel; its global shortcuts and listeners stand down. */ export const BackgroundThreadContext = createContext(false); + +/** True only for a thread kept mounted out of sight under Settings or Usage. */ +export const HiddenThreadContext = createContext(false); diff --git a/apps/web/src/components/chat/copySnapshot.test.ts b/apps/web/src/components/chat/copySnapshot.test.ts new file mode 100644 index 0000000000000..9ac7080f7b0f7 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.test.ts @@ -0,0 +1,75 @@ +import { ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + decodeComposerContextClipboardHtml, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { expect, it } from "vite-plus/test"; + +import { copySnapshot } from "./copySnapshot"; + +it.each([false, true])( + "preserves image bytes and snapshot metadata, custom format rejected: %s", + async (rejectCustom) => { + class Item { + constructor(readonly data: Record>) {} + } + let clipboard: Item | undefined; + const write = async ([item]: Item[]) => { + if (rejectCustom && item?.data[COMPOSER_CONTEXT_CLIPBOARD_MIME]) + throw new Error("Unsupported format"); + clipboard = item; + await Promise.all(Object.values(item!.data)); + }; + const originals = { + navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"), + ClipboardItem: Object.getOwnPropertyDescriptor(globalThis, "ClipboardItem"), + }; + using _globals = { + [Symbol.dispose]() { + for (const key of ["navigator", "ClipboardItem"] as const) { + const descriptor = originals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { clipboard: { write } }, + }); + Object.defineProperty(globalThis, "ClipboardItem", { configurable: true, value: Item }); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [ + { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "Snapshot", + attachmentId: "snapshot", + name: "snapshot.png", + mimeType: "image/png", + sizeBytes: 3, + source: { + kind: "snap-shot", + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, + }, + ], + })!; + const image = "data:image/png;base64,AQID"; + await copySnapshot(image, "Snapshot", fragment); + const png = await clipboard!.data["image/png"]!; + expect(png.type).toBe("image/png"); + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual([1, 2, 3]); + expect( + decodeComposerContextClipboardHtml(await (await clipboard!.data["text/html"]!).text()), + ).toEqual(JSON.parse(fragment)); + expect(await (await clipboard!.data["text/plain"]!).text()).toBe("Snapshot"); + }, +); diff --git a/apps/web/src/components/chat/copySnapshot.ts b/apps/web/src/components/chat/copySnapshot.ts new file mode 100644 index 0000000000000..118121e753647 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.ts @@ -0,0 +1,33 @@ +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextClipboardHtml, +} from "@t3tools/shared/composerContextClipboard"; + +import { readMediaPng } from "../media/mediaContent"; + +export async function copySnapshot(src: string, text: string, fragment: string): Promise { + if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") { + throw new Error("Snapshot copying requires a secure browser connection."); + } + const formats = { + "image/png": readMediaPng(src), + "text/plain": new Blob([text], { type: "text/plain" }), + "text/html": new Blob([encodeComposerContextClipboardHtml(text, fragment)], { + type: "text/html", + }), + }; + // Start writing within the click gesture, before the image fetch or decode completes. + try { + await navigator.clipboard.write([ + new ClipboardItem({ + ...formats, + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: new Blob([fragment], { + type: COMPOSER_CONTEXT_CLIPBOARD_MIME, + }), + }), + ]); + } catch { + // HTML carries the same snapshot metadata when custom clipboard formats are unsupported. + await navigator.clipboard.write([new ClipboardItem(formats)]); + } +} diff --git a/apps/web/src/components/chat/threadFind.test.ts b/apps/web/src/components/chat/threadFind.test.ts new file mode 100644 index 0000000000000..43b1c75b07f0d --- /dev/null +++ b/apps/web/src/components/chat/threadFind.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vite-plus/test"; +import { nextThreadFindAnnouncement, type ThreadFindAnnouncement } from "./threadFind"; + +type Step = Omit & { readonly provisional?: boolean }; + +function replay(steps: readonly Step[]) { + let current: ThreadFindAnnouncement | null = null; + const spoken: string[] = []; + for (const step of steps) { + const next = nextThreadFindAnnouncement(current, { provisional: false, ...step }); + if (next.text !== (current?.text ?? "")) spoken.push(next.text); + current = next; + } + return spoken; +} + +describe("nextThreadFindAnnouncement", () => { + it("speaks each settled search or step once and stays silent through streamed refreshes", () => { + expect( + replay([ + { navigationId: 1, text: "Searching…", settled: true, provisional: true }, + { navigationId: 1, text: "1/…", settled: false }, + { navigationId: 1, text: "1/3", settled: true }, + { navigationId: 1, text: "1/…", settled: false }, + { navigationId: 1, text: "1/4", settled: true }, + { navigationId: 2, text: "1/4", settled: false }, + { navigationId: 2, text: "2/4", settled: true }, + { navigationId: 2, text: "2/5", settled: true }, + ]), + ).toEqual(["Searching…", "1/3", "2/4"]); + }); + + it("speaks a failure and the result of retrying it", () => { + expect( + replay([ + { navigationId: 1, text: "Search failed", settled: true, provisional: true }, + { navigationId: 1, text: "1/3", settled: true }, + { navigationId: 1, text: "1/4", settled: true }, + ]), + ).toEqual(["Search failed", "1/3"]); + }); + + it("speaks a new search that ends on the same count as the last one", () => { + expect( + replay([ + { navigationId: 1, text: "Searching…", settled: true, provisional: true }, + { navigationId: 1, text: "0/0", settled: true }, + { navigationId: 2, text: "Searching…", settled: true, provisional: true }, + { navigationId: 2, text: "0/0", settled: true }, + ]), + ).toEqual(["Searching…", "0/0", "Searching…", "0/0"]); + }); +}); diff --git a/apps/web/src/components/chat/threadFind.ts b/apps/web/src/components/chat/threadFind.ts index d0a265ceb13fa..98bff31c95996 100644 --- a/apps/web/src/components/chat/threadFind.ts +++ b/apps/web/src/components/chat/threadFind.ts @@ -23,3 +23,28 @@ export function stepThreadFindIndex(index: number, total: number, delta: number) export function formatThreadFindCount(index: number, total: number): string { return total <= 0 ? "0/0" : `${clampThreadFindIndex(index, total) + 1}/${total}`; } + +export interface ThreadFindAnnouncement { + readonly navigationId: number; + readonly text: string; + /** The label shows the outcome of `navigationId`: a count, a search or a failure. */ + readonly settled: boolean; + /** "Searching…" or a failure: spoken, but a later count for the same navigation is too. */ + readonly provisional: boolean; +} + +/** + * What the find counter's live region says: the settled outcome of each + * user search or step, once. Background refreshes during streaming keep the + * navigation, so they stay silent. A new query passes through "Searching…", + * so its count is spoken even when it equals the last one. + */ +export function nextThreadFindAnnouncement( + previous: ThreadFindAnnouncement | null, + next: ThreadFindAnnouncement, +): ThreadFindAnnouncement { + if (!next.settled) return previous ?? { ...next, text: "" }; + if (previous?.navigationId !== next.navigationId) return next; + if (previous.settled && !previous.provisional) return previous; + return previous.text === next.text ? previous : next; +} diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index e2bf9676b8b6d..d48e965895ddd 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -48,6 +48,7 @@ function deferred() { it.each([ { kind: "file", edit: "delete" }, { kind: "image", edit: "delete" }, + { kind: "image", edit: "retain" }, { kind: "file", edit: "undo" }, { kind: "file", edit: "retain" }, { kind: "file", edit: "switch" }, @@ -124,7 +125,17 @@ it.each([ const attachment = ( kind === "file" ? { ...attachmentFields, kind: "file" as const } - : { ...attachmentFields, kind: "image" as const } + : { + ...attachmentFields, + kind: "image" as const, + source: { + kind: "snap-shot" as const, + appName: "Finder", + windowTitle: "Downloads", + capturedAt: "2026-01-01T00:00:00.000Z", + accessibleText: "Downloads", + }, + } ) satisfies ComposerContextRecord; const annotation = { version: 1, @@ -182,6 +193,10 @@ it.each([ const draft = store.getComposerDraft(target)!; expect(draft.prompt).toBe(promptRef.current); const attachments = kind === "file" ? draft.files : draft.images; + if (kind === "image" && edit === "retain") + expect(draft.images[0]?.source).toEqual( + attachment.kind === "image" ? attachment.source : undefined, + ); expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 0cc66d6a71d19..265278faec747 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -246,6 +246,7 @@ export function useComposerContextImport(input: { sizeBytes: file.size, previewUrl: URL.createObjectURL(file), file, + ...(record.source ? { source: record.source } : {}), }, ], { diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx index 3b23abfcb7c9a..1a6e2b038832c 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx @@ -39,7 +39,13 @@ vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({ refreshSelection: resources.refreshSelection, }), })); -vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects })); +vi.mock("../../state/entities", () => ({ + useProjects: () => resources.projects, + readProject: (ref: { environmentId: EnvironmentId; projectId: ProjectId }) => + resources.projects.find( + (project) => project.environmentId === ref.environmentId && project.id === ref.projectId, + ) ?? null, +})); vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) })); function setup() { @@ -102,6 +108,7 @@ function setup() { enabled: true, }, connection: { phase: "connected", error: null, traceId: null }, + refusedRouteIds: [], serverConfig: null, }, ]), @@ -314,3 +321,35 @@ it("keeps the selected models when automatic routing picks another machine", asy await expect.element(screen.getByText(b)).toBeInTheDocument(); await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument(); }); + +it.each([ + { name: "takes the destination default", explicit: false, remoteDefault: true, model: "luna" }, + { name: "keeps a model the user picked", explicit: true, remoteDefault: true, model: "sol" }, + { + name: "keeps the last-used model without a default", + explicit: false, + remoteDefault: false, + model: "sol", + }, +])("$name when the draft switches machine by hand", async ({ explicit, remoteDefault, model }) => { + const { b, draftId, input, store } = fanoutSetup(); + const codex = ProviderInstanceId.make("codex"); + resources.projects = resources.projects.map((project) => + project.environmentId === b && remoteDefault + ? { ...project, defaultModelSelection: createModelSelection(codex, "luna") } + : project, + ); + store.setStickyModelSelection(createModelSelection(codex, "sol")); + store.setModelSelection(draftId, createModelSelection(codex, "sol"), { explicit }); + await using screen = await render( + , + ); + await screen.getByRole("button", { name: `Switch to ${b}` }).click(); + await expect.element(screen.getByText(b)).toBeInTheDocument(); + const draft = store.getComposerDraft(draftId); + expect(draft?.activeProvider).toBe(codex); + expect(draft?.modelSelectionByProvider[codex]?.model).toBe(model); + expect(draft?.modelSelectionExplicit === true).toBe(explicit); +}); diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts index 977f5cb31c7f1..86664b567a658 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts @@ -35,6 +35,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import type { DraftSessionState } from "../../composerDraftStore"; import { loadBalancingSendWarning } from "./composerSend.logic"; import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { seedDraftModelSelection } from "../../lib/seedDraftModelSelection"; import { draftFanoutSelectionsAtom } from "./chatViewSend"; interface DraftEnvironmentRoutingInput { @@ -337,6 +338,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) loadBalancedEnvironmentId: null, }); } + seedDraftModelSelection(draftId, projectRef); }; const finish = () => { if (environmentChangeRef.current === request) environmentChangeRef.current = null; diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.ts index b88951e3b6ac3..ada7955e1c2ad 100644 --- a/apps/web/src/components/chat/useThreadFind.ts +++ b/apps/web/src/components/chat/useThreadFind.ts @@ -214,6 +214,9 @@ export function useThreadFind({ counting, activeIndex, status, + navigationId: state.navigationId, + settled: + status === "error" || (status === null && !counting && navigationId === state.navigationId), focusRequestId: state.focusRequestId, onRetry: remote.refresh, onQueryChange: (query: string) => { diff --git a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx index cc3640fc2a166..40c84cc69fde6 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx @@ -1,11 +1,15 @@ -import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; +import { + FILE_PREVIEW_SCROLL_SCRIPT, + injectHtmlRenderBootstrap, + readFilePreviewScroll, +} from "@t3tools/shared/htmlRender"; import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; -import { HtmlRenderDocument } from "./BrowserDocumentFrame"; +import { BrowserDocumentFrame, HtmlRenderDocument } from "./BrowserDocumentFrame"; const sizeChanged = (height: number) => ({ jsonrpc: "2.0", @@ -219,3 +223,98 @@ it("keeps the first and last selected card rings inside the fitted renderer fram expect(bounds.scrollWidth).toBeLessThanOrEqual(bounds.viewportWidth); } }); + +describe("BrowserDocumentFrame", () => { + it("keeps a page on screen until its next revision has loaded", async () => { + using pages = (() => { + const urls = ["first", "second", "third"].map((name) => + URL.createObjectURL(new Blob([`

${name}

`], { type: "text/html" })), + ); + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) }; + })(); + const [first, second, third] = pages.urls as [string, string, string]; + const frame = (revision: string, src: string) => ( +
+ +
+ ); + await using screen = await render(frame("1", first)); + const srcs = () => Array.from(screen.container.querySelectorAll("iframe"), (f) => f.src); + const onScreen = () => { + const box = screen.container.getBoundingClientRect(); + const hit = document.elementFromPoint(box.left + box.width / 2, box.top + 10); + return hit instanceof HTMLIFrameElement ? hit.src : null; + }; + await vi.waitFor(() => expect(onScreen()).toBe(first)); + + // The incoming frame cannot have loaded when it is inserted, so the current page must cover it. + const atInsertion = new Promise((resolve) => { + const observer = new MutationObserver(() => { + if (!srcs().includes(second)) return; + observer.disconnect(); + resolve(onScreen()); + }); + observer.observe(screen.container, { childList: true, subtree: true }); + }); + await screen.rerender(frame("2", second)); + expect(await atInsertion).toBe(first); + await vi.waitFor(() => expect(srcs()).toEqual([second])); + expect(onScreen()).toBe(second); + + await screen.rerender(frame("3", third)); + await screen.rerender(frame("2", second)); + expect(srcs(), "returning to the shown revision kept the pending frame").toEqual([second]); + await screen.rerender(frame("3", third)); + await vi.waitFor(() => expect(onScreen()).toBe(third)); + }); + + it("opens the next revision where the reader left the page", async () => { + // The first page scrolls itself, as a reader would; the second is served without scrolling. + const tall = '
report
'; + using pages = (() => { + const urls = [ + `${tall}`, + tall, + ].map((body) => + URL.createObjectURL(new Blob([body + FILE_PREVIEW_SCROLL_SCRIPT], { type: "text/html" })), + ); + return { urls, [Symbol.dispose]: () => urls.forEach((url) => URL.revokeObjectURL(url)) }; + })(); + const [first, second] = pages.urls as [string, string]; + const reports: Array<{ source: MessageEventSource | null; y: number }> = []; + const onMessage = (event: MessageEvent) => { + const scroll = readFilePreviewScroll(event.data); + if (scroll !== undefined) reports.push({ source: event.source, y: scroll.y }); + }; + window.addEventListener("message", onMessage); + using _listener = { [Symbol.dispose]: () => window.removeEventListener("message", onMessage) }; + const frame = (revision: string, src: string) => ( +
+ +
+ ); + await using screen = await render(frame("1", first)); + const iframes = () => Array.from(screen.container.querySelectorAll("iframe")); + await vi.waitFor(() => expect(reports.map((report) => report.y)).toContain(1200)); + + await screen.rerender(frame("2", second)); + await vi.waitFor(() => expect(iframes().map((element) => element.src)).toEqual([second])); + const shown = iframes()[0]!.contentWindow; + expect( + reports.filter((report) => report.source === shown).map((report) => report.y), + "the next revision was uncovered before it took the reader's position", + ).toContain(1200); + }); +}); diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 4dba7607f81c0..bfa699cf252b4 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -7,6 +7,10 @@ import { THREAD_JUMP_KEYBINDING_COMMANDS, } from "@t3tools/contracts"; import { + type FilePreviewScroll, + filePreviewRestoreScrollMessage, + isFilePreviewScrollRestored, + readFilePreviewScroll, type HtmlRenderShortcut, htmlRenderShortcutsMessage, htmlRenderThemeFragment, @@ -157,21 +161,119 @@ export function BrowserDocumentFrame(props: { className="min-h-0 flex-1" /> ) : ( - + ); } -// URL renewals must not discard form input or scroll; a new key mounts a fresh document. -function FileDocument(props: { readonly src: string; readonly title: string }) { - const [src] = useState(props.src); +interface FileDocumentRevision { + readonly key: string; + readonly src: string; +} + +interface FileDocumentFrames { + readonly shown: FileDocumentRevision; + readonly next: FileDocumentRevision | null; +} + +// Identity, not key, so a late load from a replaced frame cannot uncover a newer unloaded one. +const showRevision = + (next: FileDocumentRevision) => + (current: FileDocumentFrames): FileDocumentFrames => + current.next === next ? { shown: next, next: null } : current; + +// A page whose load never fires (a stalled subresource) must not pin the previous revision. +const FILE_DOCUMENT_SWAP_TIMEOUT_MS = 5_000; + +// URL renewals keep a revision's first URL, so they do not discard form input or scroll. A new +// revision loads beneath the page on screen, takes its scroll position and replaces it once +// painted, so no blank frame shows and the reader keeps their place. +function FileDocument(props: { + readonly documentKey: string; + readonly src: string; + readonly title: string; +}) { + const [frames, setFrames] = useState(() => ({ + shown: { key: props.documentKey, src: props.src }, + next: null, + })); + if ((frames.next ?? frames.shown).key !== props.documentKey) { + setFrames({ + shown: frames.shown, + next: + frames.shown.key === props.documentKey ? null : { key: props.documentKey, src: props.src }, + }); + } + const { next } = frames; + const shownFrame = useRef(null); + const nextFrame = useRef(null); + // The page reports its scroll position (see FILE_PREVIEW_SCROLL_SCRIPT); the next revision + // scrolls there before it is uncovered. + const scroll = useRef(null); + // Two frames let the browser paint the incoming page before it is uncovered. + const reveal = (revision: FileDocumentRevision) => + requestAnimationFrame(() => requestAnimationFrame(() => setFrames(showRevision(revision)))); + const onFrameMessage = useEffectEvent((event: MessageEvent) => { + const position = readFilePreviewScroll(event.data); + if (position !== undefined) { + if (event.source === shownFrame.current?.contentWindow) scroll.current = position; + } else if ( + next !== null && + event.source === nextFrame.current?.contentWindow && + isFilePreviewScrollRestored(event.data) + ) { + reveal(next); + } + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for the frames' scroll reports + useEffect(() => { + const onMessage = (event: MessageEvent) => onFrameMessage(event); + window.addEventListener("message", onMessage); + return () => window.removeEventListener("message", onMessage); + }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- swaps in a revision whose load event never arrives + useEffect(() => { + if (next === null) return; + const timer = setTimeout(() => setFrames(showRevision(next)), FILE_DOCUMENT_SWAP_TIMEOUT_MS); + return () => clearTimeout(timer); + }, [next]); + // The shown frame stays last so it paints on top and is never moved, which would reload it. return ( -