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..356a097b4bfbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -326,7 +326,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..dc06871822830 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: @@ -140,8 +146,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 +169,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 +240,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 +252,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 @@ -347,9 +361,169 @@ jobs: fi echo "link=$link" >> "$GITHUB_OUTPUT" + 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: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + + # The comment script comes from main, not from the PR. + - name: Checkout trusted scripts + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + path: .trusted + sparse-checkout: .github/scripts + + # 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). + - 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 + + - name: Select Xcode 27.1 + 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 + 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 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - name: Enable corepack + run: | + npm install --global corepack@latest + corepack enable + pnpm --version + + - name: Install mobile dependencies + run: pnpm install --frozen-lockfile --filter=@t3tools/mobile... + + - name: Setup EAS + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + with: + eas-version: latest + eas-cache: false + token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + packager: npm + + - name: Build tools + run: | + command -v pod || sudo gem install cocoapods --no-document + command -v fastlane || brew install fastlane + pod --version + fastlane --version | tail -1 + + - 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 + + - id: build + name: Build and upload + working-directory: apps/mobile + shell: bash + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + run: | + export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" + eas build --local --platform ios --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.ipa" + 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" + + 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..26f9a16f8a5d7 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,33 @@ 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 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). + - 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 - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' @@ -68,25 +96,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 +115,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 +163,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: @@ -258,14 +291,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 +301,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 @@ -447,9 +475,205 @@ jobs: # 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" + 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 + + - id: record + name: Check build record + run: | + 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 + + # 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). + - 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 + + - 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: Enable corepack + if: steps.record.outputs.built != 'true' + 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... + + - 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_PREVIEW_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 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 + + # EAS hosts the signed client and returns its install page. + - id: build + name: Build and upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" + eas build --local --platform ios --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.ipa" + 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 "### iOS preview client for \`$FINGERPRINT\`: $link" + } >> "$GITHUB_STEP_SUMMARY" + + # The tag stores the install link and provisioning-profile expiry. + - name: Record build + 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" + profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | awk '/^Payload\/[^/]+\.app\/embedded.mobileprovision$/')" + test -n "$profile_path" + 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")" + old_tag="$(git rev-parse -q --verify "refs/tags/$BUILD_TAG" || true)" + git tag -f -a "$BUILD_TAG" -m "$record" + # Only this step has the token; the checkout's copy was removed before the build. + git push --force-with-lease="refs/tags/$BUILD_TAG:$old_tag" "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "refs/tags/$BUILD_TAG" + + 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/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/package.json b/apps/mobile/package.json index 424d41e903e51..2ab0e38d89e24 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -134,7 +134,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/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 88b4999c45532..c2946c59ed065 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, @@ -753,7 +753,7 @@ export function HomeScreen(props: HomeScreenProps) { { settleLaunchSplashHomeRows(); 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/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx index 9d3d2f9279bd1..367942ad43139 100644 --- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx +++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx @@ -28,7 +28,13 @@ import { type ComponentProps, type ReactNode, } from "react"; -import { StyleSheet, View } from "react-native"; +import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; +import { + currentWorkspaceSelections, + workspaceSelectionCheck, +} from "./workspace/workspace-selection-store"; +import { workspaceTabColumns, workspaceTabPage } from "./workspace/workspace-tab-navigation"; +import { Platform, StyleSheet, View } from "react-native"; import { Split, type SplitHostCommands } from "react-native-screens"; import { SafeAreaView } from "react-native-safe-area-context"; import { GestureHandlerRootView } from "react-native-gesture-handler"; @@ -77,6 +83,7 @@ import { NativePrimaryColumnContext, NativeWorkspaceInspectorContext, NativeWorkspaceModeContext, + NativeWorkspaceTabActivityContext, WorkspaceSlotOptionsContext, slotScreenOptions, } from "../../native/v5-workspace-context"; @@ -104,6 +111,7 @@ function ColumnScreen(props: { readonly screenKey?: string; readonly primary?: boolean; readonly attached?: boolean; + readonly animatesPush?: boolean; readonly selectedThreadKey?: string | null; readonly selectedPullRequestKey?: string | null; readonly onDismiss: (routeKey: string, native: boolean) => void; @@ -138,6 +146,7 @@ function ColumnScreen(props: { { props.onDismiss(key, event.nativeEvent.isNativeDismiss); }} @@ -265,6 +274,14 @@ function WorkspaceColumns( deviceType === "duo-unfolded" && selectedTab !== "pullRequests" && !settingsOpen ? openNewTask : undefined; + // Pages a hidden tab opens as it's shown belong to the tab, so they appear in place. + const headerOnly = use(NativeWorkspaceTabActivityContext)?.headerOnly === true; + const [shownPages, setShownPages] = useState({ headerOnly, keys: new Set() }); + if (shownPages.headerOnly !== headerOnly) + setShownPages({ + headerOnly, + keys: headerOnly ? new Set() : new Set(props.detail.map((route) => route.key)), + }); const inspector = use(NativeWorkspaceInspectorContext); const hideInspector = () => { if (inspector.visible) toggleAuxiliaryPane(); @@ -455,6 +472,7 @@ function WorkspaceColumns( screenKey={screenKey} descriptor={descriptor} attached={props.detail.some((current) => current.key === route.key)} + animatesPush={!shownPages.keys.has(route.key)} onDismiss={handleNativeDismiss} onAppearance={followCollapsedSplit} onCompose={isPullRequestRoute(route) ? undefined : detailCompose} @@ -538,7 +556,6 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean render: () => ( 0} hidden={ projection.detail.length > 0 && !primaryVisible && @@ -546,30 +563,45 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean (metrics?.verticalBarEdge ?? "none") === "none" } > - {(slotWorkspace) => - props.nativeColumns && - workspaceUsesColumns(slotWorkspace.state.selectedTab, slotWorkspace.settingsOpen) ? ( + {(slotWorkspace, headerOnly) => { + // A tab not shown yet renders the page opening it shows, under the key it opens with, + // so that page is already on screen in the tab when it's selected. + const tab = slotWorkspace.settingsOpen ? "settings" : slotWorkspace.state.selectedTab; + const page = headerOnly + ? (workspaceTabPage(props.state, tab, currentWorkspaceSelections(), { + columns: workspaceTabColumns(Platform.OS, tab, layout.usesSplitView), + check: workspaceSelectionCheck, + seedPullRequest: withKnownPullRequestSummary, + }) as Route | undefined) + : undefined; + const detail = headerOnly ? (page ? [page] : []) : projection.detail; + const slotDescriptors = + page && !descriptors[page.key] + ? { ...descriptors, [page.key]: props.describe(page, true) } + : descriptors; + return props.nativeColumns && + workspaceUsesColumns(slotWorkspace.state.selectedTab, slotWorkspace.settingsOpen) ? ( ) : ( - ) - } + ); + }} ), }; diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx index 1add35a9c3371..9d189ea9589ef 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceNativeTabs.ios.tsx @@ -13,12 +13,7 @@ import { type SetStateAction, } from "react"; import { View, useWindowDimensions, type NativeSyntheticEvent } from "react-native"; -import { - Tabs, - type TabSelectedEvent, - type TabSelectionPreventedEvent, - type TabSelectionRejectedEvent, -} from "react-native-screens"; +import { Tabs, type TabSelectedEvent, type TabSelectionRejectedEvent } from "react-native-screens"; import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; import type { NavigationTab } from "./navigation-tab-order"; @@ -51,11 +46,11 @@ function RetainedWorkspaceTab(props: { readonly slot: string; readonly tab: NavigationTab; readonly active: boolean; - /** Mount the header of a slot that hasn't been shown yet. */ + /** Render a slot that hasn't been shown yet: its header, and the page it opens with. */ readonly prewarm: boolean; readonly setMountedSlots: Dispatch>>; readonly setPrewarmRequests: Dispatch>>; - readonly children: (workspace: SlotWorkspace) => ReactNode; + readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode; }) { const workspace = useWorkspaceTabs()!; // Whether this slot is the visible one, read by cleanups after the switch has committed. @@ -66,12 +61,17 @@ function RetainedWorkspaceTab(props: { }, [props.active]); const isActive = () => activeRef.current; const [content, setContent] = useState( - props.active ? { workspace, children: props.children, headerOnly: false } : null, + props.active + ? { source: workspace, workspace, children: props.children, headerOnly: false } + : null, ); - if (props.active && (content?.workspace !== workspace || content?.children !== props.children)) - setContent({ workspace, children: props.children, headerOnly: false }); - else if (!props.active && props.prewarm && content === null) + const stale = content?.source !== workspace || content?.children !== props.children; + if (props.active && (content?.headerOnly !== false || stale)) + setContent({ source: workspace, workspace, children: props.children, headerOnly: false }); + // A slot not shown yet follows the workspace, so the page it opens with stays current. + else if (!props.active && props.prewarm && (content === null || (content.headerOnly && stale))) setContent({ + source: workspace, workspace: { ...workspace, settingsOpen: props.slot === "settings", @@ -95,24 +95,28 @@ function RetainedWorkspaceTab(props: { const mounted = content !== null && !content.headerOnly; const headerOnly = content?.headerOnly === true; const { slot, setMountedSlots, setPrewarmRequests } = props; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the slot's first native mount to the host, which holds the switch until then + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports the slot's mount to the host, which uncovers the tab then useEffect(() => { if (!mounted) return; - // The header options this mount wrote reach UIKit in the commit after it. + // Each header write commits in the render after it; the slot is ready once a frame passes + // without one, which is when its native header and content are in place. const frame = requestAnimationFrame(() => setMountedSlots((current) => (current.has(slot) ? current : new Set(current).add(slot))), ); - return () => { - cancelAnimationFrame(frame); - // A replacement slot (e.g. a re-enabled fourth tab) must report its own mount. + return () => cancelAnimationFrame(frame); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each header write re-arms the frame + }, [mounted, optionsByRoute, slot, setMountedSlots]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a replacement slot (e.g. a re-enabled fourth tab) must report its own mount + useEffect( + () => () => setMountedSlots((current) => { if (!current.has(slot)) return current; const next = new Set(current); next.delete(slot); return next; - }); - }; - }, [mounted, slot, setMountedSlots]); + }), + [slot, setMountedSlots], + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks UIKit to prewarm a hidden header after each write, since bar items it rebuilds fade in on their own first entry useEffect(() => { if (!headerOnly || optionsByRoute.size === 0) return; @@ -125,7 +129,7 @@ function RetainedWorkspaceTab(props: { - {content.children(content.workspace)} + {content.children(content.workspace, content.headerOnly)} @@ -136,12 +140,10 @@ type SlotWorkspace = NonNullable>; export function WorkspaceNativeTabs(props: { /** Renders a slot's tree for its own tab, which can lay out differently from the shown one. */ - readonly children: (workspace: SlotWorkspace) => ReactNode; + readonly children: (workspace: SlotWorkspace, headerOnly: boolean) => ReactNode; readonly hidden: boolean; /** The sidebar column draws the tabs itself, so they leave with it. */ readonly tabsInSidebarColumn?: boolean; - /** Every slot renders the pushed routes too, so prewarming waits until none are. */ - readonly detailOpen: boolean; }) { const workspace = useWorkspaceTabs()!; const order = useEnabledNavigationTabs(); @@ -167,12 +169,9 @@ export function WorkspaceNativeTabs(props: { const selectedSlot = workspace.settingsOpen ? -1 : primaryTabs.indexOf(selectedTab); const selectedScreenKey = selectedSlot === -1 ? "settings" : NATIVE_WORKSPACE_TAB_SLOTS[selectedSlot]!; - // A slot mounts its content the first time it's selected. Showing it in that same commit - // shows a blank controller, then its header animates in, so the switch waits for the mount. + // A slot renders its body the first time it's selected. Until it has, UIKit keeps the last + // tab's snapshot over it, so the switch never shows a half-built tab. const [mountedSlots, setMountedSlots] = useState>(() => new Set()); - const [shownScreenKey, setShownScreenKey] = useState(selectedScreenKey); - if (shownScreenKey !== selectedScreenKey && mountedSlots.has(selectedScreenKey)) - setShownScreenKey(selectedScreenKey); // Once the first tab is up, the others mount their headers for UIKit to put in the window // once: iOS 26 fades bar items in the first time they enter it, which a first visit would show. const [prewarm, setPrewarm] = useState(false); @@ -191,14 +190,14 @@ export function WorkspaceNativeTabs(props: { const [prewarmRequests, setPrewarmRequests] = useState>( () => new Map(), ); - const prewarmReady = mountedSlots.size > 0 && !props.detailOpen; + const prewarmReady = mountedSlots.size > 0; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- waits for the JS thread to go idle after the first tab mounts useEffect(() => { if (!prewarmReady || prewarm) return; const handle = requestIdleCallback(() => setPrewarm(true), { timeout: 2_000 }); return () => cancelIdleCallback(handle); }, [prewarmReady, prewarm]); - const request = { selectedScreenKey: shownScreenKey, baseProvenance: provenance }; + const request = { selectedScreenKey, baseProvenance: provenance }; return ( @@ -215,12 +214,6 @@ export function WorkspaceNativeTabs(props: { }: NativeSyntheticEvent) => setProvenance(nativeEvent.provenance) } - onTabSelectionPrevented={({ - nativeEvent, - }: NativeSyntheticEvent) => { - const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.preventedScreenKey); - if (tab) selectTab(tab); - }} onTabSelected={({ nativeEvent }: NativeSyntheticEvent) => { setProvenance(nativeEvent.provenance); if (nativeEvent.actionOrigin === "programmatic-js") return; @@ -237,12 +230,11 @@ export function WorkspaceNativeTabs(props: { // Stable slot controllers keep UIKit's stacks attached when a section moves into Settings. key={slot} screenKey={slot} - // Taps on an unmounted slot select it from JS, which shows it once it has mounted. - preventNativeSelection={!mountedSlots.has(slot) && slot !== shownScreenKey} title="" tabBarItemAccessibilityLabel={settings ? "Settings" : WORKSPACE_TAB_LABELS[tab]} ios={{ prewarmRequest: prewarmRequests.get(slot) ?? 0, + contentReady: mountedSlots.has(slot), icon: settings ? { type: "sfSymbol", name: "gearshape" } : tab === "pullRequests" diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx index e9e7bc09f0b64..e96bf422842e7 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.tsx @@ -123,7 +123,6 @@ function WorkspaceRootContent() { optionsVersion={[ settingsOpen, state.selectedTab, - state.selectionRevision, width, sidebarNavigation, enabled.length, diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts index 3cd3fe6d0978f..b7ee8cb2f6094 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts @@ -6,6 +6,7 @@ import { workspaceSelectionsIn, workspaceTabColumns, workspaceTabNavigationState, + workspaceTabPage, } from "./workspace-tab-navigation"; const home = { key: "home", name: "Home" }; @@ -118,6 +119,12 @@ describe("opening a workspace tab", () => { workspaceTabNavigationState(state, "settings", { settings: "SettingsMicrophone" }, columns), ), ).toEqual(["Home", "Settings", "SettingsVoice"]); + // A hidden tab renders its page under the key that opening the tab later uses. + for (const tab of ["pullRequests", "settings"] as const) { + expect(workspaceTabNavigationState(state, tab, selections, columns).routes.at(-1)?.key).toBe( + workspaceTabPage(state, tab, selections, columns)?.key, + ); + } }); it("keeps the route that is already open, so re-selecting a tab doesn't rebuild it", () => { diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts index 6a44e617e53ed..704e47d2b9168 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.ts @@ -146,6 +146,13 @@ function keyed(route: Route): Route & { readonly key: s return { ...route, key: `${route.name}-workspace-${routeKeys}` }; } +// A hidden tab renders the page it would open under this key, so opening it reuses that screen. +function keyedPage(route: Route): Route & { readonly key: string } { + return route.key === undefined + ? { ...route, key: `${route.name}-workspace-page` } + : (route as Route & { readonly key: string }); +} + function detailRoute( state: { readonly routes: readonly RouteLike[] }, tab: "threads" | "pullRequests", @@ -222,7 +229,12 @@ export function workspaceTabNavigationState< undefined, page === selections.settings ? selections.settingsKey : undefined, ); - const routes = [...settings.routes.map(keyed), ...overlays]; + const [home, list, current] = settings.routes; + const routes = [ + ...[home!, list!].map(keyed), + ...(current ? [keyedPage(current)] : []), + ...overlays, + ]; return { ...settings, index: routes.length - 1, routes }; } const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" }; @@ -230,6 +242,23 @@ export function workspaceTabNavigationState< options.columns && tab !== "usage" ? detailRoute(state, tab, selections, options.check, options.seedPullRequest) : undefined; - const routes = [...[home, ...(detail ? [detail] : [])].map(keyed), ...overlays]; + const routes = [keyed(home), ...(detail ? [keyedPage(detail)] : []), ...overlays]; return { ...state, index: routes.length - 1, routes }; } + +/** The page opening `tab` would show beside its list, which the hidden tab renders ahead. */ +export function workspaceTabPage( + state: { readonly routes: readonly RouteLike[] }, + tab: WorkspaceTab | "settings", + selections: WorkspaceSelections, + options: { + readonly columns: boolean; + readonly check: WorkspaceSelectionCheck; + readonly seedPullRequest?: (identity: Omit) => object; + }, +) { + const page = workspaceTabNavigationState(state, tab, selections, options).routes.find( + (route) => route.name !== "Home" && route.name !== "Settings", + ); + return page?.key === undefined ? undefined : { ...page, key: page.key }; +} diff --git a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx index 096513c0e0a3c..96f4cedb9bd88 100644 --- a/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsAboutRouteScreen.tsx @@ -1,5 +1,6 @@ import * as Dialog from "../../components/ui/Dialog"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; +import * as Application from "expo-application"; import Constants from "expo-constants"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; import { useRef, useState } from "react"; @@ -53,7 +54,10 @@ function AppSettingsSection() { // Match app.config.ts's production fallback to avoid mislabeling builds as development. const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production"; const variantLabel = variant === "production" ? "" : capitalize(variant); - const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version; + // EAS assigns build numbers remotely; only the installed binary knows its own. + const build = Application.nativeBuildVersion; + const versionWithBuild = build ? `${version} (${build})` : version; + const versionLabel = variantLabel ? `${versionWithBuild} · ${variantLabel}` : versionWithBuild; const updateCheckAvailable = isAppUpdateCheckAvailable(); const busy = updateState === "checking" || updateState === "downloading" || updateState === "restarting"; diff --git a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx index cb0ecbb6d8c01..99c442e144cfb 100644 --- a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx @@ -8,9 +8,36 @@ import { SYSTEM_LANGUAGE, nativeLanguageName } from "@t3tools/client-runtime/loc import { SUPPORTED_LOCALES } from "../../i18n/locales"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; +import { SettingsRow } from "./components/SettingsRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsScreen } from "./components/SettingsScreen"; +/** General's row that opens the language picker, showing the current choice. */ +export function LanguageSettingsSection() { + return ( + + + + ); +} + +function LanguageRow() { + const gt = useGT(); + const language = useLanguagePreference(); + return ( + + + + ); +} + export function SettingsLanguageRouteScreen() { return ( diff --git a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx index 9d49650e1a67a..d374727fd4b3a 100644 --- a/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProjectGroupingRouteScreen.tsx @@ -12,6 +12,7 @@ import { import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsSection } from "./components/SettingsSection"; +import { LanguageSettingsSection } from "./SettingsLanguageRouteScreen"; import { NewThreadSettingsSection, WorkingSectionSettings } from "./ThreadSettingsSections"; const GROUPING_OPTIONS: ReadonlyArray<{ @@ -54,6 +55,7 @@ export function SettingsProjectGroupingRouteScreen() { contentContainerClassName="gap-3 px-5 pt-4" contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }} > + {GROUPING_OPTIONS.map((option, index) => ( group.key === selectedProjectKey); @@ -273,11 +270,6 @@ function useSettingsIndexSections(): SettingsListSection[] { rows: [ page("SettingsOrganization", "gearshape", gt("General")), page("SettingsAppearance", "paintbrush", gt("Appearance")), - page("SettingsLanguage", "globe", gt("Language"), { - value: SUPPORTED_LOCALES.includes(language) - ? nativeLanguageName(language) - : gt("System default"), - }), page("SettingsFollowUp", "bubble.left.and.bubble.right", gt("Chat")), ...(navigationCustomizationAvailable() ? [page("SettingsNavigation", "line.3.horizontal", gt("Navigation tabs"))] diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 49e1a8dbe082e..77fbdfd7be975 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -33,7 +33,6 @@ const SETTINGS_SEARCH_TERMS = { "zen", "final answers only", ], - SettingsLanguage: ["language", "locale", "translation", "english"], SettingsNavigation: ["tabs", "tab order", "reorder", "hide tabs"], SettingsKeyboard: ["return key", "send message", "new line", "hardware keyboard"], SettingsVoice: [ @@ -53,6 +52,10 @@ const SETTINGS_SEARCH_TERMS = { SettingsScheduledTasks: ["automations", "schedule", "cron", "recurring", "webhook"], SettingsProjectOverview: ["project", "overview", "checkouts", "delete project"], SettingsOrganization: [ + "language", + "locale", + "translation", + "english", "project grouping", "group projects", "organization", diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 1153ad498b88a..27551a83afa41 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -148,7 +148,11 @@ function collapsedEditorInset(text: ScaledTextRole): number { return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); } -function useCompactComposerEditor(text: ScaledTextRole, value: string) { +const EXPANDED_EDITOR_INSET = 14; +// Room under the expanded editor for the toolbar row. +const EXPANDED_EDITOR_BOTTOM = 52; + +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; @@ -169,27 +173,55 @@ function useCompactComposerEditor(text: ScaledTextRole, value: string) { (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 editorStyle = useAnimatedStyle(() => ({ - 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, - ...(isExpanded - ? { left: 14, right: 14 } - : compactEditorInsets({ - slotX: editorX.value, - slotWidth: editorWidth.value, - rowWidth: rowWidth.value, - isRTL, - })), - // The full-width editor must move above the controls in the same frame it widens. - bottom: isExpanded ? 52 : (compactRowHeight - minimum) / 2, + 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: { height: isExpanded ? height + 52 : compactRowHeight }, + 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); @@ -623,7 +655,12 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const surfacePaddingVertical = usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2; const [compactRowWidth, setCompactRowWidth] = useState(0); const compactAttachmentLimit = compactRowWidth >= 500 ? 3 : 1; - const compactEditor = useCompactComposerEditor(bodyText, draftMessage); + // Animate only while typing; a thread switch or restored draft lands in place. + const compactEditor = useCompactComposerEditor( + bodyText, + draftMessage, + Platform.OS === "ios" && isFocused, + ); const showsCompactDictation = isVoiceInputPresented; const isToolbarVisible = isVoiceInputPresented; const hasEditingAttachments = @@ -1145,8 +1182,14 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps compactEditor.isExpanded ? { flex: 1, justifyContent: "flex-end" } : undefined } > - {compactControl} - {modelControl} + + {compactControl} + {modelControl} + {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- The Android sidebar has no native header to register with. */} { update: { sessionUpdate, messageId, content: { type: "text", text } }, }); - yield* replay("user_message_chunk", "u1", "hel"); - yield* replay("user_message_chunk", "u1", "lo"); + yield* replay("user_message_chunk", "u1", " is "); + yield* replay("user_message_chunk", "u1", "XML"); yield* replay("agent_message_chunk", "a1", "hi"); yield* replay("user_message_chunk", "u2", "next"); yield* replay("agent_message_chunk", "a1", " "); yield* replay("agent_message_chunk", "a1", "there"); yield* replay("agent_message_chunk", "a3", "\t"); - yield* replay("agent_message_chunk", "a3", "code"); + yield* replay("agent_message_chunk", "a3", "code with "); yield* replay("agent_message_chunk", "a4", "\n\n"); + yield* replay("user_message_chunk", "u3", "Why did Monitor 0123abcd ended appear?"); + // Grok's injected monitor wakes replay as user chunks and stay out of history. + yield* replay( + "user_message_chunk", + "u4", + '\n\nline\n', + ); + yield* replay( + "user_message_chunk", + "u5", + 'Monitor "019f44a5-87d1-7640-8e35-6a4667ffc873" ended: exit 0', + ); const first = yield* runtime.readThreadSnapshot({ providerThread }); yield* replay("agent_message_chunk", "a2", "done"); yield* replay("user_message_chunk", "u2", "\n"); yield* replay("user_message_chunk", "u2", "\tone"); + yield* sessionUpdateHandler({ + sessionId: "mock-child-session", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Child private work" }, + }, + }); const second = yield* runtime.readThreadSnapshot({ providerThread }); const texts = (snapshot: typeof first) => snapshot.messages.map((message) => `${message.role}:${message.text}`); assert.deepEqual(texts(first), [ - "user:hello", + "user: is XML", "assistant:hi there", "user:next", - "assistant:\tcode", + "assistant:\tcode with ", + "user:Why did Monitor 0123abcd ended appear?", ]); assert.deepEqual(texts(second), [ - "user:hello", + "user: is XML", "assistant:hi there", "user:next\n\tone", - "assistant:\tcode", + "assistant:\tcode with ", + "user:Why did Monitor 0123abcd ended appear?", "assistant:done", ]); }).pipe(Effect.provide(layerTest), Effect.scoped), @@ -4682,6 +4703,11 @@ describe("AcpAdapterV2", () => { const startupMethods = yield* pollProtocolMethods(protocolEvents); assert.include(startupMethods, "session/resume"); assert.notInclude(startupMethods, "session/new"); + const loaded = yield* runtime.readThreadSnapshot({ providerThread }); + assert.deepEqual( + loaded.messages.map((message) => `${message.role}:${message.text}`), + ["user:replay"], + ); yield* runtime.resumeThread({ providerThread, modelSelection, runtimePolicy }); assert.notInclude(yield* pollProtocolMethods(protocolEvents), "session/resume"); @@ -5207,28 +5233,35 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); - it.effect.each([false, true])( - "ends a running tool call when its agent process exits mid-prompt (followAgentWorkState: %s)", - (followAgentWorkState) => + it.effect.each( + [false, true].flatMap((followAgentWorkState) => [ + { ending: "agent process exits mid-prompt", followAgentWorkState }, + { ending: "prompt returns an RPC error", followAgentWorkState }, + ]), + )( + "ends an open tool call when its $ending (followAgentWorkState: $followAgentWorkState)", + ({ ending, followAgentWorkState }) => Effect.gen(function* () { + const agentExits = ending === "agent process exits mid-prompt"; const harness = yield* makePromptInactivityHarness({ followAgentWorkState, environment: (runtimeOrdinal) => - runtimeOrdinal === 1 ? { T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG: "execute" } : {}, + runtimeOrdinal === 1 + ? { + T3_ACP_EMIT_TRACKED_TOOL_CALL_KIND_THEN_HANG: "execute", + ...(agentExits ? {} : { T3_ACP_FAIL_PROMPT: "1" }), + } + : {}, }); yield* harness.startTurn(1); - let exited = false; - const statuses = yield* harness.runtime.events.pipe( + let exited = !agentExits; + const events = yield* harness.runtime.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tracked-tool-call" - ? Stream.make(event.turnItem.status) - : Stream.empty, - ), // The agent dies while its tool call is open. - Stream.tap(() => - exited + Stream.tap((event) => + exited || + event.type !== "turn_item.updated" || + event.turnItem.nativeItemRef?.nativeId !== "tracked-tool-call" ? Effect.void : Effect.sync(() => (exited = true)).pipe( Effect.andThen(harness.natives[0]!.notify("_test/exit", {})), @@ -5237,8 +5270,16 @@ describe("AcpAdapterV2", () => { Stream.runCollect, Effect.map((collected) => Array.from(collected)), ); - // regression: #37368 the dead agent's tool call stayed open in the failed turn. - assert.include(["failed", "interrupted", "cancelled"], statuses.at(-1)); + const toolStatuses = events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "tracked-tool-call" + ? [event.turnItem.status] + : [], + ); + // regression: #37368 the tool call stayed open in the failed turn. + assert.equal(toolStatuses.at(-1), "failed"); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : undefined, "failed"); }).pipe(Effect.provide(layerTest)), ); @@ -11174,4 +11215,17 @@ describe("acpPostSettleContinuationOfferEvidence", () => { }), ); }); + it("offers on a reply that only mentions monitor markup, not on monitor chatter", () => { + const reply = (text: string) => + ({ + sessionId, + update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }, + }) as const; + assert.isTrue(acpPostSettleContinuationOfferEvidence(reply(" tags wrap it"))); + assert.isFalse( + acpPostSettleContinuationOfferEvidence( + reply('line'), + ), + ); + }); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index b9e2f977a36ee..1d549d7f2c18b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -14087,6 +14087,50 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("resumes in a fresh session after Claude Code reports its conversation gone", () => + Effect.gen(function* () { + const harness = yield* openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame( + "claude-query-conversation-missing", + Stream.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "fromAsyncIterable", + cause: new ClaudeAdapterV2.ClaudeConversationNotFoundError({ + cause: new Error("Claude Code process exited with code 1"), + }), + }), + ), + ); + const turnInput = harness.turnInput("a", 1); + const started = yield* harness.runtime.startTurn(turnInput).pipe(Effect.exit); + assert.isTrue(Exit.isFailure(started)); + if (Exit.isFailure(started)) { + assert.include( + makeProviderFailure({ cause: started.cause, class: "transport_error" }).message, + "could not find this conversation", + ); + } + // A failed resume is what sends the next turn to a fresh native session. + const resumed = yield* harness.runtime + .resumeThread({ + providerThread: turnInput.providerThread, + threadId: turnInput.threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + }) + .pipe(Effect.exit); + assert.isTrue(Exit.isFailure(resumed)); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("fails a turn whose Claude query ends before its first frame", () => Effect.gen(function* () { const harness = yield* openAdapterWhoseFirstQueryEndsBeforeItsFirstFrame( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 996501e885849..5dcb77f7abddc 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -383,6 +383,8 @@ const CLAUDE_DESCENDANT_POLL = "1 second"; // Claude Code's refusal of bypassPermissions as root, which it explains only on stderr. const CLAUDE_ROOT_REFUSAL = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; +// Claude Code's answer to a --resume whose session store is gone, as a result error and on stderr. +const CLAUDE_CONVERSATION_NOT_FOUND = "No conversation found with session ID:"; // fd 4 gates the launch until the server has recorded the process it is about to become. // The shell enters the cwd itself: as a native cwd, a mount that hangs chdir freezes the server. @@ -725,6 +727,17 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError()( + "ClaudeConversationNotFoundError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Claude Code could not find this conversation to resume. Send the message again to continue in a new Claude session with this thread's history."; + } +} + class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError()( "ClaudeMcpRegistrationTimeoutError", { phase: Schema.Literals(["initialize", "setMcpServers"]) }, @@ -821,6 +834,14 @@ export interface ClaudeAgentSdkSubagentLookupInput { } const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError); + +const isClaudeConversationNotFound = (cause: Cause.Cause) => { + const error = Cause.squash(cause); + return ( + isClaudeAgentSdkQueryRunnerError(error) && + Predicate.isTagged(error.cause, "ClaudeConversationNotFoundError") + ); +}; const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError); const isProviderAdapterRuntimeRequestResponseError = Schema.is( ProviderAdapter.ProviderAdapterRuntimeRequestResponseError, @@ -1517,6 +1538,7 @@ export const layerQueryRunner: Layer.Layer< let stderrTail = ""; let stderrClosed: Promise = Promise.resolve(); let answered = false; + let conversationMissing = false; const appendStderr = (text: string) => { if (answered) return; stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); @@ -1695,15 +1717,27 @@ export const layerQueryRunner: Layer.Layer< } const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL); return yield* queryRunnerError( - refusedRoot ? new ClaudeCodeRootRefusalError({ cause }) : cause, + refusedRoot + ? new ClaudeCodeRootRefusalError({ cause }) + : conversationMissing || + (!answered && stderrTail.includes(CLAUDE_CONVERSATION_NOT_FOUND)) + ? new ClaudeConversationNotFoundError({ cause }) + : cause, "fromAsyncIterable", ); }), ), ), - Stream.tap(() => + Stream.tap((message) => Effect.sync(() => { answered = true; + if ( + message.type === "result" && + message.subtype !== "success" && + message.errors.some((error) => error.startsWith(CLAUDE_CONVERSATION_NOT_FOUND)) + ) { + conversationMissing = true; + } }), ), Stream.tap((message) => @@ -5843,6 +5877,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); }); const openedNativeThreads = yield* Ref.make(new Set()); + // Sessions Claude Code reported gone on resume; resumeThread fails them into a fresh session. + const missingNativeThreads = new Set(); const pdfBudgets = new Map>(); const latestPlanByKind = yield* Ref.make(new Map()); // Claude 5 task tools edit one list per native session, across turns. @@ -12910,7 +12946,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.exit, Effect.flatMap( Effect.fnUntraced(function* (exit: ClaudeQueryStreamExit) { - if (exit._tag === "Failure") context.exitCause = exit.cause; + if (exit._tag === "Failure") { + context.exitCause = exit.cause; + if (isClaudeConversationNotFound(exit.cause)) { + missingNativeThreads.add(context.nativeThreadId); + } + } const heldContext = yield* Ref.get(activeTurn); if ( (yield* Ref.get(queryContext))?.query === querySession && @@ -13877,6 +13918,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // A live process holds the conversation even before saving it. (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId ) { + if (missingNativeThreads.has(nativeThreadId)) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Claude Code has no conversation ${nativeThreadId} to resume.`, + }); + } // An unreadable transcript leaves the resume to the CLI. const transcript = yield* claudeTranscriptState(nativeThreadId).pipe( Effect.orElseSucceed(() => "missing" as const), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 4a87c04043029..28072c29d7fda 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -710,6 +710,49 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro const unknown = yield* startupFailureMessage("token=sk-private-123"); assert.notInclude(unknown, "sk-private-123"); + + const missingConversation = yield* startupFailureMessage( + "No conversation found with session ID: sk-private-123", + ); + assert.include(missingConversation, "could not find this conversation"); + assert.notInclude(missingConversation, "sk-private-123"); + }).pipe(Effect.provide(realQueryRunner)), + ); + + // What Claude Code writes when the session store behind --resume is gone. + it.effect("names a resumed conversation Claude Code cannot find", () => + Effect.gen(function* () { + const missing = "No conversation found with session ID: native-session-fake-cli"; + const result = JSON.stringify({ + type: "result", + subtype: "error_during_execution", + is_error: true, + num_turns: 0, + duration_ms: 0, + duration_api_ms: 0, + total_cost_usd: 0, + usage: {}, + modelUsage: {}, + permission_denials: [], + errors: [missing], + session_id: "native-session-fake-cli", + uuid: "00000000-0000-4000-8000-000000000000", + }); + const cli = fakeClaudeCli( + `printf '%s\\n' '${result}'\nprintf '%s\\n' '${missing}' >&2\nexit 1`, + ); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(NodePath.dirname(cli), { recursive: true, force: true })), + ); + const session = yield* openFakeCli(cli); + const exit = yield* Stream.runDrain(session.messages).pipe(Effect.exit); + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) { + assert.include( + makeProviderFailure({ cause: exit.cause, class: "transport_error" }).message, + "could not find this conversation", + ); + } }).pipe(Effect.provide(realQueryRunner)), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 919784509bf09..69375c34a2a66 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -459,7 +459,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly hasPendingBackgroundWorkForThread?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; - readonly startTurn?: Effect.Effect; + readonly startTurn?: Effect.Effect; readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly unloads?: Queue.Queue; @@ -641,7 +641,7 @@ function layerTest(input: { readonly hasPendingBackgroundWorkForThread?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; - readonly startTurn?: Effect.Effect; + readonly startTurn?: Effect.Effect; readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly unloads?: Queue.Queue; @@ -1634,6 +1634,86 @@ it.effect("ProviderSessionManagerV2 gives up on a provider that never confirms a }), ); +// A failed start can leave its native thread gone, as when Claude rejects a resume. +it.effect("ProviderSessionManagerV2 resumes a thread natively again after its start failed", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-failed-start-resume"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-${threadId}`, + }); + const resume = runtime.resumeThread({ + providerThread, + threadId, + modelSelection, + runtimePolicy, + }); + yield* resume; + yield* resume; + assert.equal((yield* Ref.get(state)).resumeCount, 1); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + yield* runtime + .startTurn({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }), + text: "turn", + attachments: [], + }, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + yield* resume; + assert.equal((yield* Ref.get(state)).resumeCount, 2); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 60_000, + startTurn: Effect.fail( + new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CODEX_DRIVER, + detail: "query ended before the turn could start", + }), + ), + }), + ), + ); + }), +); + it.effect("ProviderSessionManagerV2 still idles out a session releaseUnlessBusy kept", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 8e4c381bc8b9a..ba9ba7a2bd3f3 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -1683,6 +1683,25 @@ export const layerWithOptions = ( ), ); + const forgetProviderThreadLoaded = (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; + }) => + Ref.update(sessions, (current) => { + const key = sessionKey(input.providerSessionId); + const entry = current.get(key); + if ( + entry?.runtime !== input.runtime || + !entry.loadedProviderThreadKeyByThread.has(input.threadId) + ) { + return current; + } + const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); + loadedProviderThreadKeyByThread.delete(input.threadId); + return new Map(current).set(key, { ...entry, loadedProviderThreadKeyByThread }); + }); + /** Pass the setting read before a native load; cache hits keep the earlier record. */ const markProviderThreadLoaded = (input: { readonly providerSessionId: ProviderSessionId; @@ -2494,6 +2513,16 @@ export const layerWithOptions = ( ? observeActivity( providerSessionId, markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), + ).pipe( + // A failed start can leave its native thread gone (Claude rejecting a + // resume), so the next start must ask the adapter to resume it again. + Effect.andThen( + forgetProviderThreadLoaded({ + providerSessionId, + threadId: input.threadId, + runtime, + }), + ), ) : Effect.void, ), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index c3a6ad0a0ad03..c9316bd231fc1 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -2886,6 +2886,43 @@ it.effect("tells the thread when its worktree branch could not be renamed", () = }), ); +it.effect("starts the agent on the temporary branch when branch naming hangs", () => + Effect.gen(function* () { + const branchNameStarted = yield* Deferred.make(); + const harness = makeHarness({ + // A rate-limited provider retries until the CLI's own timeout, minutes later. + generateBranchName: () => + Deferred.succeed(branchNameStarted, undefined).pipe(Effect.andThen(Effect.never)), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; + const threads = yield* ThreadManagement.ThreadManagementService; + const launched = yield* launches.launch( + launchInput({ + command: "launch:rename-hangs", + thread: "thread:rename-hangs", + message: "Start", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + yield* Deferred.await(branchNameStarted); + yield* TestClock.adjust("20 seconds"); + yield* tracker.stream(launched.threadId).pipe( + Stream.filter((snapshot) => snapshot?.phase === "done"), + Stream.runHead, + ); + assert.equal(harness.renameBranch.mock.calls.length, 0); + const projection = yield* threads.getThreadProjection(launched.threadId); + const notice = projection.turnItems.find((item) => item.type === "system_notice"); + assert.include( + notice?.type === "system_notice" ? notice.message : "", + `stays ${projection.thread.branch}. Text generation failed in generateBranchName: Timed out after 20 seconds.`, + ); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect("reports submodule downloads as their own setup step", () => Effect.gen(function* () { const progressReady = @@ -3020,6 +3057,62 @@ it.effect.each([0, 1])("releases an async setup before its completion with exit }), ); +it.effect("shows an async setup as done while the agent still waits for its branch name", () => + Effect.gen(function* () { + const branchNameStarted = yield* Deferred.make(); + const allowBranchName = yield* Deferred.make(); + const harness = makeHarness({ + runSetup: () => + Effect.succeed({ + status: "started" as const, + async: true, + scriptId: "setup", + scriptName: "Setup", + scriptCommand: "vp install", + terminalId: "setup", + cwd: "/repo-worktrees/feature", + completion: Effect.succeed({ exitCode: 0, durationMs: 1 }), + }), + generateBranchName: () => + Deferred.succeed(branchNameStarted, undefined).pipe( + Effect.andThen(Deferred.await(allowBranchName)), + Effect.as({ branch: "generated-branch" }), + ), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker; + const launched = yield* launches.launch( + launchInput({ + command: "launch:async-setup-before-name", + thread: "thread:async-setup-before-name", + message: "Start", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + yield* Deferred.await(branchNameStarted); + const snapshot = yield* tracker.stream(launched.threadId).pipe( + Stream.filter( + (current) => + current?.stages.some( + (stage) => + (stage.id === "setup-script" && + (stage.status === "done" || stage.status === "failed")) || + (stage.id === "agent" && stage.status === "done"), + ) === true, + ), + Stream.runHead, + ); + const stages = Option.getOrUndefined(snapshot)?.stages ?? []; + const setupStage = stages.find((stage) => stage.id === "setup-script"); + assert.equal(setupStage?.status, "done"); + assert.isNotNull(setupStage?.endedAt ?? null); + assert.notEqual(stages.find((stage) => stage.id === "agent")?.status, "done"); + yield* Deferred.succeed(allowBranchName, undefined); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect.each(["origin/master", ":/initial"])( "refuses a worktree in a non-Git project before checking base %s", (baseRef) => diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index d46f5e2d41514..eb452b883d761 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -19,6 +19,7 @@ import { type RunId, type RuntimeMode, type ScheduledTaskId, + TextGenerationError, ThreadId, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -59,6 +60,9 @@ import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid"; import { DispatchModeLimit } from "./DispatchModeLimit.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; +// The agent waits for its branch name; a rate-limited provider would hold it for minutes. +const BRANCH_NAME_TIMEOUT = "20 seconds"; + export type ThreadLaunchWorkspaceStrategy = | { readonly type: "root"; readonly branch?: string | undefined } | { @@ -569,6 +573,16 @@ const make = Effect.gen(function* () { projectId: input.projectId, }) .pipe( + Effect.timeoutOrElse({ + duration: BRANCH_NAME_TIMEOUT, + orElse: () => + Effect.fail( + new TextGenerationError({ + operation: "generateBranchName", + detail: `Timed out after ${BRANCH_NAME_TIMEOUT}.`, + }), + ), + }), Effect.map((result) => ({ branch: result.branch, exactName: settings.branchNamingMode === "custom", @@ -946,10 +960,12 @@ const make = Effect.gen(function* () { if (setup.completion) { const awaitCompletion = Effect.gen(function* () { const completion = yield* setup.completion!; - yield* setupTracker.stage(threadId, "setup-script", { - status: completion.exitCode === 0 ? "done" : "failed", - detail: `exited with ${completion.exitCode ?? "no exit code"}`, - }); + yield* setupTracker.stageStatus( + threadId, + "setup-script", + completion.exitCode === 0 ? "done" : "failed", + `exited with ${completion.exitCode ?? "no exit code"}`, + ); if (completion.exitCode !== 0 && !setup.async) return yield* mapError( input, @@ -958,14 +974,19 @@ const make = Effect.gen(function* () { )(`Setup script exited with ${completion.exitCode ?? "no exit code"}.`); }); if (setup.async) { - awaitAsyncSetup = awaitCompletion.pipe( + // Record the result when the script ends, not after the agent starts. + const asyncSetup = yield* awaitCompletion.pipe( Effect.catchCause((cause) => - setupTracker.stage(threadId, "setup-script", { - status: "failed", - detail: failureDetail(Cause.squash(cause)), - }), + setupTracker.stageStatus( + threadId, + "setup-script", + "failed", + failureDetail(Cause.squash(cause)), + ), ), + Effect.forkChild, ); + awaitAsyncSetup = Fiber.join(asyncSetup); } else { yield* awaitCompletion; } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/output.ts index 3726fda9f9318..a765e75bb1983 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/output.ts @@ -48,7 +48,7 @@ export function assertPiCompactionOutput( result, transcript, runCount: 6, - runStatuses: ["completed", "completed", "completed", "completed", "completed", "completed"], + runStatuses: ["completed", "failed", "completed", "completed", "completed", "completed"], }); const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson index c7cdd0173ed88..f0f24c77d3dda 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/pi_compaction/pi_transcript.ndjson @@ -51,9 +51,7 @@ {"type":"emit_inbound","label":"compaction_end","frame":{"type":"compaction_end","reason":"manual","aborted":false,"willRetry":false,"errorMessage":"Compaction failed: Nothing to compact (session too small)"}} {"type":"emit_inbound","label":"response:compact","frame":{"type":"response","command":"compact","success":false,"error":"Nothing to compact (session too small)"}} {"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-9"}} -{"type":"expect_outbound","label":"get_state","frame":{"type":"get_state","id":"t3-10"}} {"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-9","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} -{"type":"emit_inbound","label":"response:get_state","frame":{"id":"t3-10","type":"response","command":"get_state","success":true,"data":{"model":{"type":"chat","id":"deepseek/deepseek-v4-flash","name":"DeepSeek: DeepSeek V4 Flash 0423","api":"openai-completions","baseUrl":"https://openrouter.ai/api/v1","provider":"openrouter","reasoning":true,"thinkingLevelMap":{"off":"none","minimal":null,"low":null,"medium":null,"high":"high","xhigh":"xhigh","max":null},"input":["text"],"cost":{"input":0.04186,"output":0.08372,"cacheRead":0.008372,"cacheWrite":0},"contextWindow":1048576,"maxTokens":131072,"compat":{"supportsDeveloperRole":false,"thinkingFormat":"openrouter","supportsStrictMode":true,"sendSessionAffinityHeaders":true,"requiresReasoningContentOnAssistantMessages":true}},"thinkingLevel":"high","isStreaming":false,"isCompacting":false,"steeringMode":"one-at-a-time","followUpMode":"one-at-a-time","sessionFile":"/pi-sessions/session-1.jsonl","sessionId":"00000000-0000-4000-8000-000000000002","sessionName":"Replay fixture: pi_compaction","autoCompactionEnabled":true,"messageCount":3,"pendingMessageCount":0}}} {"type":"expect_outbound","label":"get_entries","frame":{"type":"get_entries","since":"9923aaa9","id":"t3-11"}} {"type":"emit_inbound","label":"response:get_entries","frame":{"id":"t3-11","type":"response","command":"get_entries","success":true,"data":{"entries":[],"leafId":"9923aaa9"}}} {"type":"expect_outbound","label":"get_session_stats","frame":{"type":"get_session_stats","id":"t3-12"}} diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index 64705e4bbb8f5..03fcb9cad6e66 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -69,12 +69,18 @@ describe("runMigrations", () => { }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); - it.effect("upgrades a database at exactly 54", () => + it.effect("upgrades a database at exactly 54, then rechecks it without a write lock", () => Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; yield* runMigrations({ toMigrationInclusive: 54 }); assert.deepStrictEqual(yield* runMigrations(), v2Migrations); assert.deepStrictEqual(yield* history, migrationManifest); assert.isAbove(yield* v2TableCount, 0); + + // query_only rejects BEGIN IMMEDIATE, which CLI startup would otherwise take on the live database. + yield* sql`PRAGMA query_only = ON`; + assert.deepStrictEqual(yield* runMigrations(), []); + assert.deepStrictEqual(yield* history, migrationManifest); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 92cfe02df3cc5..55c2f67c8c4aa 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -290,10 +290,12 @@ export const runMigrations = Effect.fn("runMigrations")(function* ({ toMigrationInclusive, }: RunMigrationsOptions = {}) { // The desktop waits past its readiness budget until the finished line follows this one. - if (yield* hasPendingMigrations()) yield* Effect.log(DATABASE_MIGRATIONS_STARTED_MESSAGE); + const hasPending = yield* hasPendingMigrations(); + if (hasPending) yield* Effect.log(DATABASE_MIGRATIONS_STARTED_MESSAGE); const includesV2 = toMigrationInclusive === undefined || toMigrationInclusive >= FIRST_V2_MIGRATION_ID; - const previewMigrations = includesV2 ? yield* reconcileV2PreviewMigration() : []; + // The reconcile takes the write lock; CLI startup must not contend with the server for a no-op. + const previewMigrations = includesV2 && hasPending ? yield* reconcileV2PreviewMigration() : []; if (includesV2) { yield* assertV2MigrationsCanRun(toMigrationInclusive); } diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index d2e165ea3b2b5..84b7a9151e062 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -188,7 +188,7 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { withFakeClaudeEnv( { output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }), - stdinMustContain: "Additional instructions:\nUse two to four words.", + stdinMustContain: "Title instructions from the user:\nUse two to four words.", }, (textGeneration) => textGeneration.generateThreadTitle({ diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 3bb70c8b609eb..a6f2a2fa541a5 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -32,6 +32,7 @@ import { isDefaultCopiedFile, } from "../lib/addProjectToMachine"; import { formatBytes } from "../lib/formatBytes"; +import { seedDraftModelSelection } from "../lib/seedDraftModelSelection"; import { newProjectId } from "../lib/utils"; import { readProject, subscribeProject, useProject } from "../state/entities"; import { useEnvironments } from "../state/environments"; @@ -201,6 +202,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe environmentSelection: "manual", loadBalancedEnvironmentId: null, }); + seedDraftModelSelection(draftId, targetRef); return; } void handleNewThread(targetRef); 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..3cb77464473b4 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1112,6 +1112,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 +1123,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const { widensScope: revealWidensScope } = resolveSidebarRouteReveal({ reveal: routeReveal, routeKey: routeRowThreadKey, + routeKeyInPlace, isSearching: isSearchingThreads, scopedProjectKeys: chosenScopeProjectKeys, delegatedUnderParent, @@ -1143,7 +1147,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, 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({