diff --git a/.gitattributes b/.gitattributes index 24860868b59bc..ab74efd46bf7f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,7 +3,8 @@ # Batch files need CRLF for cmd.exe to parse them reliably. *.cmd text eol=crlf *.bat text eol=crlf -# GitHub's and Expo's GraphQL schemas and the operations graphqlgen writes from them. +# GitHub's, Linear's and Expo's GraphQL schemas and the operations graphqlgen writes from them. packages/source-control-github/schema/** linguist-generated +packages/issue-tracker-linear/schema/** linguist-generated apps/server/schema/** linguist-generated **/*.graphql.ts linguist-generated diff --git a/.github/actions/drop-checkout-credentials/action.yml b/.github/actions/drop-checkout-credentials/action.yml new file mode 100644 index 0000000000000..f9a60340e1fe5 --- /dev/null +++ b/.github/actions/drop-checkout-credentials/action.yml @@ -0,0 +1,38 @@ +name: Drop checkout credentials +description: Removes the token actions/checkout leaves behind, so later steps can run dependency and build scripts. + +# checkout keeps the token in a file under RUNNER_TEMP that .git/config includes, so +# both go. `persist-credentials: false` fails in this repo: its cleanup runs `git +# submodule foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules). +runs: + using: composite + steps: + - name: Drop checkout credentials + shell: bash + run: | + # Status 1 means no match; any other failure stops the step. + lookup() { + local status=0 + git -C "$dir" config --local "$@" || status=$? + if [ "$status" -gt 1 ]; then exit "$status"; fi + } + for dir in . .trusted; do + [ -e "$dir/.git" ] || continue + lookup --get-regexp '^includeif\..*\.path$' | while read -r key file; do + rm -f "$file" + git -C "$dir" config --local --unset-all "$key" + done + lookup --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do + git -C "$dir" config --local --unset-all "$key" + done + remaining="$(lookup --get-regexp 'extraheader|includeif')" + if [ -n "$remaining" ]; then + echo "::error::checkout credentials are still configured in $dir" + exit 1 + fi + done + rm -f "$RUNNER_TEMP"/git-credentials-*.config + if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then + echo "::error::a checkout credential file is still present" + exit 1 + fi diff --git a/.github/actions/eas-local-build/action.yml b/.github/actions/eas-local-build/action.yml new file mode 100644 index 0000000000000..f9699c08a5255 --- /dev/null +++ b/.github/actions/eas-local-build/action.yml @@ -0,0 +1,188 @@ +name: EAS local build +description: Installs the toolchain and mobile dependencies, then runs `eas build --local` on this runner. + +inputs: + platform: + description: android or ios + required: true + profile: + description: eas.json build profile + required: true + environment: + description: EAS environment to pull, preview or production + required: true + expo-token: + description: Expo token for that environment + required: true + output: + description: Path the build artifact is written to + required: true + cache: + description: "false for untrusted code: no build cache and no EAS cache, so nothing it writes reaches trusted builds" + default: "true" + sourcemaps-r2: + description: R2 credentials for the eas-build-on-success source map upload; EAS secrets don't reach local builds + default: "" + +runs: + using: composite + steps: + - name: Prepare Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + env: + CACHE_NAME: ${{ inputs.environment == 'production' && 'store' || 'preview' }} + run: | + cache="$HOME/.cache/t3-android-$CACHE_NAME" + { + echo "GRADLE_USER_HOME=$cache/gradle" + echo "CCACHE_DIR=$cache/ccache" + echo "CCACHE_MAXSIZE=5G" + # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. + echo "CCACHE_COMPILERCHECK=%compiler% -v" + echo "pnpm_config_store_dir=$cache/pnpm-store" + # eas build --local copies the project here. A fixed path keeps + # ccache keys stable, and the same disk as the store lets pnpm hardlink. + echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" + echo "CCACHE_BASEDIR=$cache/eas-build" + # CMake (3.17+) reads these, and AGP passes Gradle's environment through. + echo "CMAKE_C_COMPILER_LAUNCHER=ccache" + echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" + } >> "$GITHUB_ENV" + + - name: Mount Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + key: ${{ github.repository }}-android-${{ inputs.environment == 'production' && 'store' || 'preview' }}-build-${{ github.run_id }} + restore-keys: ${{ github.repository }}-android-${{ inputs.environment == 'production' && 'store' || 'preview' }}-build- + path: ~/.cache/t3-android-${{ inputs.environment == 'production' && 'store' || 'preview' }} + + - name: Configure Gradle and ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" + rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" + # No daemon: nothing should hold the cache directory open when it is saved. + printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" + sudo apt-get update -qq && sudo apt-get install -y -qq ccache + ccache --zero-stats + + # Matches the EAS build image in eas.json. + - name: Select Xcode 27.1 + if: inputs.platform == 'ios' + shell: bash + run: | + xcode=/Applications/Xcode_27.1.app + if [ ! -d "$xcode" ]; then + ls -d /Applications/Xcode*.app + echo "::error::Xcode 27.1 is not on this runner." + exit 1 + fi + sudo xcode-select -s "$xcode/Contents/Developer" + xcodebuild -version + echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" + + # EAS's credentials step fails to import the distribution certificate without it. + - name: Install Apple WWDR G3 intermediate + if: inputs.platform == 'ios' + shell: bash + run: | + curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer + sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true + security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep labl + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - name: Enable corepack + shell: bash + run: | + npm install --global corepack@latest + corepack enable + pnpm --version + + # EAS commands load app.config.ts, whose plugins must resolve. Keep install + # scripts: some download native assets that the build's fingerprint check hashes. + - name: Install mobile dependencies + shell: bash + run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... + + - name: Setup Java + if: inputs.platform == 'android' + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + with: + distribution: temurin + java-version: 17 + + - name: Setup EAS + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + with: + eas-version: latest + eas-cache: ${{ inputs.cache }} + token: ${{ inputs.expo-token }} + # npm, not pnpm: this only installs eas-cli into the action's own + # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's + # ignored build script (no allowBuilds config outside the repo). + packager: npm + + - name: Build tools + if: inputs.platform == 'ios' + shell: bash + run: | + command -v pod || sudo gem install cocoapods --no-document + command -v fastlane || brew install fastlane + pod --version + fastlane --version | tail -1 + + # EAS commands skip dotenv, and the Android fingerprint hashes this file. + - name: Pull ${{ inputs.environment }} environment variables + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + ENVIRONMENT: ${{ inputs.environment }} + PLATFORM: ${{ inputs.platform }} + run: | + eas env:pull "$ENVIRONMENT" --non-interactive + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from "node:fs"; + import { parseEnv } from "node:util"; + const env = parseEnv(readFileSync(".env.local", "utf8")); + const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; + if (!googleServicesFile && process.env.PLATFORM === "android") { + throw new Error(`T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the ${process.env.ENVIRONMENT} environment`); + } + if (googleServicesFile) { + appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); + } + NODE + + - name: Build + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + MOBILE_SOURCEMAPS_R2: ${{ inputs.sourcemaps-r2 }} + PLATFORM: ${{ inputs.platform }} + PROFILE: ${{ inputs.profile }} + OUTPUT: ${{ inputs.output }} + run: | + if [ "$PLATFORM" = "ios" ]; then + # A real path: /var -> /private/var symlinks break the expo-widgets bundle step. + export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" + fi + eas build --local --platform "$PLATFORM" --profile "$PROFILE" --non-interactive --output "$OUTPUT" + + - name: Report ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + { + echo '```' + ccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml new file mode 100644 index 0000000000000..2086d004b295c --- /dev/null +++ b/.github/actions/record-build-tag/action.yml @@ -0,0 +1,57 @@ +name: Record build tag +description: Pushes the tag that tells later runs a build for this fingerprint exists. + +inputs: + tag: + description: Tag name, without refs/tags/ + required: true + message: + description: Annotated tag message; empty makes a lightweight tag + default: "" + replace: + description: "true replaces an existing tag; otherwise an existing tag counts as recorded" + default: "false" + token: + description: Token with contents write + required: true + +runs: + using: composite + steps: + - name: Record build tag + shell: bash + env: + TAG: ${{ inputs.tag }} + MESSAGE: ${{ inputs.message }} + REPLACE: ${{ inputs.replace }} + GH_TOKEN: ${{ inputs.token }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). + for attempt in 1 2 3; do + if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then + old="$(printf '%s\n' "$refs" | while read -r sha ref; do + if [ "$ref" = "refs/tags/$TAG" ]; then echo "$sha"; fi + done)" + if [ -n "$old" ] && [ "$REPLACE" != "true" ]; then + echo "$TAG exists." + exit 0 + fi + if [ -n "$MESSAGE" ]; then + git tag -f -a "$TAG" -m "$MESSAGE" + else + git tag -f "$TAG" + fi + # An empty lease means the tag must not exist yet. + if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then + exit 0 + fi + fi + if [ "$attempt" = 3 ]; then + echo "::error::Could not push $TAG." + exit 1 + fi + sleep $((attempt * 15)) + done diff --git a/.github/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 2c3b55c8c1207..3d25834066067 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -122,6 +122,12 @@ jobs: - name: Check generated Expo GraphQL operations run: vp run --filter t3 generate --check + - name: Check generated Linear GraphQL operations + run: vp run --filter @t3tools/issue-tracker-linear generate --check + + - name: Check i18n catalogs + run: vp run i18n:check + - name: Check run: vp check @@ -335,7 +341,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 1789a27c1371b..6f4cb39568252 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 a GitHub-hosted runner (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 GitHub-hosted runners +# with preview signing credentials. The label is the maintainer's sign-off # that they reviewed that code, so it covers exactly the commit it was applied # to: this pins that commit and consumes the label before running anything. A # later push deploys nothing until the label is applied again. @@ -30,6 +30,12 @@ jobs: contents: read pull-requests: write outputs: + ios_group: ${{ steps.ios_update.outputs.group }} + ios_client: ${{ steps.ios_client.outputs.link }} + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} + ios_build: ${{ steps.ios_client.outputs.build }} + ios_fingerprint: ${{ steps.ios_client.outputs.fingerprint }} build: ${{ steps.client.outputs.build }} fingerprint: ${{ steps.client.outputs.fingerprint }} env: @@ -81,40 +87,20 @@ jobs: fetch-depth: 0 # No sparse-checkout: see mobile-eas-preview.yml. - # The comment script comes from main, not from the PR. + # Scripts and actions come from main, not from the PR. - name: Checkout trusted scripts if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: path: .trusted - sparse-checkout: .github/scripts + sparse-checkout: | + .github/scripts + .github/actions - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials if: steps.expo-token.outputs.present == 'true' - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.trusted/.github/actions/drop-checkout-credentials # No caches: pull_request_target saves them under main's scope, where # trusted workflows with other secrets would restore what PR code wrote. @@ -140,8 +126,7 @@ jobs: if: steps.expo-token.outputs.present == 'true' uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: - # Pinned and installed with npm for the same reasons as mobile-eas-preview.yml. - eas-version: 21.8.0 + eas-version: latest eas-cache: false token: ${{ secrets.EXPO_PREVIEW_TOKEN }} packager: npm @@ -164,23 +149,40 @@ jobs: } NODE - - name: Deploy with fingerprint check + - id: ios_client + name: Find the iOS client for this fingerprint if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action/continuous-deploy-fingerprint@5273c2136bd09c2a341fe3340d3e767ce5a13015 # v9.0.2 + working-directory: apps/mobile + shell: bash env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - RUNNER_DEBUG: "1" - # The action only comments for pull_request events; this hook gives - # it the PR under pull_request_target. Without it, it skips the comment. - EXPO_TEST_GITHUB_PULL: ${{ github.event.pull_request.number }} - with: - profile: preview:dev - branch: pr-${{ github.event.pull_request.number }} - # Android is below: its client builds on a GitHub-hosted runner (android-build). - platform: ios - environment: preview - working-directory: apps/mobile - github-token: ${{ secrets.GITHUB_TOKEN }} + run: | + hash="$(eas env:exec --non-interactive preview "npx expo-updates fingerprint:generate --platform ios" | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')" + echo "fingerprint=$hash" >> "$GITHUB_OUTPUT" + tag="mobile-ios-preview-build/$hash" + link="" + if git fetch --quiet origin "refs/tags/$tag:refs/tags/$tag" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$tag" | node "$GITHUB_WORKSPACE/.trusted/.github/scripts/mobile-ios-preview-record.cjs" read)" + fi + if [ -z "$link" ]; then + link="$(eas build:list --platform ios --build-profile preview:dev --runtime-version "$hash" --status finished --limit 5 --json --non-interactive \ + | sed -n '/^\[/,$p' \ + | jq -r --arg now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" '[.[] | select((.expirationDate // "9999") > $now)][0] | select(. != null) | "https://expo.dev/accounts/pingdotgg/projects/t3-code/builds/\(.id)"')" + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + if [ -z "$link" ]; then echo "build=true" >> "$GITHUB_OUTPUT"; fi + + - id: ios_update + name: Publish the iOS update + if: steps.expo-token.outputs.present == 'true' + working-directory: apps/mobile + shell: bash + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + PR: ${{ github.event.pull_request.number }} + run: | + group="$(eas update --auto --branch "pr-$PR" --platform ios --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" + echo "group=$group" >> "$GITHUB_OUTPUT" # Android, as in mobile-eas-preview.yml: the same fingerprint command the Expo # action runs. A client built for a same-repo PR (its tag) or by EAS is reused. @@ -218,16 +220,6 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" - - name: Comment - if: steps.expo-token.outputs.present == 'true' - env: - GH_TOKEN: ${{ github.token }} - PR: ${{ github.event.pull_request.number }} - FINGERPRINT: ${{ steps.client.outputs.fingerprint }} - CLIENT: ${{ steps.client.outputs.link }} - GROUP: ${{ steps.update.outputs.group }} - run: node .trusted/.github/scripts/mobile-preview-comment.cjs - # The reviewed commit's Android client, built cold: no build cache, because PR # code could leave Gradle or ccache state that trusted builds would restore, and # no build record tag, so nobody else is served an APK a fork's code built. @@ -240,6 +232,8 @@ jobs: permissions: contents: read pull-requests: write + outputs: + client: ${{ steps.build.outputs.link }} env: APP_VARIANT: preview NODE_OPTIONS: --max-old-space-size=8192 @@ -254,92 +248,100 @@ jobs: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 - # The comment script comes from main, not from the PR. + # Scripts and actions come from main, not from the PR. - name: Checkout trusted scripts uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: path: .trusted - sparse-checkout: .github/scripts + sparse-checkout: | + .github/scripts + .github/actions - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.trusted/.github/actions/drop-checkout-credentials - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + # Cold: no build cache or EAS cache that trusted builds would restore. + - name: Build + uses: ./.trusted/.github/actions/eas-local-build with: - node-version-file: package.json + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk + cache: "false" - - name: Enable corepack + - id: build + name: Upload + working-directory: apps/mobile + shell: bash + env: + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - name: Install mobile dependencies - run: pnpm install --frozen-lockfile --filter=@t3tools/mobile... + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" - - name: Setup Java - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + ios-build: + name: iOS preview client + needs: preview + if: needs.preview.outputs.ios_build == 'true' + runs-on: macos-latest + timeout-minutes: 60 + permissions: + contents: read + pull-requests: write + outputs: + client: ${{ steps.build.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + FINGERPRINT: ${{ needs.preview.outputs.ios_fingerprint }} + steps: + - name: Checkout reviewed commit + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - distribution: temurin - java-version: 17 + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 - - name: Setup EAS - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + # Scripts and actions come from main, not from the PR. + - name: Checkout trusted scripts + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - eas-version: latest - eas-cache: false - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm + path: .trusted + sparse-checkout: | + .github/scripts + .github/actions - - name: Pull preview environment variables - working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - run: | - eas env:pull preview --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (googleServicesFile) { - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - } - NODE + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.trusted/.github/actions/drop-checkout-credentials + + # Cold: no build cache or EAS cache that trusted builds would restore. + - name: Build + uses: ./.trusted/.github/actions/eas-local-build + with: + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa + cache: "false" - id: build - name: Build and upload + name: Upload working-directory: apps/mobile shell: bash env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | - eas build --local --platform android --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.apk" - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then echo "::error::eas upload returned no install link" @@ -347,9 +349,32 @@ jobs: fi echo "link=$link" >> "$GITHUB_OUTPUT" + comment: + name: Mobile preview comment + needs: [preview, android-build, ios-build] + if: always() && !cancelled() && needs.preview.result == 'success' + runs-on: ubuntu-24.04 + 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 26111ce619b90..31f45402c0e5f 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: ubuntu-24.04 concurrency: - group: mobile-eas-preview-${{ github.event.pull_request.number }} + group: mobile-eas-preview-ios-${{ github.event.pull_request.number }} cancel-in-progress: true permissions: contents: read pull-requests: write + outputs: + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} + build: ${{ steps.client.outputs.build }} + fingerprint: ${{ steps.client.outputs.fingerprint }} env: APP_VARIANT: preview NODE_OPTIONS: --max-old-space-size=8192 MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} steps: - id: expo-token name: Check for EXPO_PREVIEW_TOKEN - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | if [ -n "$EXPO_TOKEN" ]; then echo "present=true" >> "$GITHUB_OUTPUT" else echo "present=false" >> "$GITHUB_OUTPUT" - echo "EXPO_PREVIEW_TOKEN is not available; skipping EAS preview." + echo "EXPO_PREVIEW_TOKEN is not available; skipping the iOS preview." fi - name: Checkout @@ -41,10 +46,11 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 - # No sparse-checkout here: it makes actions/checkout fetch with - # --filter=blob:none, and eas-cli archives the project via - # `git clone --depth 1 file://`, which fails (exit 128) - # when the partial clone can't serve the unfetched blobs. + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + if: steps.expo-token.outputs.present == 'true' + uses: ./.github/actions/drop-checkout-credentials - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' @@ -68,25 +74,15 @@ jobs: if: steps.expo-token.outputs.present == 'true' uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: - # eas-cli 22 renamed `project` to `app` in build JSON, and - # continuous-deploy-fingerprint still reads `build.project.ownerAccount`. - # Unpin once https://github.com/expo/expo-github-action/issues/358 is fixed. - eas-version: 21.8.0 + eas-version: latest token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - # npm, not pnpm: this only installs eas-cli into the action's own - # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's - # ignored build script (no allowBuilds config outside the repo). packager: npm - name: Pull preview environment variables if: steps.expo-token.outputs.present == 'true' working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | eas env:pull preview --non-interactive - # EAS Update disables dotenv loading. Keep the downloaded native config - # in its process environment so Android build and OTA fingerprints match. node --input-type=module <<'NODE' import { appendFileSync, readFileSync } from "node:fs"; import { parseEnv } from "node:util"; @@ -97,27 +93,40 @@ jobs: } NODE - - name: Deploy with fingerprint check + # The same command the Expo action runs, so this is the runtime version the update gets. + - id: client + name: Find the client for this fingerprint if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action/continuous-deploy-fingerprint@5273c2136bd09c2a341fe3340d3e767ce5a13015 # v9.0.2 - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - # The Expo action otherwise suppresses the EAS command's failure output. - RUNNER_DEBUG: "1" - with: - profile: preview:dev - branch: pr-${{ github.event.pull_request.number }} - # Android is the android job below: its client builds on a GitHub-hosted runner. - 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 a GitHub-hosted runner (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 GitHub-hosted runners}" >> "$GITHUB_STEP_SUMMARY" + + - id: update + name: Publish the update + if: steps.expo-token.outputs.present == 'true' + working-directory: apps/mobile + shell: bash + run: | + group="$(eas update --auto --branch "pr-$PR" --platform ios --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" + echo "group=$group" >> "$GITHUB_OUTPUT" + + # Preview build tags store the install link for each fingerprint; older EAS clients also count. android: name: EAS Preview (Android) if: | @@ -132,6 +141,8 @@ jobs: contents: read pull-requests: write outputs: + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} build: ${{ steps.client.outputs.build }} fingerprint: ${{ steps.client.outputs.fingerprint }} env: @@ -158,32 +169,10 @@ jobs: with: fetch-depth: 0 - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials if: steps.expo-token.outputs.present == 'true' - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' @@ -247,7 +236,7 @@ jobs: fi echo "link=$link" >> "$GITHUB_OUTPUT" if [ -z "$link" ]; then echo "build=true" >> "$GITHUB_OUTPUT"; fi - echo "android fingerprint \`$hash\`: ${link:-no client yet, building on GitHub Actions}" >> "$GITHUB_STEP_SUMMARY" + echo "android fingerprint \`$hash\`: ${link:-no client yet, building on GitHub-hosted runners}" >> "$GITHUB_STEP_SUMMARY" - id: update name: Publish the update @@ -258,14 +247,6 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" - - name: Comment - if: steps.expo-token.outputs.present == 'true' - env: - FINGERPRINT: ${{ steps.client.outputs.fingerprint }} - CLIENT: ${{ steps.client.outputs.link }} - GROUP: ${{ steps.update.outputs.group }} - run: node .github/scripts/mobile-preview-comment.cjs - android-build: name: Android preview client needs: android @@ -276,9 +257,12 @@ jobs: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-android-preview-build-${{ needs.android.outputs.fingerprint }} cancel-in-progress: false + queue: max permissions: contents: write # pushes the build record tag pull-requests: write + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} env: APP_VARIANT: preview NODE_OPTIONS: --max-old-space-size=8192 @@ -302,154 +286,169 @@ jobs: echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" fi - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials - - name: Prepare build directories - if: steps.record.outputs.built != 'true' - run: | - cache="$HOME/.cache/t3-android-preview" - { - echo "GRADLE_USER_HOME=$cache/gradle" - echo "CCACHE_DIR=$cache/ccache" - echo "CCACHE_MAXSIZE=5G" - # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. - echo "CCACHE_COMPILERCHECK=%compiler% -v" - echo "pnpm_config_store_dir=$cache/pnpm-store" - # eas build --local copies the project here. A fixed path keeps - # ccache keys stable, and the same disk as the store lets pnpm hardlink. - echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" - echo "CCACHE_BASEDIR=$cache/eas-build" - echo "CMAKE_C_COMPILER_LAUNCHER=ccache" - echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" - } >> "$GITHUB_ENV" - - - name: Mount build cache + - name: Build if: steps.record.outputs.built != 'true' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: ./.github/actions/eas-local-build with: - key: ${{ github.repository }}-android-preview-build-${{ github.run_id }} - restore-keys: ${{ github.repository }}-android-preview-build- - path: ~/.cache/t3-android-preview + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk - - name: Configure Gradle and ccache + # `eas upload` hosts the APK on EAS and returns the page testers install from. + - id: build + name: Upload if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash run: | - mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" - rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" - # No daemon: nothing should hold the cache directory open when it is saved. - printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" - sudo apt-get update -qq && sudo apt-get install -y -qq ccache - ccache --zero-stats + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - name: Setup Node + # The tag is the record later runs look up; its message is the install link. + - name: Record build if: steps.record.outputs.built != 'true' + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + message: ${{ steps.build.outputs.link }} + token: ${{ github.token }} + + ios-build: + name: iOS preview client + needs: ios + if: needs.ios.outputs.build == 'true' + runs-on: macos-latest + timeout-minutes: 60 + concurrency: + # One build per fingerprint; a second PR with the same one finds the tag. + group: mobile-ios-preview-build-${{ needs.ios.outputs.fingerprint }} + cancel-in-progress: false + queue: max + permissions: + contents: write # pushes the build record tag + pull-requests: write + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} + BUILD_TAG: mobile-ios-preview-build/${{ needs.ios.outputs.fingerprint }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Setup Node uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: node-version-file: package.json - - name: Enable corepack - if: steps.record.outputs.built != 'true' + - id: record + name: Check build record run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" + if [ -n "$link" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$link" >> "$GITHUB_OUTPUT" + fi + fi - - name: Setup Java - if: steps.record.outputs.built != 'true' - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 17 + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials - - name: Setup EAS + - name: Build if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + uses: ./.github/actions/eas-local-build with: - eas-version: latest - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm - - - name: Pull preview environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: | - eas env:pull preview --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (googleServicesFile) { - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - } - NODE + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa - # `eas upload` hosts the APK on EAS and returns the page testers install from. + # EAS hosts the signed client and returns its install page. - id: build - name: Build and upload + name: Upload if: steps.record.outputs.built != 'true' working-directory: apps/mobile shell: bash run: | - eas build --local --platform android --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.apk" - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then echo "::error::eas upload returned no install link" exit 1 fi echo "link=$link" >> "$GITHUB_OUTPUT" - { - echo "### Android preview client for \`$FINGERPRINT\`: $link" - echo '```' - ccache --show-stats - echo '```' - } >> "$GITHUB_STEP_SUMMARY" + echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - # The tag is the record later runs look up; its message is the install link. - - name: Record build + # The tag stores the install link and provisioning-profile expiry. + - id: profile + name: Read the provisioning profile if: steps.record.outputs.built != 'true' env: LINK: ${{ steps.build.outputs.link }} - GH_TOKEN: ${{ github.token }} run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git tag -a "$BUILD_TAG" -m "$LINK" - # Only this step has the token; the checkout's copy was removed before the build. - git push "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "refs/tags/$BUILD_TAG" + profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" + unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" + security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" + record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" + echo "record=$record" >> "$GITHUB_OUTPUT" + + # Replaces an expired record for the same fingerprint. + - name: Record build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + message: ${{ steps.profile.outputs.record }} + replace: "true" + token: ${{ github.token }} + + comment: + name: Mobile preview comment + needs: [android, ios, android-build, ios-build] + if: always() && !cancelled() && (needs.android.result == 'success' || needs.ios.result == 'success') + runs-on: ubuntu-24.04 + concurrency: + group: mobile-preview-comment-${{ github.event.pull_request.number }} + cancel-in-progress: false + permissions: + contents: read + pull-requests: write + steps: + - name: Checkout comment script + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + sparse-checkout: .github/scripts - name: Comment env: GH_TOKEN: ${{ github.token }} PR: ${{ github.event.pull_request.number }} - CLIENT: ${{ steps.build.outputs.link || steps.record.outputs.link }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + ANDROID_FINGERPRINT: ${{ needs.android.outputs.fingerprint }} + ANDROID_GROUP: ${{ needs.android.outputs.group }} + ANDROID_CLIENT: ${{ needs.android-build.outputs.client || needs.android.outputs.client }} + IOS_FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} + IOS_GROUP: ${{ needs.ios.outputs.group }} + IOS_CLIENT: ${{ needs.ios-build.outputs.client || needs.ios.outputs.client }} run: node .github/scripts/mobile-preview-comment.cjs diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index 2479f882d4314..e54f680c05e1d 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -7,10 +7,8 @@ name: Mobile EAS Production # runner, with corepack pinning pnpm 10.24 in eas.json, local == build. # # Every merge reconciles native fingerprints and publishes matching OTAs. -# Android store builds run here with `eas build --local` on GitHub-hosted runners (the -# android job). iOS builds run on EAS unless the MOBILE_IOS_LOCAL_BUILDS -# repository variable is `true`, which moves them to the ios job the same way. -# Local builds never appear in `eas build:list`, so each finished local build +# Store builds run here with `eas build --local` on GitHub-hosted runners (the android and +# ios jobs). Local builds never appear in `eas build:list`, so each finished build # pushes a mobile-android-build// or # mobile-ios-build/// tag that the reconcile reads. # iOS prereleases use the testflight profile (3.0.0); App Store binaries use @@ -253,17 +251,9 @@ jobs: echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version." } >> "$GITHUB_STEP_SUMMARY" - - name: Build and submit iOS (manual) - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.platform != 'android' && vars.MOBILE_IOS_LOCAL_BUILDS != 'true' - working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - MOBILE_BUILD_PROFILE: ${{ inputs.profile || 'production' }} - run: eas build --platform ios --profile "$MOBILE_BUILD_PROFILE" --auto-submit --non-interactive --no-wait - - id: ios_manual name: Queue iOS build (manual) - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.platform != 'android' && vars.MOBILE_IOS_LOCAL_BUILDS == 'true' + if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.platform != 'android' working-directory: apps/mobile env: EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} @@ -351,7 +341,6 @@ jobs: working-directory: apps/mobile env: EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - IOS_LOCAL_BUILDS: ${{ vars.MOBILE_IOS_LOCAL_BUILDS == 'true' }} run: | failed=0 message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))" @@ -374,19 +363,16 @@ jobs: latest_version="$(eas build:list --platform "$platform" --build-profile "$profile" --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')" # Local builds (the android and ios jobs) record each build as a tag; # EAS records still count for builds made before that. - tag_prefix="" if [ "$platform" = "android" ]; then tag_prefix="mobile-android-build" - elif [ "$IOS_LOCAL_BUILDS" = "true" ]; then + else tag_prefix="mobile-ios-build/$profile" fi - if [ -n "$tag_prefix" ]; then - if [ -n "$(git tag -l "$tag_prefix/*/$hash")" ]; then - finished=$((finished + 1)) - fi - if [ -n "$(git tag -l "$tag_prefix/$version/*")" ]; then - latest_version="$version" - fi + if [ -n "$(git tag -l "$tag_prefix/*/$hash")" ]; then + finished=$((finished + 1)) + fi + if [ -n "$(git tag -l "$tag_prefix/$version/*")" ]; then + latest_version="$version" fi if [ "$finished" -gt 0 ]; then @@ -441,23 +427,14 @@ jobs: echo ":building_construction: android: building and submitting $version in the Android store build job ($reason)" >> "$GITHUB_STEP_SUMMARY" continue fi - if [ "$platform" = "ios" ] && [ "$IOS_LOCAL_BUILDS" = "true" ]; then - { - echo "ios_build=true" - echo "ios_profile=$profile" - echo "ios_fingerprint=$hash" - echo "ios_version=$version" - echo "ios_sha=$(git rev-parse HEAD)" - } >> "$GITHUB_OUTPUT" - echo ":building_construction: ios/$profile: building and submitting $version in the iOS store build job ($reason)" >> "$GITHUB_STEP_SUMMARY" - continue - fi - if eas build --platform "$platform" --profile "$profile" --auto-submit --non-interactive --no-wait; then - echo ":building_construction: $platform: scheduled production build and submission for $version ($reason)" >> "$GITHUB_STEP_SUMMARY" - else - failed=1 - echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY" - fi + { + echo "ios_build=true" + echo "ios_profile=$profile" + echo "ios_fingerprint=$hash" + echo "ios_version=$version" + echo "ios_sha=$(git rev-parse HEAD)" + } >> "$GITHUB_OUTPUT" + echo ":building_construction: ios/$profile: building and submitting $version in the iOS store build job ($reason)" >> "$GITHUB_STEP_SUMMARY" done exit "$failed" @@ -476,9 +453,9 @@ jobs: fi done - # `eas build --local` on a GitHub-hosted runner, ARM-only, without release lint (see the - # production profile in eas.json), with Gradle, ccache, and pnpm state in the - # Actions cache. Its own concurrency group keeps later OTAs from waiting on it. + # ARM-only, without release lint (see the production profile in eas.json), + # with Gradle, ccache, and pnpm state in the Actions cache. Its own concurrency + # group keeps later OTAs from waiting on it. android: name: Android store build needs: production @@ -503,20 +480,9 @@ jobs: ref: ${{ needs.production.outputs.android_sha }} fetch-depth: 0 - # Dependency scripts and the build run in this job; only Record build gets a token. - # persist-credentials: false would clean up via `git submodule foreach`, which fails on .repos gitlinks. + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - git config --local --unset-all http.https://github.com/.extraheader || true - { git config --local --name-only --get-regexp '^includeif\.' || true; } | while read -r key; do - path=$(git config --local --get "$key") - git config --local --unset-all "$key" - case "$path" in "$RUNNER_TEMP"/*) rm -f "$path" ;; esac - done - if git config --local --get-regexp '^(http\..*\.extraheader|includeif\.)'; then - echo "::error::Checkout credentials are still configured" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials # A queued run can follow a build of the same fingerprint; manual runs always build. - id: record @@ -529,111 +495,22 @@ jobs: echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" fi - - name: Prepare build directories - if: steps.record.outputs.built != 'true' - run: | - cache="$HOME/.cache/t3-android-store" - { - echo "GRADLE_USER_HOME=$cache/gradle" - echo "CCACHE_DIR=$cache/ccache" - echo "CCACHE_MAXSIZE=5G" - # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. - echo "CCACHE_COMPILERCHECK=%compiler% -v" - echo "pnpm_config_store_dir=$cache/pnpm-store" - # eas build --local copies the project here. A fixed path keeps - # ccache keys stable, and the same disk as the store lets pnpm hardlink. - echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" - echo "CCACHE_BASEDIR=$cache/eas-build" - # CMake (3.17+) reads these, and AGP passes Gradle's environment through. - echo "CMAKE_C_COMPILER_LAUNCHER=ccache" - echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" - } >> "$GITHUB_ENV" - - - name: Mount build cache - if: steps.record.outputs.built != 'true' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 - with: - key: ${{ github.repository }}-android-store-build-${{ github.run_id }} - restore-keys: ${{ github.repository }}-android-store-build- - path: ~/.cache/t3-android-store - - - name: Configure Gradle and ccache - if: steps.record.outputs.built != 'true' - run: | - mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" - rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" - # No daemon: nothing should hold the cache directory open when it is saved. - printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" - sudo apt-get update -qq && sudo apt-get install -y -qq ccache - ccache --zero-stats - - - name: Setup Node - if: steps.record.outputs.built != 'true' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - # EAS commands load app.config.ts, whose plugins must resolve. Keep install - # scripts: some download native assets that the build's fingerprint check hashes. - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... - - - name: Setup Java - if: steps.record.outputs.built != 'true' - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 17 - - - name: Setup EAS + - name: Build if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + uses: ./.github/actions/eas-local-build with: - eas-version: latest - token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - packager: npm - - - name: Pull production environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: | - eas env:pull production --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (!googleServicesFile) { - throw new Error("T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the production environment"); - } - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - NODE - - - name: Build + platform: android + profile: production + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.aab + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - name: Check ABIs if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - env: - # EAS secret variables don't reach local builds; the eas-build-on-success - # hook needs these to upload the bundle's source map. - MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} run: | - eas build --local --platform android --profile production --non-interactive --output "$RUNNER_TEMP/t3code.aab" abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" - { - echo "### Android $BUILD_TAG" - echo "- ABIs: \`$abis\`" - echo '```' - ccache --show-stats - echo '```' - } >> "$GITHUB_STEP_SUMMARY" + echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then echo "::error::Expected only ARM native libraries in the AAB, found $abis" exit 1 @@ -658,30 +535,16 @@ jobs: # pushed, the next merge rebuilds with a new build number; nothing is lost. - name: Record build if: steps.record.outputs.built != 'true' - env: - GH_TOKEN: ${{ github.token }} + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + token: ${{ github.token }} + + - name: Summarize + if: steps.record.outputs.built != 'true' run: | - sha="$(git rev-parse HEAD)" - # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). - for attempt in 1 2 3; do - if gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$BUILD_TAG" >/dev/null 2>&1; then - echo "$BUILD_TAG exists." - break - fi - if gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$BUILD_TAG" -f sha="$sha" >/dev/null; then - break - fi - if [ "$attempt" = 3 ]; then - echo "::error::Submitted, but could not create $BUILD_TAG; the next merge will rebuild." - exit 1 - fi - sleep $((attempt * 15)) - done echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" - # Off unless the MOBILE_IOS_LOCAL_BUILDS repository variable is `true`; the - # production job only sets ios_build then. Xcode 27.1 matches the EAS build - # image in eas.json. ios: name: iOS store build needs: production @@ -707,20 +570,9 @@ jobs: ref: ${{ needs.production.outputs.ios_sha }} fetch-depth: 0 - # Dependency scripts and the build run in this job; only Record build gets a token. - # persist-credentials: false would clean up via `git submodule foreach`, which fails on .repos gitlinks. + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - git config --local --unset-all http.https://github.com/.extraheader || true - { git config --local --name-only --get-regexp '^includeif\.' || true; } | while read -r key; do - path=$(git config --local --get "$key") - git config --local --unset-all "$key" - case "$path" in "$RUNNER_TEMP"/*) rm -f "$path" ;; esac - done - if git config --local --get-regexp '^(http\..*\.extraheader|includeif\.)'; then - echo "::error::Checkout credentials are still configured" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials # A queued run can follow a build of the same fingerprint; manual runs always build. - id: record @@ -733,78 +585,16 @@ jobs: echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" fi - - name: Select Xcode 27.1 - if: steps.record.outputs.built != 'true' - run: | - xcode=/Applications/Xcode_27.1.app - if [ ! -d "$xcode" ]; then - ls -d /Applications/Xcode*.app - echo "::error::Xcode 27.1 is not on this runner." - exit 1 - fi - sudo xcode-select -s "$xcode/Contents/Developer" - xcodebuild -version - echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" - - # EAS's credentials step fails to import the distribution certificate without it. - - name: Install Apple WWDR G3 intermediate - if: steps.record.outputs.built != 'true' - run: | - curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer - sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true - security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep -m1 labl - - - name: Setup Node - if: steps.record.outputs.built != 'true' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - # EAS commands load app.config.ts, whose plugins must resolve. Keep install - # scripts: some download native assets that the build's fingerprint check hashes. - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... - - - name: Setup EAS - if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 - with: - eas-version: latest - token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - packager: npm - - - name: Build tools - if: steps.record.outputs.built != 'true' - run: | - command -v pod || sudo gem install cocoapods --no-document - command -v fastlane || brew install fastlane - pod --version - fastlane --version | tail -1 - - - name: Pull production environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas env:pull production --non-interactive - - name: Build if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - env: - # EAS secret variables don't reach local builds; the eas-build-on-success - # hook needs these to upload the bundle's source map. - MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - run: | - # A real path: /var -> /private/var symlinks break the expo-widgets bundle step. - export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" - eas build --local --platform ios --profile "$PROFILE" --non-interactive --output "$RUNNER_TEMP/t3code.ipa" + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: ${{ env.PROFILE }} + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.ipa + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - name: Submit to App Store Connect if: steps.record.outputs.built != 'true' @@ -815,23 +605,12 @@ jobs: # pushed, the next merge rebuilds with a new build number; nothing is lost. - name: Record build if: steps.record.outputs.built != 'true' - env: - GH_TOKEN: ${{ github.token }} + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + token: ${{ github.token }} + + - name: Summarize + if: steps.record.outputs.built != 'true' run: | - sha="$(git rev-parse HEAD)" - # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). - for attempt in 1 2 3; do - if gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$BUILD_TAG" >/dev/null 2>&1; then - echo "$BUILD_TAG exists." - break - fi - if gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$BUILD_TAG" -f sha="$sha" >/dev/null; then - break - fi - if [ "$attempt" = 3 ]; then - echo "::error::Submitted, but could not create $BUILD_TAG; the next merge will rebuild." - exit 1 - fi - sleep $((attempt * 15)) - done echo ":rocket: ios: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index 6bc4639fcda2d..303348a27f916 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -19,12 +19,15 @@ on: types: [opened, synchronize, reopened, edited] concurrency: - group: mobile-fingerprint-check-${{ github.event.pull_request.number }} + # A title or body edit gets its own group, so it cannot cancel the PR's real + # run and leave a cancelled check on the head commit. + group: mobile-fingerprint-check-${{ github.event.action == 'edited' && !github.event.changes.base && format('edit-{0}', github.run_id) || github.event.pull_request.number }} cancel-in-progress: true jobs: fingerprint: name: Native fingerprint diff + if: github.event.action != 'edited' || github.event.changes.base runs-on: ubuntu-24.04 permissions: contents: read diff --git a/AGENTS.md b/AGENTS.md index e5941a175264c..12f6c581956cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,6 +73,7 @@ The most common defect in this repo is a change that works on the path you teste - **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow. - **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug. - **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real. +- **Languages.** User-facing text ships in every locale: translate new keys in `apps/{web,mobile}/src/i18n/translations` after `vp run i18n:generate` (`vp run i18n:check` gates it) and in `apps/marketing/src/i18n`. - **Docs.** Check whether the change makes existing guidance inaccurate. Apply the [documentation rules](#documentation) before adding anything. ## Dev servers diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 97554fd823205..0daa6f14cf5c4 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.9", + "version": "0.1.10", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 78349c4cbc4c2..c5957afb77070 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -54,6 +55,7 @@ import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts"; import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts"; import * as DesktopIpc from "../ipc/DesktopIpc.ts"; @@ -72,6 +74,181 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as PreviewManager from "../preview/Manager.ts"; +interface StubbedDesktop { + readonly localEnvironmentEnabled: boolean; + readonly environment: Partial; + readonly fileSystem: Layer.Layer; + readonly record: (event: string) => Effect.Effect; + readonly windowStarted: Deferred.Deferred; + readonly registerLinuxUrlHandler: Effect.Effect; + readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; + readonly flushRendererHistory?: Effect.Effect; + readonly tokenRequested?: Deferred.Deferred; +} + +const runStubbedDesktop = (stub: StubbedDesktop) => + Effect.gen(function* () { + const quitting = yield* Ref.make(false); + const runApp = DesktopApp.program + .pipe( + Effect.provide(NodeCrypto.layer), + Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { + resolveUserDataPath: Effect.succeed("/isolated/userdata"), + configure: stub.record("identity"), + } as DesktopAppIdentity.DesktopAppIdentity["Service"]), + Effect.provideService(ElectronApp.ElectronApp, { + setPath: () => Effect.void, + whenReady: stub.record("ready"), + } as unknown as ElectronApp.ElectronApp["Service"]), + Effect.provideService(ElectronDialog.ElectronDialog, { + showErrorBox: () => Effect.die("unexpected fatal startup error"), + } as unknown as ElectronDialog.ElectronDialog["Service"]), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + platform: "linux", + isDevelopment: false, + isPackaged: true, + stateDir: "/isolated/userdata", + configuredBackendPort: Option.some(3773), + defaultDesktopSettings: { serverExposureMode: "local-only" }, + ...stub.environment, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { + linux: null, + linuxPasswordStoreCommandLine: "basic", + }), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), + updates: Stream.empty, + }), + Effect.provideService(DesktopAppSettings.DesktopAppSettings, { + load: Effect.void, + get: Effect.succeed({ + localEnvironmentEnabled: stub.localEnvironmentEnabled, + serverExposureMode: "local-only", + }), + } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), + Effect.provideService(DesktopLifecycle.DesktopLifecycle, { + register: Effect.void, + relaunch: () => Effect.void, + }), + Effect.provideService(DesktopClerk.DesktopClerk, { + configure: Effect.void, + } as DesktopClerk.DesktopClerk["Service"]), + Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { + selectedStorageBackend: Effect.succeedNone, + } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), + Effect.provideService(PreviewPasskeys.PreviewPasskeys, { + configure: Effect.void, + } as PreviewPasskeys.PreviewPasskeys["Service"]), + Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { + configure: stub.record("menu"), + }), + Effect.provideService(DesktopUpdates.DesktopUpdates, { + configure: Effect.void, + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { + register: stub.registerLinuxUrlHandler, + }), + ) + .pipe( + Effect.provideService(ElectronProtocol.ElectronProtocol, { + registerDesktopProtocol: () => Effect.void, + } as unknown as ElectronProtocol.ElectronProtocol["Service"]), + Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { + load: () => Effect.void, + } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), + Effect.provideService(DesktopSnapShot.DesktopSnapShot, { + initialize: Effect.void, + } as DesktopSnapShot.DesktopSnapShot["Service"]), + Effect.provideService(DesktopState.DesktopState, { + quitting, + } as DesktopState.DesktopState["Service"]), + Effect.provideService(DesktopWindow.DesktopWindow, { + ensureMain: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + createMainIfBackendReady: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + Effect.provideService(DesktopBackendPool.DesktopBackendPool, { + primary: Effect.succeed({ + start: stub.record("backend"), + currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), + }), + list: Effect.succeed(stub.backends ?? []), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Effect.provideService(DesktopServerExposure.DesktopServerExposure, { + configureFromSettings: () => Effect.succeed({ mode: "local-only" }), + backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), + } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), + Effect.provideService(DesktopWslBackend.DesktopWslBackend, { + reconcile: Effect.void, + } as DesktopWslBackend.DesktopWslBackend["Service"]), + Effect.provideService(DesktopAppActivation.DesktopAppActivation, { + start: Effect.void, + } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), + Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { + shutdown: stub.flushRendererHistory ?? Effect.void, + } as DesktopRendererHistory.DesktopRendererHistory["Service"]), + ); + return yield* runApp.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), + Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), + Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), + Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), + Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), + Layer.mock(DesktopIpc.DesktopIpc, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { + getBearerToken: stub + .record("token") + .pipe( + Effect.andThen( + stub.tokenRequested + ? Deferred.succeed(stub.tokenRequested, undefined) + : Effect.void, + ), + Effect.as("token"), + ), + }), + Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), + Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, { + closeAllTunnels: Effect.void, + }), + Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), + Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), + Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), + Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), + Layer.mock(ElectronMenu.ElectronMenu, {}), + Layer.mock(ElectronShell.ElectronShell, {}), + Layer.mock(ElectronTheme.ElectronTheme, {}), + Layer.mock(ElectronWindow.ElectronWindow, {}), + Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(PreviewManager.PreviewManager, { + isBrowserPartition: () => { + throw new Error("unexpected browser partition lookup"); + }, + }), + stub.fileSystem, + Layer.mock(NetService.NetService, {}), + Path.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ), + Effect.forkScoped, + ); + }); + it.effect.each([false, true])( "stops backends together before flushing history and cancels Linux registration, stop defect=%s", (stopDefect) => @@ -85,180 +262,42 @@ it.effect.each([false, true])( const releaseStops = yield* Deferred.make(); const historyStarted = yield* Deferred.make(); const releaseHistory = yield* Deferred.make(); - const quitting = yield* Ref.make(false); const tokenRequested = yield* Deferred.make(); const events: string[] = []; - const record = (event: string) => - Effect.sync(() => { - events.push(event); - }); - const runApp = DesktopApp.program - .pipe( - Effect.provide(NodeCrypto.layer), - Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { - resolveUserDataPath: Effect.succeed("/isolated/userdata"), - configure: record("identity"), - } as DesktopAppIdentity.DesktopAppIdentity["Service"]), - Effect.provideService(ElectronApp.ElectronApp, { - setPath: () => Effect.void, - whenReady: record("ready"), - } as unknown as ElectronApp.ElectronApp["Service"]), - Effect.provideService(ElectronDialog.ElectronDialog, { - showErrorBox: () => Effect.die("unexpected fatal startup error"), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - Effect.provideService(DesktopEnvironment.DesktopEnvironment, { - platform: "linux", - isDevelopment: false, - isPackaged: true, - stateDir: "/isolated/userdata", - configuredBackendPort: Option.some(3773), - defaultDesktopSettings: { serverExposureMode: "local-only" }, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { - linux: null, - linuxPasswordStoreCommandLine: "basic", - }), - Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { - installIntoProcess: Effect.succeed(true), - awaitDiscovery: Effect.succeed(true), - awaitUserShellDiscovery: Effect.succeed(true), - updates: Stream.empty, + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: true, + environment: {}, + fileSystem: FileSystem.layerNoop({}), + record: (event) => + Effect.sync(() => { + events.push(event); }), - Effect.provideService(DesktopAppSettings.DesktopAppSettings, { - load: Effect.void, - get: Effect.succeed({ - localEnvironmentEnabled: true, - serverExposureMode: "local-only", - }), - } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), - Effect.provideService(DesktopLifecycle.DesktopLifecycle, { - register: Effect.void, - relaunch: () => Effect.void, - }), - Effect.provideService(DesktopClerk.DesktopClerk, { - configure: Effect.void, - } as DesktopClerk.DesktopClerk["Service"]), - Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { - selectedStorageBackend: Effect.succeedNone, - } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), - Effect.provideService(PreviewPasskeys.PreviewPasskeys, { - configure: Effect.void, - } as PreviewPasskeys.PreviewPasskeys["Service"]), - Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { - configure: record("menu"), - }), - Effect.provideService(DesktopUpdates.DesktopUpdates, { - configure: Effect.void, - } as unknown as DesktopUpdates.DesktopUpdates["Service"]), - Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { - register: Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), - ), - }), - ) - .pipe( - Effect.provideService(ElectronProtocol.ElectronProtocol, { - registerDesktopProtocol: () => Effect.void, - } as unknown as ElectronProtocol.ElectronProtocol["Service"]), - Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { - load: () => Effect.void, - } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), - Effect.provideService(DesktopSnapShot.DesktopSnapShot, { - initialize: Effect.void, - } as DesktopSnapShot.DesktopSnapShot["Service"]), - Effect.provideService(DesktopState.DesktopState, { - quitting, - } as DesktopState.DesktopState["Service"]), - Effect.provideService(DesktopWindow.DesktopWindow, { - ensureMain: record("window").pipe( - Effect.andThen(Deferred.succeed(windowStarted, undefined)), - ), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Effect.provideService(DesktopBackendPool.DesktopBackendPool, { - primary: Effect.succeed({ - start: record("backend"), - currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), - }), - list: Effect.succeed([ - { - stop: () => - Deferred.succeed(firstStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), - ), - }, - { - stop: () => - Deferred.succeed(secondStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - ), - }, - ]), - } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), - Effect.provideService(DesktopServerExposure.DesktopServerExposure, { - configureFromSettings: () => Effect.succeed({ mode: "local-only" }), - backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), - } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), - Effect.provideService(DesktopWslBackend.DesktopWslBackend, { - reconcile: Effect.void, - } as DesktopWslBackend.DesktopWslBackend["Service"]), - Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, - } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), - Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { - shutdown: Deferred.succeed(historyStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseHistory)), - Effect.asVoid, - ), - } as DesktopRendererHistory.DesktopRendererHistory["Service"]), - ); - const app = yield* runApp.pipe( - Effect.provide( - Layer.mergeAll( - Layer.mock(BrowserImport.BrowserImport, {}), - Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), - Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), - Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), - Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), - Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), - Layer.mock(DesktopIpc.DesktopIpc, {}), - Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { - getBearerToken: record("token").pipe( - Effect.andThen(Deferred.succeed(tokenRequested, undefined)), - Effect.as("token"), + windowStarted, + tokenRequested, + registerLinuxUrlHandler: Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRegistration)), + Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), + ), + backends: [ + { + stop: () => + Deferred.succeed(firstStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), ), - }), - Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), - Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), - Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, { - closeAllTunnels: Effect.void, - }), - Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), - Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), - Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), - Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), - Layer.mock(ElectronMenu.ElectronMenu, {}), - Layer.mock(ElectronShell.ElectronShell, {}), - Layer.mock(ElectronTheme.ElectronTheme, {}), - Layer.mock(ElectronWindow.ElectronWindow, {}), - Layer.mock(MacPermissions.MacPermissions, {}), - Layer.mock(PreviewManager.PreviewManager, { - isBrowserPartition: () => { - throw new Error("unexpected browser partition lookup"); - }, - }), - FileSystem.layerNoop({}), - Layer.mock(NetService.NetService, {}), - Path.layer, - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), - ), - ), + }, + { + stop: () => + Deferred.succeed(secondStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + ), + }, + ], + flushRendererHistory: Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseHistory)), + Effect.asVoid, ), - Effect.forkScoped, - ); + }); yield* Deferred.await(registrationStarted); yield* Deferred.await(windowStarted); yield* Deferred.await(tokenRequested); @@ -285,3 +324,53 @@ it.effect.each([false, true])( assert.isTrue(yield* Deferred.isDone(registrationStopped)); }).pipe(Effect.provide(DesktopShutdown.layer)), ); + +it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ + path, + baseDir, + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), +); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 418a3b63e38ea..0064eb99a5c14 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -15,6 +15,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; @@ -302,6 +303,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ); if (!settings.localEnvironmentEnabled) { + // The backend config refreshes the launcher when the local environment runs; an update may move the app. + yield* DesktopCliShim.install; if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } diff --git a/apps/desktop/src/app/DesktopStartupRecovery.test.ts b/apps/desktop/src/app/DesktopStartupRecovery.test.ts index 029bcaac2b487..5d407feff79d1 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.test.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.test.ts @@ -211,3 +211,75 @@ it.effect.each([ }), ).pipe(Effect.provide(DesktopState.layer)), ); + +it.effect("installs the build the update action downloaded, not the one it offered", () => + Effect.scoped( + Effect.gen(function* () { + const installed = yield* Deferred.make(); + const shown = yield* Deferred.make(); + let navigate: ((event: { preventDefault: () => void }, url: string) => void) | undefined; + const recovery = { + isDestroyed: () => false, + loadURL: () => Promise.resolve(), + once: () => {}, + webContents: { + setWindowOpenHandler: () => {}, + on: (_event: string, listener: typeof navigate) => { + navigate = listener; + Deferred.doneUnsafe(shown, Effect.void); + }, + }, + } as unknown as Electron.BrowserWindow; + const offered = updateState({ status: "available", availableVersion: "0.1.4" }); + const state = yield* DesktopState.DesktopState; + yield* listen.pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ readFileString: () => Effect.succeed("0.1.3") }), + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + appVersion: "0.1.3", + stateDir: "/task/state", + logDir: "/task/logs", + path: { join: (...parts: string[]) => parts.join("/") }, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Layer.succeed(ElectronApp.ElectronApp, { + on: () => Effect.void, + } as unknown as ElectronApp.ElectronApp["Service"]), + Layer.succeed( + ElectronShell.ElectronShell, + {} as ElectronShell.ElectronShell["Service"], + ), + Layer.succeed(ElectronTheme.ElectronTheme, { + shouldUseDarkColors: Effect.succeed(false), + } as ElectronTheme.ElectronTheme["Service"]), + Layer.succeed(ElectronWindow.ElectronWindow, { + main: Effect.succeedNone, + create: () => Effect.succeed(recovery), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + Layer.succeed(DesktopUpdates.DesktopUpdates, { + subscribe: Effect.succeed({ latest: offered, changes: Stream.empty }), + check: () => Effect.void, + getState: Effect.succeed(offered), + // A release published since the offer: the download fetches it instead. + download: Effect.succeed({ + accepted: true, + completed: true, + state: updateState({ status: "downloaded", downloadedVersion: "0.1.5" }), + }), + installPrepared: (version: string) => Deferred.succeed(installed, version), + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + ), + ), + ); + yield* SubscriptionRef.set(state.primaryBackendStartup, { + _tag: "Failing", + reason: "Server failed before readiness", + managedPolicy: false, + output: "Failure details", + }); + yield* Deferred.await(shown); + navigate!({ preventDefault: () => {} }, "https://startup-recovery.invalid/update"); + expect(yield* Deferred.await(installed)).toBe("0.1.5"); + }), + ).pipe(Effect.provide(DesktopState.layer)), +); diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index 090a8231b8bb9..0e47b00b26e16 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -212,12 +212,15 @@ export const listen: Effect.Effect< switch (action) { case "update": { if (current._tag !== "Update") return; - const state = yield* updates.getState; - if (state.downloadedVersion === null) { + let { downloadedVersion } = yield* updates.getState; + if (downloadedVersion === null) { + // The download re-checks first, so it can fetch a newer build than the one offered. const download = yield* updates.download; if (!download.completed) return; + downloadedVersion = download.state.downloadedVersion; } - yield* updates.installPrepared(current.version); + if (downloadedVersion === null) return; + yield* updates.installPrepared(downloadedVersion); return; } case "reinstall": diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 44a0d1411250a..1e8e486562921 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -29,6 +29,7 @@ const layerShellEnvironment = (prepared = true) => installIntoProcess: Effect.succeed(prepared), awaitDiscovery: Effect.succeed(prepared), awaitUserShellDiscovery: Effect.succeed(prepared), + discoveryFinished: Effect.succeed(true), updates: Stream.empty, }); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 39f75b43ce235..9086fb01acb57 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,3 +1,4 @@ +import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; @@ -111,6 +112,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(startFileDrag); yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 13ae461289451..d018d2deb9f97 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -143,3 +143,5 @@ export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-stor export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; + +export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts new file mode 100644 index 0000000000000..7e140f9db5445 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -0,0 +1,55 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { vi } from "vite-plus/test"; + +const { startDrag, getFileIcon } = vi.hoisted(() => ({ + startDrag: vi.fn(), + getFileIcon: vi.fn(async () => "file-icon"), +})); +vi.mock("electron", () => ({ app: { getFileIcon } })); + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import { startFileDrag } from "./fileDrag.ts"; + +it.effect("only drags existing absolute paths from the host environment and app window", () => + Effect.gen(function* () { + startDrag.mockClear(); + getFileIcon.mockClear(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const filePath = path.join(stateDir, "file with spaces.txt"); + yield* fs.writeFileString(filePath, "file"); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), "host\n"); + const run = (environmentId: string, target: string, platform = "darwin", sender = 1) => + startFileDrag.handler({ environmentId, path: target }, { sender: { id: sender } }).pipe( + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + path, + stateDir, + platform, + } as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ); + assert.isFalse(yield* run("remote", filePath)); + assert.isFalse(yield* run("host", "relative.txt")); + assert.isFalse(yield* run("host", `${filePath}:12`)); + assert.isFalse(yield* run("host", filePath, "linux")); + assert.isFalse(yield* run("host", filePath, "darwin", 2)); + assert.strictEqual(startDrag.mock.calls.length, 0); + assert.isTrue(yield* run("host", filePath)); + assert.isTrue(yield* run("host", filePath, "win32")); + assert.deepEqual(startDrag.mock.calls, [ + [{ file: filePath, icon: "file-icon" }], + [{ file: filePath, icon: "file-icon" }], + ]); + yield* fs.remove(path.join(stateDir, "environment-id")); + assert.isFalse(yield* run("host", filePath)); + assert.strictEqual(startDrag.mock.calls.length, 2); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts new file mode 100644 index 0000000000000..227849c5935be --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -0,0 +1,37 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Electron from "electron"; + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import { makeIpcMethod } from "../DesktopIpc.ts"; +import { getHostEnvironmentId } from "./localEnvironment.ts"; + +export const startFileDrag = makeIpcMethod({ + channel: IpcChannels.START_FILE_DRAG_CHANNEL, + payload: Schema.Struct({ environmentId: Schema.String, path: Schema.String }), + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin" && environment.platform !== "win32") return false; + if (!environment.path.isAbsolute(input.path)) return false; + const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); + if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; + const window = yield* (yield* ElectronWindow.ElectronWindow).main; + if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(input.path))) return false; + return yield* Effect.promise(async () => { + try { + const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); + window.value.webContents.startDrag({ file: input.path, icon }); + return true; + } catch { + return false; + } + }); + }), +}); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index de202529c4113..b256025eff844 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -10,6 +10,7 @@ import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -26,6 +27,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; @@ -235,6 +237,7 @@ describe("installRelayTelemetryEnabled", () => { const relayTelemetryEnabled = ( env: NodeJS.ProcessEnv, policy?: Parameters[0], + loginShellEnv: NodeJS.ProcessEnv = {}, ) => Effect.gen(function* () { const listeners = new Map(); @@ -244,21 +247,47 @@ describe("installRelayTelemetryEnabled", () => { removeAllListeners: (channel) => void listeners.delete(channel), on: (channel, listener) => void listeners.set(channel, listener), }; + let discoveryFinished = false; + const ask = () => { + const event = { returnValue: undefined as unknown }; + listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); + return event.returnValue; + }; yield* installRelayTelemetryEnabled().pipe( Effect.provideService(HostProcess.Environment, env), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.sync(() => discoveryFinished), + updates: Stream.empty, + }), Effect.provide( Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)), ), ); - const event = { returnValue: undefined as unknown }; - listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); - return event.returnValue; + const beforeDiscovery = ask(); + // The login shell's values land in the process env after startup has installed handlers. + Object.assign(env, loginShellEnv); + discoveryFinished = true; + return { beforeDiscovery, afterDiscovery: ask() }; }).pipe(Effect.scoped); it.effect("reads the desktop host opt-out before returning the renderer policy", () => Effect.gen(function* () { - assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" })); - assert.isTrue(yield* relayTelemetryEnabled({})); + assert.deepEqual(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }), { + beforeDiscovery: false, + afterDiscovery: false, + }); + // Undecided until the login shell is read, so the renderer asks again instead of opting out. + assert.deepEqual(yield* relayTelemetryEnabled({}), { + beforeDiscovery: null, + afterDiscovery: true, + }); + assert.deepEqual( + yield* relayTelemetryEnabled({}, undefined, { T3CODE_TELEMETRY_ENABLED: "false" }), + { beforeDiscovery: null, afterDiscovery: false }, + ); }), ); @@ -269,14 +298,14 @@ describe("installRelayTelemetryEnabled", () => { organization: "Example Corp", limits, }); - assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false }))); - assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false }))); + const after = function* (...args: Parameters) { + return (yield* relayTelemetryEnabled(...args)).afterDiscovery; + }; + assert.isFalse(yield* after({}, policy({ telemetry: false }))); + assert.isTrue(yield* after({}, policy({ webhookTasks: false }))); // A policy that cannot be read fails closed. assert.isFalse( - yield* relayTelemetryEnabled( - {}, - new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }), - ), + yield* after({}, new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })), ); }), ); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 38887ec71d906..2545cb9dc5390 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -34,6 +34,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronApp from "../../electron/ElectronApp.ts"; @@ -82,22 +83,28 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ /** * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read, - * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. + * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. Until the login + * shell's environment (which may opt out) is known, answer null so the renderer asks again. */ export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")( function* () { const ipc = yield* DesktopIpc.DesktopIpc; - const enabled = - isRelayTracingEnabled(yield* HostProcess.Environment) && - (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( - Effect.map((found) => found?.document.limits?.telemetry !== false), - Effect.orElseSucceed(() => false), - )); + const env = yield* HostProcess.Environment; + const policyAllows = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( + Effect.map((found) => found?.document.limits?.telemetry !== false), + Effect.orElseSucceed(() => false), + ); + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; yield* ipc.handleSync( DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL, - result: Schema.Boolean, - handler: () => Effect.succeed(enabled), + result: Schema.NullOr(Schema.Boolean), + handler: () => + shellEnvironment.discoveryFinished.pipe( + Effect.map((known) => + !policyAllows || !isRelayTracingEnabled(env) ? false : known ? true : null, + ), + ), }), ); }, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 432577917a3ea..564ada478ff9a 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -16,14 +16,11 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Electron from "electron"; import * as NetService from "@t3tools/shared/Net"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel"; -import serverPackageJson from "../../server/package.json" with { type: "json" }; import * as DesktopIpc from "./ipc/DesktopIpc.ts"; import * as ElectronApp from "./electron/ElectronApp.ts"; @@ -109,24 +106,15 @@ const layerDesktopEnvironment = Layer.unwrap( }), ); -const resolveDesktopSshCliRunner = ( - environment: DesktopEnvironment.DesktopEnvironment["Service"], -): RemoteT3RunnerOptions => { - const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); - if (environment.isDevelopment && devRemoteEntryPath !== undefined) { - return { - nodeScriptPath: devRemoteEntryPath, - nodeEngineRange: serverPackageJson.engines.node, - }; - } - return { archiveVersion: environment.appVersion }; -}; - const layerDesktopSshEnvironment = Layer.unwrap( Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; + const env = yield* HostProcess.Environment; return DesktopSshEnvironment.layer({ - resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)), + // Per connect: the login shell's environment is installed after this layer is built. + resolveCliRunner: Effect.sync(() => + DesktopSshEnvironment.resolveDesktopSshCliRunner(environment, env), + ), resolveLauncherId: yield* Effect.cached( DesktopSshEnvironment.readOrCreateLauncherId( environment.path.join(environment.stateDir, "ssh-launcher-id"), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 82ed51f356e39..4c5df518c0dbd 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -111,8 +111,10 @@ contextBridge.exposeInMainWorld("desktopBridge", { } return result as ReturnType; }, - getRelayTelemetryEnabled: () => - ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true, + getRelayTelemetryEnabled: () => { + const enabled = ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL); + return enabled === null ? null : enabled === true; + }, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), @@ -256,6 +258,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), + startFileDrag: (input) => ipcRenderer.invoke(IpcChannels.START_FILE_DRAG_CHANNEL, input), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), checkSystemPermission: (pane: string) => diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 518e62e803018..7ba14c83e4c38 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -367,6 +367,7 @@ describe("DesktopShellEnvironment", () => { NODE_EXTRA_CA_CERTS: "/cached/ca.pem", SSL_CERT_FILE: "/cached/cert.pem", SSL_CERT_DIR: "/cached/certs", + T3CODE_TELEMETRY_ENABLED: "false", SSH_AUTH_SOCK: "/stale.sock", NODE_OPTIONS: "--bad", }, @@ -406,6 +407,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); assert.equal(env.SSL_CERT_FILE, ""); assert.equal(env.SSL_CERT_DIR, "/cached/certs"); + assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false"); assert.equal(env.SSH_AUTH_SOCK, "/current.sock"); assert.isUndefined(env.NODE_OPTIONS); assert.equal(yield* fs.readFileString(cachePath), contents); @@ -723,6 +725,8 @@ describe("DesktopShellEnvironment", () => { Effect.gen(function* () { assert.isTrue(yield* service.awaitDiscovery); assert.equal(env.PATH, "/usr/bin"); + // The user's shell may still opt out of telemetry, so discovery has not settled. + assert.isFalse(yield* service.discoveryFinished); // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await. const published = yield* service.updates.pipe( Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"), diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index b49ded686235c..380ede9c8ace8 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -6,6 +6,7 @@ import { mergePathValues, readUserLoginShell, setWindowsPath, + windowsEnvironmentValueCommand, } from "@t3tools/shared/shell"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; @@ -92,6 +93,8 @@ export class DesktopShellEnvironment extends Context.Service< readonly awaitDiscovery: Effect.Effect; /** Whether the user's own login shell, not a fallback, gave the PATH a new terminal gets. */ readonly awaitUserShellDiscovery: Effect.Effect; + /** Whether discovery has settled (the user's shell answered or retries ran out), without waiting. */ + readonly discoveryFinished: Effect.Effect; readonly updates: Stream.Stream; } >()("@t3tools/desktop/shell/DesktopShellEnvironment") {} @@ -121,6 +124,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", ] as const; @@ -232,7 +236,7 @@ const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, - `$value = [Environment]::GetEnvironmentVariable('${name}')`, + windowsEnvironmentValueCommand(name), "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }", `Write-Output '${endMarker(name)}'`, ]; @@ -556,6 +560,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { config.env[name] = shellEnvironment[name]; @@ -659,6 +664,7 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", + "T3CODE_TELEMETRY_ENABLED", ] as const; /** @public */ @@ -680,6 +686,7 @@ export const make = Effect.gen(function* () { const changes = yield* PubSub.unbounded(); const latest = yield* Ref.make>(Option.none()); const discovered = yield* Deferred.make(); + const settledDiscovery = yield* Deferred.make(); const publish = Effect.fn("desktop.shellEnvironment.publish")(function* ( patch: ShellEnvironmentPatch, discovered = false, @@ -749,6 +756,7 @@ export const make = Effect.gen(function* () { ), ), ), + Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)), ); const installIntoProcess = yield* Effect.cached( Effect.gen(function* () { @@ -804,6 +812,7 @@ export const make = Effect.gen(function* () { Effect.andThen(Deferred.await(discovered)), Effect.map(({ fromUserShell }) => fromUserShell), ), + discoveryFinished: Deferred.isDone(settledDiscovery), updates, }); }); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts new file mode 100644 index 0000000000000..b94958a633156 --- /dev/null +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts @@ -0,0 +1,47 @@ +import * as NodePath from "@effect/platform-node/NodePath"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as DesktopConfig from "../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import { resolveDesktopSshCliRunner } from "./DesktopSshEnvironment.ts"; + +const packagedEnvironment = DesktopEnvironment.DesktopEnvironment.pipe( + Effect.provide( + DesktopEnvironment.layer({ + dirname: "/Applications/T3 Code.app/Contents/Resources/app.asar/dist-electron", + homeDirectory: "/Users/alice", + platform: "darwin", + processArch: "arm64", + appVersion: "0.0.22", + appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar", + isPackaged: true, + resourcesPath: "/Applications/T3 Code.app/Contents/Resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(NodeServices.layer, NodePath.layerPosix, DesktopConfig.layerTest({})), + ), + ), + ), +); + +describe("resolveDesktopSshCliRunner", () => { + it.effect("downloads the remote runner from the release mirror", () => + Effect.gen(function* () { + const environment = yield* packagedEnvironment; + + const runner = resolveDesktopSshCliRunner(environment, { + [CLI_RELEASE_BASE_URL_ENV]: "https://mirror.example.com/t3code", + }); + + assert.deepStrictEqual(runner, { + archiveVersion: "0.0.22", + releaseBaseUrl: "https://mirror.example.com/t3code", + }); + }), + ); +}); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 0693c16cc15fd..fd749b663cd2d 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -3,6 +3,7 @@ import type { DesktopSshEnvironmentBootstrap, DesktopSshEnvironmentTarget, } from "@t3tools/contracts"; +import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as NetService from "@t3tools/shared/Net"; import * as SshAuth from "@t3tools/ssh/auth"; import { resolveSshTarget } from "@t3tools/ssh/command"; @@ -27,6 +28,10 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as Option from "effect/Option"; +import serverPackageJson from "../../../server/package.json" with { type: "json" }; + +import type * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; @@ -74,6 +79,24 @@ export interface DesktopSshEnvironmentLayerOptions { readonly resolveLauncherId?: Effect.Effect; } +export const resolveDesktopSshCliRunner = ( + environment: DesktopEnvironment.DesktopEnvironment["Service"], + env: NodeJS.ProcessEnv, +): SshTunnel.RemoteT3RunnerOptions => { + const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath); + if (environment.isDevelopment && devRemoteEntryPath !== undefined) { + return { + nodeScriptPath: devRemoteEntryPath, + nodeEngineRange: serverPackageJson.engines.node, + }; + } + const releaseBaseUrl = env[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined; + return { + archiveVersion: environment.appVersion, + ...(releaseBaseUrl === undefined ? {} : { releaseBaseUrl }), + }; +}; + // Remote servers record this ID as their owner, so it has to outlive restarts, // updates and edits to a saved connection. Without a stored one there is none. export const readOrCreateLauncherId = Effect.fn("desktop.ssh.readOrCreateLauncherId")( diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index e2bfabe32762c..3b0582e8131b7 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -93,6 +93,7 @@ describe("DesktopTelemetryPublisher", () => { installIntoProcess: Effect.succeed(true), awaitDiscovery: Effect.succeed(true), awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), updates: Stream.make({ version: 1, type: "shellEnvironment", diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts index fdac65f86a595..5cdf2ba1b56dc 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts @@ -733,16 +733,15 @@ describe("DesktopRemoteUpdates", () => { it.effect("waits for a background check before installing a prepared update", () => { const backgroundCheckStarted = Deferred.makeUnsafe(); const releaseBackgroundCheck = Deferred.makeUnsafe(); - let checks = 0; + let blockCheck = false; const harness = makeHarness({ - checkForUpdates: Effect.suspend(() => { - checks += 1; - return checks === 2 + checkForUpdates: Effect.suspend(() => + blockCheck ? Deferred.succeed(backgroundCheckStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseBackgroundCheck)), ) - : Effect.void; - }), + : Effect.void, + ), }); return runRemoteUpdatesTest(harness, ({ requests, commits }) => @@ -755,6 +754,7 @@ describe("DesktopRemoteUpdates", () => { harness.emit("update-downloaded", { version: "1.2.4" }); yield* settle; + blockCheck = true; const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild); yield* Deferred.await(backgroundCheckStarted); assert.isTrue(yield* updates.isActionActive); diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index ce4a8734dfdc8..23993ee984892 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -344,10 +344,11 @@ describe("DesktopUpdates", () => { const installFiber = yield* updates.install.pipe(Effect.forkScoped); yield* Deferred.await(installStarted); + const checksBefore = harness.checkCount(); const checkResult = yield* updates.check("manual"); assert.isFalse(checkResult.checked); - assert.equal(harness.checkCount(), 0); + assert.equal(harness.checkCount(), checksBefore); yield* Deferred.succeed(releaseInstall, undefined); const installResult = yield* Fiber.join(installFiber); @@ -358,7 +359,9 @@ describe("DesktopUpdates", () => { ); it.effect("preserves a queued installer after a background updater error", () => { - const harness = makeHarness(); + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-not-available")), + }); return Effect.scoped( Effect.gen(function* () { @@ -494,6 +497,152 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("downloads the newest release published since the last check", () => { + // electron-updater downloads the release its last checkForUpdates found. + let published = "1.2.4"; + let lastChecked: string | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => { + lastChecked = published; + harness.emit("update-available", { version: published }); + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: lastChecked }); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + assert.equal((yield* updates.getState).availableVersion, "1.2.4"); + + published = "1.2.5"; + const result = yield* updates.download; + yield* flushCallbacks; + assert.isTrue(result.completed); + assert.equal((yield* updates.getState).downloadedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect.each([ + { install: "local", installed: "1.2.5", checks: 1 }, + { install: "prepared", installed: "1.2.4", checks: 0 }, + ])( + "installs $installed on a $install install after a new release", + ({ install, installed, checks }) => { + let published = "1.2.4"; + let lastChecked: string | undefined; + let installedVersion: string | null | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => { + lastChecked = published; + harness.emit("update-available", { version: published }); + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: lastChecked }); + }), + quitAndInstall: Effect.sync(() => { + installedVersion = harness.sentStates.at(-1)?.downloadedVersion; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + yield* updates.download; + yield* flushCallbacks; + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4"); + + published = "1.2.5"; + const checksBefore = harness.checkCount(); + const result = yield* install === "prepared" + ? updates.installPrepared("1.2.4") + : updates.install; + assert.isTrue(result.accepted); + assert.equal(installedVersion, installed); + assert.equal(harness.checkCount(), checksBefore + checks); + assert.equal(harness.quitAndInstalls(), 1); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }, + ); + + it.effect("downloads the known offer when the check before downloading fails", () => { + let checks = 0; + const harness = makeHarness({ + checkForUpdates: Effect.suspend(() => { + checks += 1; + if (checks > 1) { + return Effect.fail( + new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({ + channel: null, + cause: new Error("offline"), + }), + ); + } + harness.emit("update-available", { version: "1.2.4" }); + return Effect.void; + }), + downloadUpdate: Effect.sync(() => { + harness.emit("update-downloaded", { version: "1.2.4" }); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* flushCallbacks; + + const result = yield* updates.download; + yield* flushCallbacks; + assert.isTrue(result.completed); + assert.equal((yield* updates.getState).downloadedVersion, "1.2.4"); + // Remote requests treat a published error after their own check as final. + assert.notInclude( + harness.sentStates.map((state) => state.status), + "error", + ); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + + it.effect("installs the retained download when a stale feed offers an older release", () => { + let published = "1.2.5"; + let installedVersion: string | null | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: published })), + downloadUpdate: Effect.sync(() => harness.emit("update-downloaded", { version: "1.2.5" })), + quitAndInstall: Effect.sync(() => { + installedVersion = harness.sentStates.at(-1)?.downloadedVersion; + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* updates.download; + yield* flushCallbacks; + + published = "1.2.4"; + const result = yield* updates.install; + assert.isTrue(result.accepted); + assert.equal(harness.downloadCount(), 1); + assert.equal(installedVersion, "1.2.5"); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("restores download state and permits retry after interruption", () => Effect.gen(function* () { const actionStarted = yield* Deferred.make(); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index a35103703bbb3..fc61a223d3bde 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -557,6 +557,17 @@ export const make = Effect.gen(function* () { }); }); + // The flag is shared updater state, so callers flip it only while holding a reservation. + const runUpdaterCheck = Effect.fn("desktop.updates.runUpdaterCheck")(function* ( + allowDowngrade: boolean, + ) { + const restoreDowngrade = yield* electronUpdater.allowDowngrade; + if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true); + return yield* electronUpdater.checkForUpdates.pipe( + Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)), + ); + }); + const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* ( reason: string, actionReservation: "acquire" | "held" = "acquire", @@ -586,11 +597,7 @@ export const make = Effect.gen(function* () { } yield* logUpdaterInfo("checking for updates", { reason }); - // The flag is shared updater state, so it flips only while this check holds the reservation. - const restoreDowngrade = yield* electronUpdater.allowDowngrade; - if (allowDowngrade) yield* electronUpdater.setAllowDowngrade(true); - return yield* electronUpdater.checkForUpdates.pipe( - Effect.ensuring(electronUpdater.setAllowDowngrade(restoreDowngrade).pipe(Effect.ignore)), + return yield* runUpdaterCheck(allowDowngrade).pipe( Effect.as(true), Effect.catchTags({ ElectronUpdaterCheckForUpdatesError: Effect.fn( @@ -619,7 +626,10 @@ export const make = Effect.gen(function* () { ); }); - const downloadAvailableUpdate = Effect.gen(function* () { + // Install refreshes before downloading, and a second check could pick a stale, older release. + const downloadAvailableUpdate = Effect.fn("desktop.updates.downloadAvailableUpdate")(function* ( + refresh: boolean, + ) { const admission = yield* Effect.scoped( admitAfterCheck( Effect.gen(function* () { @@ -643,8 +653,29 @@ export const make = Effect.gen(function* () { return { accepted: false, completed: false }; } - const state = yield* Ref.get(updateStateRef); + const offered = yield* Ref.get(updateStateRef); + let state = offered; return yield* Effect.gen(function* () { + if (refresh) { + // electron-updater downloads what its last check found, which can be hours old. + yield* logUpdaterInfo("checking for updates", { reason: "download" }); + yield* runUpdaterCheck( + offered.channel !== desktopUpdateChannelOf(environment.appVersion), + ).pipe( + // A failed check keeps electron-updater's earlier result, so the known offer still downloads. + Effect.catchTags({ + ElectronUpdaterCheckForUpdatesError: (error) => + logUpdaterWarning(error.message, { + errorTag: error._tag, + cause: describeUpdateErrorCause(error.cause), + }), + }), + ); + } + state = yield* Ref.get(updateStateRef); + if (state.status !== "available") { + return { accepted: true, completed: false }; + } yield* setState(reduceDesktopUpdateStateOnDownloadStart(state)); yield* electronUpdater.setDisableDifferentialDownload( isArm64HostRunningIntelBuild(environment.runtimeInfo), @@ -693,7 +724,7 @@ export const make = Effect.gen(function* () { }), Effect.ensuring(finishUpdateAction("download")), ); - }).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate")); + }); const updateRestartMarkerDir = environment.path.join(environment.baseDir, "runtime"); const updateRestartMarkerPath = environment.path.join( @@ -950,6 +981,36 @@ export const make = Effect.gen(function* () { state: yield* Ref.get(updateStateRef), }; } + const retained = yield* Ref.get(updateStateRef); + if ( + expectedVersion === undefined && + retained.downloadedVersion !== null && + (yield* checkForUpdates( + "install", + "acquire", + retained.channel !== desktopUpdateChannelOf(environment.appVersion), + )) && + (yield* Ref.get(updateStateRef)).status === "available" + ) { + const refreshed = yield* Ref.get(updateStateRef); + // electron-updater compares a stale feed with the running build, not the retained download. + if ( + refreshed.availableVersion === null || + compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0 + ) { + yield* setState(retained); + } else { + const download = yield* downloadAvailableUpdate(false); + if (!download.completed) { + return { + accepted: download.accepted, + completed: false, + failed: download.accepted, + state: yield* Ref.get(updateStateRef), + }; + } + } + } const result = yield* installDownloadedUpdate(expectedVersion); return { accepted: result.accepted, @@ -1368,7 +1429,7 @@ export const make = Effect.gen(function* () { }; }), download: Effect.gen(function* () { - const result = yield* downloadAvailableUpdate; + const result = yield* downloadAvailableUpdate(true); return { accepted: result.accepted, completed: result.completed, diff --git a/apps/mobile/assets/icons/issue.png b/apps/mobile/assets/icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/assets/icons/issue.png differ diff --git a/apps/mobile/assets/icons/issue@2x.png b/apps/mobile/assets/icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/assets/icons/issue@2x.png differ diff --git a/apps/mobile/assets/icons/issue@3x.png b/apps/mobile/assets/icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/assets/icons/issue@3x.png differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.50.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.50.tgz deleted file mode 100644 index 74c351ddc3371..0000000000000 Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.50.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz new file mode 100644 index 0000000000000..06f9fc0fa91b9 Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.58.tgz differ diff --git a/apps/mobile/index.ts b/apps/mobile/index.ts index 9367ade408e95..756c69e52176b 100644 --- a/apps/mobile/index.ts +++ b/apps/mobile/index.ts @@ -8,6 +8,8 @@ import "react-native-gesture-handler"; import { LogBox } from "react-native"; import { featureFlags } from "react-native-screens"; +// Before any GT module initializes: GT validates locales with Intl APIs that Hermes lacks. +import "./src/i18n/intl-polyfills"; import App from "./src/App"; // Enables iOS FormSheet sizing for nested native stacks in non-fitToContents sheets. diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 6b2e183892937..253376fe5e4d3 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -250,8 +250,9 @@ private final class ComposerTextView: UITextView { return } } + // pasteboard.string is only the first item; super.paste inserts every text item. if !bypassTextPasteInterception, - let text = pasteboard.string, shouldInterceptTextPaste(text) { + let text = pasteboard.strings?.joined(), shouldInterceptTextPaste(text) { onPasteText?(text, selectedRange) return } diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index 6009daacb4046..6b69f29d308d5 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -237,6 +237,21 @@ for readOnly in [true, false] { check(provider.loadCount == 0, "Locked inputs must not load pasted image providers") } +func interceptedPaste(_ items: [String]) -> String? { + let savedItems = UIPasteboard.general.items + defer { UIPasteboard.general.items = savedItems } + let editor = ComposerTextView() + editor.textPasteThresholdBytes = 32 * 1024 + var intercepted: String? + editor.onPasteText = { text, _ in intercepted = text } + UIPasteboard.general.items = items.map { [UTType.utf8PlainText.identifier: $0] } + editor.paste(nil) + return intercepted +} +let halfA = String(repeating: "A", count: 20_000) +let halfB = String(repeating: "B", count: 20_000) +check(interceptedPaste([halfA, halfB]) == halfA + halfB, "Text items that together reach the threshold must fold") + // Two-frame animated GIF: a mixed paste keeps the GIF's original bytes and the still image's PNG, in order. private let gifBytes = Data(base64Encoded: "R0lGODlhAQABAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAAIBAABBAQAIfkEAAoAAAAsAAAAAAEAAQCBAP8AAAAAAAAAAAAACAQAAQQEADs=")! private let gifProvider = NSItemProvider() diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 736f7cd3019f0..1208f3176935d 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -126,7 +126,7 @@ class T3WorkspaceNavigationView( private val onTabSelected by EventDispatcher() private val onNewThread by EventDispatcher() private val onOverlayChange by EventDispatcher() - var tabs by mutableStateOf(listOf("threads", "pullRequests", "usage", "settings")) + var tabs by mutableStateOf(listOf("threads", "pullRequests", "issues", "usage", "settings")) var selectedTab by mutableStateOf("threads") var rail by mutableStateOf(false) var floating by mutableStateOf(false) @@ -415,6 +415,7 @@ class T3WorkspaceNavigationView( private fun tabTitle(tab: String) = when (tab) { "threads" -> "Chats" "pullRequests" -> "Pulls" + "issues" -> "Issues" "usage" -> "Usage" else -> "Settings" } @@ -427,6 +428,7 @@ class T3WorkspaceNavigationView( when (tab) { "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests + "issues" -> R.drawable.t3_issues "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml new file mode 100644 index 0000000000000..14de69947215f --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_issues.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png new file mode 100644 index 0000000000000..d90e5053a9395 Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png new file mode 100644 index 0000000000000..98518dda6098b Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@2x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png new file mode 100644 index 0000000000000..6b43b0cf37caf Binary files /dev/null and b/apps/mobile/modules/t3-native-controls/ios/Resources/Icons/issue@3x.png differ diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec index c32f88b0dacb3..ed5fd7f091dba 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControls.podspec @@ -15,6 +15,6 @@ Pod::Spec.new do |s| s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', } - s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png'] } + s.resource_bundles = { 'T3NativeControlIcons' => ['Resources/Icons/pull-request*.png', 'Resources/Icons/issue*.png'] } s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' end diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index 5b3d84aedcee3..c8ec3886974a9 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -10,6 +10,7 @@ public final class T3NativeControlsModule: Module { private let presentationSources = T3PresentationSources() private var videoPresentation: T3NativeVideoPresentation? private var filePresentation: T3NativeFilePresentation? + private var imageViewer: T3NativeImageViewer? /// The last file preview that closed. Written on main, read synchronously from JS. private let filePreviewActivity = NSLock() private var finishedFilePreview: String? @@ -88,13 +89,21 @@ public final class T3NativeControlsModule: Module { else { throw URLError(.badURL) } - let file = try self.makeFilePresentation(sourceIdentifiers: sourceIdentifiers, identifier: identifier, - promise: promise) - guard let presenter = self.appContext?.utilities?.currentViewController() else { - file.dismiss() - return - } - file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter) + // A viewer still animating closed must not block the next one, as Quick Look's error alert did. + self.imageViewer?.finishImmediately() + guard self.filePresentation == nil, self.videoPresentation == nil, + let presenter = self.appContext?.utilities?.currentViewController() + else { throw URLError(.cannotLoadFromNetwork) } + let viewer = T3NativeImageViewer( + identifier: identifier, sources: self.presentationSources, sourceIdentifiers: sourceIdentifiers, + onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) }, + completion: { [weak self] error in + if self?.imageViewer?.identifier == identifier { self?.imageViewer = nil } + if let error { promise.reject(error) } else { promise.resolve(nil) } + } + ) + self.imageViewer = viewer + viewer.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter) }.runOnQueue(.main) // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone. @@ -105,15 +114,17 @@ public final class T3NativeControlsModule: Module { // A nil URL marks the item as one that could not be resolved. AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in - if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) } + if self.imageViewer?.identifier == identifier { self.imageViewer?.update(index: index, url: url) } }.runOnQueue(.main) OnDestroy { let presentation = self.videoPresentation let file = self.filePresentation + let images = self.imageViewer DispatchQueue.main.async { presentation?.dismiss() file?.dismiss() + images?.dismiss() } } @@ -270,7 +281,7 @@ public final class T3NativeControlsModule: Module { let isPlayableURL = url.isFileURL ? FileManager.default.isReadableFile(atPath: url.path) : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil) - guard videoPresentation == nil, filePresentation == nil, + guard videoPresentation == nil, filePresentation == nil, imageViewer == nil, let presenter = appContext?.utilities?.currentViewController(), isPlayableURL else { @@ -298,13 +309,13 @@ public final class T3NativeControlsModule: Module { if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() } } - private func makeFilePresentation(sourceIdentifiers: [String], identifier: String, + private func makeFilePresentation(sourceIdentifier: String, identifier: String, promise: Promise) throws -> T3NativeFilePresentation { - guard filePresentation == nil, videoPresentation == nil, + guard filePresentation == nil, videoPresentation == nil, imageViewer == nil, appContext?.utilities?.currentViewController() != nil else { throw URLError(.cannotLoadFromNetwork) } let file = T3NativeFilePresentation( - identifier: identifier, sources: presentationSources, sourceIdentifiers: sourceIdentifiers, + identifier: identifier, sources: presentationSources, sourceIdentifier: sourceIdentifier, onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) }, completion: { [weak self] error in self?.filePresentation = nil @@ -321,13 +332,14 @@ public final class T3NativeControlsModule: Module { private func presentFile(url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) throws { - let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise) + let file = try makeFilePresentation(sourceIdentifier: sourceIdentifier, identifier: identifier, promise: promise) guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return } file.present(url: url, title: title, from: presenter) } private func dismissFilePresentation(identifier: String) { if filePresentation?.identifier == identifier { filePresentation?.dismiss() } + if imageViewer?.identifier == identifier { imageViewer?.dismiss() } } private static func saveImageToLibrary(url: URL, mimeType: String, name: String, promise: Promise) { diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift index 979e87edc1b0e..a939fc473f100 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift @@ -25,13 +25,10 @@ private final class FilePreviewController: QLPreviewController { } } -/// How long the gallery waits for siblings once the selected file is ready; later ones are left out. -private let siblingGraceNanoseconds: UInt64 = 1_000_000_000 /// A load faster than this zooms straight from the thumbnail without a spinner. private let spinnerDelayNanoseconds: UInt64 = 250_000_000 -/// Quick Look only ever receives pages whose file is on disk: a page refreshed after it first -/// rendered blank keeps a stale scroll offset, so drags scroll the image instead of paging or dismissing. +/// Quick Look for PDFs and documents; images open in T3NativeImageViewer. final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate { let identifier: String @@ -39,30 +36,21 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, private let completion: (Error?) -> Void private let onFinish: () -> Void private weak var sources: T3PresentationSources? - private let sourceIdentifiers: [String] - private var titles: [String] = [] - private var urls: [URL?] = [] - /// A prepared file, or nil while loading or after failing; `settled` tells those apart. - private var files: [URL?] = [] - private var settled: [Bool] = [] - private var downloads: [Int: Task] = [:] - private var selectedIndex = 0 - /// The pages Quick Look shows, as indices into `files`. - private var pages: [Int] = [] - private var items: [FilePreviewItem] = [] - private weak var presenter: UIViewController? - private var grace: Task? + private let sourceIdentifier: String + private var file: URL? + private var item: FilePreviewItem? + private var download: Task? private var spinnerDelay: Task? private var spinner: UIView? private var openError: Error? private var dismissRequested = false private var finished = false - init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String], + init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String, onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) { self.identifier = identifier self.sources = sources - self.sourceIdentifiers = sourceIdentifiers + self.sourceIdentifier = sourceIdentifier self.onFinish = onFinish self.completion = completion super.init() @@ -70,112 +58,59 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead. func present(url: URL, title: String, from presenter: UIViewController) { - present(urls: [url], titles: [title], selectedIndex: 0, from: presenter) - } - - /// Loads the gallery in parallel and opens once the selected file is ready, with whichever - /// siblings are ready by the end of a short grace, so a slow or broken one never holds it back. - func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) { - self.titles = titles - self.urls = urls - self.selectedIndex = selectedIndex - self.presenter = presenter - files = Array(repeating: nil, count: urls.count) - settled = Array(repeating: false, count: urls.count) spinnerDelay = Task { @MainActor [self] in try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds) guard !Task.isCancelled else { return } showSpinner() } - for index in urls.indices { download(index) } - } - - /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will. - func update(index: Int, url: URL?) { - guard !finished, controller == nil, urls.indices.contains(index), urls[index] == nil, - !settled[index] - else { return } - guard let url else { - settle(index, result: .failure(URLError(.resourceUnavailable))) - return - } - urls[index] = url - download(index) - } - - private func download(_ index: Int) { - guard let url = urls[index], downloads[index] == nil else { return } - let title = titles[index] - downloads[index] = Task { @MainActor [self] in + download = Task { @MainActor [self] in let result: Result do { result = .success(try await Self.prepareFile(url: url, title: title)) } catch { result = .failure(error) } - downloads[index] = nil - settle(index, result: result) + download = nil + settle(result, title: title, presenter: presenter) } } - private func settle(_ index: Int, result: Result) { + private func settle(_ result: Result, title: String, presenter: UIViewController) { guard !finished, controller == nil, !dismissRequested else { if case .success(let file) = result { Self.remove(file) } return } - settled[index] = true - if let error = store(index, result: result), index == selectedIndex { - openError = error - dismiss() - return - } - guard files[selectedIndex] != nil else { return } - if settled.allSatisfy({ $0 }) { - show() - } else if grace == nil { - grace = Task { @MainActor [self] in - try? await Task.sleep(nanoseconds: siblingGraceNanoseconds) - guard !Task.isCancelled else { return } - show() - } - } - } - - private func store(_ index: Int, result: Result) -> Error? { switch result { case .success(let file): // Quick Look knows which formats it renders; refuse before presenting so the caller // can fall back instead of showing an "unsupported format" page. guard QLPreviewController.canPreview(file as NSURL) else { Self.remove(file) - return NSError( + openError = NSError( domain: "T3NativePresentation", code: 3, userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."] ) + finish() + return } - files[index] = file - return nil + self.file = file + show(file: file, title: title, presenter: presenter) case .failure(let error): - return error + openError = error + finish() } } - private func show() { - guard !finished, controller == nil, !dismissRequested else { return } - guard let presenter else { finish(); return } + private func show(file: URL, title: String, presenter: UIViewController) { cancelLoading() - pages = files.indices.filter { files[$0] != nil } - items = pages.map { index in - let item = FilePreviewItem() - item.previewItemURL = files[index] - item.previewItemTitle = titles[index] - return item - } + let item = FilePreviewItem() + item.previewItemURL = file + item.previewItemTitle = title + self.item = item let preview = FilePreviewController() preview.delegate = self preview.dataSource = self - preview.currentPreviewItemIndex = pages.firstIndex(of: selectedIndex) ?? 0 preview.onAppear = { [weak self] in self?.resumePendingDismissal() } preview.onDismiss = { [weak self] in self?.finish() } controller = preview @@ -188,8 +123,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, /// Shows over the tapped thumbnail that a slow open is on its way. private func showSpinner() { guard !finished, controller == nil, spinner == nil, - sourceIdentifiers.indices.contains(selectedIndex), - let source = sources?.view(for: sourceIdentifiers[selectedIndex]), + let source = sources?.view(for: sourceIdentifier), let window = source.window else { return } let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) @@ -207,10 +141,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, } private func cancelLoading() { - for task in downloads.values { task.cancel() } - downloads.removeAll() - grace?.cancel() - grace = nil + download?.cancel() + download = nil spinnerDelay?.cancel() spinnerDelay = nil spinner?.removeFromSuperview() @@ -234,27 +166,23 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, } } - func numberOfPreviewItems(in controller: QLPreviewController) -> Int { items.count } + func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item == nil ? 0 : 1 } func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { - items[index] + item ?? FilePreviewItem() } - private func sourceView(for item: QLPreviewItem) -> UIView? { - guard !UIAccessibility.isReduceMotionEnabled, - let page = items.firstIndex(where: { $0 === item }), - sourceIdentifiers.indices.contains(pages[page]) - else { return nil } - return sources?.view(for: sourceIdentifiers[pages[page]]) + private var sourceView: UIView? { + UIAccessibility.isReduceMotionEnabled ? nil : sources?.view(for: sourceIdentifier) } func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? { - sourceView(for: item) + sourceView } func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem, inSourceView view: AutoreleasingUnsafeMutablePointer) -> CGRect { - guard let source = sourceView(for: item) else { return .zero } + guard let source = sourceView else { return .zero } view.pointee = source return source.bounds } @@ -267,9 +195,9 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, guard !finished else { return } finished = true cancelLoading() - for file in files.compactMap({ $0 }) { Self.remove(file) } - files.removeAll() - items.removeAll() + if let file { Self.remove(file) } + file = nil + item = nil DispatchQueue.main.async { [completion, openError] in completion(openError) } // After queueing the completion, so a new presentation JS starts on seeing this lands behind it. onFinish() @@ -279,29 +207,33 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource, try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) } + /// Writes the bytes behind a file, data or http(s) URL to `destination`, returning the MIME type it declares. + nonisolated private static func copyOriginal(_ url: URL, to destination: URL) async throws -> String? { + if url.isFileURL { + try FileManager.default.copyItem(at: url, to: destination) + return nil + } + if url.scheme == "data" { + try Data(contentsOf: url).write(to: destination, options: .atomic) + return url.absoluteString.lowercased().hasPrefix("data:image/svg+xml") ? "image/svg+xml" : nil + } + guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { throw URLError(.unsupportedURL) } + let (temporaryFile, response) = try await URLSession.shared.download(from: url) + guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { + throw URLError(.badServerResponse) + } + try FileManager.default.moveItem(at: temporaryFile, to: destination) + return response.mimeType + } + /// Copy original bytes so preview and sharing do not mutate a draft or workspace file. - nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL { + nonisolated static func prepareFile(url: URL, title: String) async throws -> URL { try Task.checkCancellation() let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)") try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) do { let download = directory.appendingPathComponent("original") - var mimeType: String? - if url.isFileURL { - try FileManager.default.copyItem(at: url, to: download) - } else if url.scheme == "data" { - try Data(contentsOf: url).write(to: download, options: .atomic) - } else { - guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { - throw URLError(.unsupportedURL) - } - let (temporaryFile, response) = try await URLSession.shared.download(from: url) - guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else { - throw URLError(.badServerResponse) - } - mimeType = response.mimeType - try FileManager.default.moveItem(at: temporaryFile, to: download) - } + let mimeType = try await copyOriginal(url, to: download) try Task.checkCancellation() // Detect images and PDFs by content; preserve other extensions so Quick Look can decide support. let filename = URL(fileURLWithPath: title).lastPathComponent as NSString diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift new file mode 100644 index 0000000000000..382e92875f303 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift @@ -0,0 +1,952 @@ +import ImageIO +import Photos +import UIKit + +/// Full-screen image gallery modelled on Messages. It opens at once from the tapped thumbnail's +/// own pixels and sharpens when the original arrives, so a slow or failed load never holds it back. +final class T3NativeImageViewer: NSObject { + let identifier: String + private let completion: (Error?) -> Void + private let onFinish: () -> Void + private weak var sources: T3PresentationSources? + private let sourceIdentifiers: [String] + private var titles: [String] = [] + private var urls: [URL?] = [] + /// The original bytes on disk, kept for sharing. + private var files: [URL?] = [] + private var placeholders: [UIImage?] = [] + private var loads: [Int: Task] = [:] + private var decodes: [Int: Task] = [:] + /// The last queued decode; each one waits for it, so one original decodes at a time. + private var decodeQueue: Task? + /// Pages showing their decoded original; only the current page and its neighbours keep one. + private var decoded: Set = [] + private var currentIndex = 0 + private var controller: T3ImageViewerController? + private var finished = false + + init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String], + onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) { + self.identifier = identifier + self.sources = sources + self.sourceIdentifiers = sourceIdentifiers + self.onFinish = onFinish + self.completion = completion + super.init() + } + + func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) { + self.urls = urls + self.titles = titles + files = Array(repeating: nil, count: urls.count) + currentIndex = selectedIndex + let viewer = T3ImageViewerController(titles: titles, selectedIndex: selectedIndex) + viewer.sourceView = { [weak self] index in self?.sourceView(index) } + viewer.fileForPage = { [weak self] index in self?.file(at: index) } + viewer.onRetry = { [weak self] index in self?.load(index, retry: true) } + viewer.onDismissed = { [weak self] in self?.finish() } + viewer.onPageChange = { [weak self] index in self?.show(page: index) } + controller = viewer + viewer.loadViewIfNeeded() + placeholders = urls.indices.map { sourceView($0).flatMap(Self.thumbnail(of:)) } + for (index, placeholder) in placeholders.enumerated() { + if let placeholder { viewer.setImage(placeholder, at: index, full: false) } + } + presenter.present(T3ImageViewerNavigation(viewer: viewer), animated: false) { viewer.animateIn() } + for index in urls.indices { load(index, retry: false) } + } + + /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will. + func update(index: Int, url: URL?) { + guard !finished, urls.indices.contains(index), urls[index] == nil else { return } + guard let url else { + controller?.setFailed(at: index, retryable: false) + return + } + urls[index] = url + load(index, retry: false) + } + + func dismiss() { + guard !finished else { return } + guard let controller else { finish(); return } + controller.close() + } + + /// Ends at once, for a new viewer that must open while this one is still animating away. + func finishImmediately() { + guard !finished else { return } + controller?.presentingViewController?.dismiss(animated: false) + finish() + } + + private func file(at index: Int) -> URL? { + files.indices.contains(index) ? files[index] : nil + } + + private func sourceView(_ index: Int) -> UIView? { + guard sourceIdentifiers.indices.contains(index), !sourceIdentifiers[index].isEmpty else { return nil } + return sources?.view(for: sourceIdentifiers[index]) + } + + private func load(_ index: Int, retry: Bool) { + guard !finished, urls.indices.contains(index), let url = urls[index], loads[index] == nil else { return } + if retry { controller?.setLoading(at: index) } + let title = titles[index] + loads[index] = Task { @MainActor [self] in + defer { loads[index] = nil } + do { + let file = try await T3NativeFilePresentation.prepareFile(url: url, title: title) + guard !finished, !Task.isCancelled else { Self.remove(file); return } + if let previous = files[index] { Self.remove(previous) } + files[index] = file + decoded.remove(index) + if isNearCurrent(index) { decode(index) } + } catch { + guard !finished, !Task.isCancelled else { return } + controller?.setFailed(at: index, retryable: true) + } + } + } + + /// Every original downloads up front, but a decoded one costs far more memory than its file, + /// so only pages next to the current one decode, and pages further away fall back to their thumbnail. + private func show(page index: Int) { + currentIndex = index + for other in decoded where !isNearCurrent(other) { + decoded.remove(other) + controller?.release(at: other, placeholder: placeholders[other]) + } + // Queued decodes for pages paged past are skipped before they start. + for (other, task) in decodes where !isNearCurrent(other) { task.cancel() } + for near in files.indices where isNearCurrent(near) { decode(near) } + } + + private func isNearCurrent(_ index: Int) -> Bool { abs(index - currentIndex) <= 1 } + + private func decode(_ index: Int) { + guard !finished, let file = file(at: index), !decoded.contains(index), decodes[index] == nil else { return } + let source = sourceView(index) + let previous = decodeQueue + let task = Task { @MainActor [self] in + await previous?.value + var settled = false + defer { + decodes[index] = nil + // Paged away and back while this run waited: it was cancelled, so the page asks again. + if !settled, !finished, isNearCurrent(index), !decoded.contains(index) { decode(index) } + } + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } + // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size. + let isSVG = file.pathExtension.lowercased() == "svg" + let image = isSVG ? nil : await Task.detached(priority: .userInitiated) { Self.decode(file) }.value + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } + if isSVG { + // The open transition hides the thumbnail, which draws blank until it is back. + await controller?.untilRevealed() + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return } + } + settled = true + if let image = image ?? (isSVG ? source.flatMap(Self.render(_:)) : nil) { + decoded.insert(index) + controller?.setImage(image, at: index, full: true) + } else { + // A corrupt download or an SVG whose thumbnail is scrolled away; retrying downloads it again. + // A file that is not an image must not reach Share. + if !isSVG { + Self.remove(file) + files[index] = nil + } + controller?.setFailed(at: index, retryable: true) + } + } + decodes[index] = task + decodeQueue = task + } + + private func finish() { + guard !finished else { return } + finished = true + for task in loads.values { task.cancel() } + loads.removeAll() + for task in decodes.values { task.cancel() } + decodes.removeAll() + decodeQueue = nil + for file in files.compactMap({ $0 }) { Self.remove(file) } + files.removeAll() + controller = nil + DispatchQueue.main.async { [completion] in completion(nil) } + // After queueing the completion, so a new presentation JS starts on seeing this lands behind it. + onFinish() + } + + private static func remove(_ file: URL) { + try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) + } + + /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one. + /// The largest image view wins, so an overlaid icon is never mistaken for the picture. + private static func thumbnail(of view: UIView) -> UIImage? { + var queue = [view] + var best: (image: UIImage, area: CGFloat)? + while let candidate = queue.popLast() { + queue.append(contentsOf: candidate.subviews) + guard let image = (candidate as? UIImageView)?.image, image.size.width > 0, image.size.height > 0 else { continue } + let area = candidate.bounds.width * candidate.bounds.height + if area > best?.area ?? 0 { best = (image, area) } + } + if let best, best.area >= view.bounds.width * view.bounds.height / 2 { return best.image } + return snapshot(view, scale: view.window?.screen.scale ?? 2) + } + + private static func render(_ view: UIView) -> UIImage? { + let screen = view.window?.screen.bounds.size ?? CGSize(width: 1024, height: 1024) + let fit = min(screen.width / max(view.bounds.width, 1), screen.height / max(view.bounds.height, 1)) + // The thumbnail was shown again after the open transition, in a frame not yet on screen. + return snapshot(view, scale: max(1, fit) * (view.window?.screen.scale ?? 2), afterScreenUpdates: true) + } + + private static func snapshot(_ view: UIView, scale: CGFloat, afterScreenUpdates: Bool = false) -> UIImage? { + guard view.bounds.width > 1, view.bounds.height > 1, view.window != nil else { return nil } + let format = UIGraphicsImageRendererFormat() + format.scale = scale + format.opaque = false + return UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in + view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates) + } + } + + /// Decodes off the main thread at no more than zooming needs, and keeps GIFs animated. + nonisolated private static func decode(_ file: URL) -> UIImage? { + guard let source = CGImageSourceCreateWithURL(file as CFURL, nil) else { return nil } + let count = CGImageSourceGetCount(source) + guard count > 0 else { return nil } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: 4096, + ] + var animationOptions = options + animationOptions[kCGImageSourceThumbnailMaxPixelSize] = 1024 + animationOptions[kCGImageSourceShouldCacheImmediately] = nil + // Every frame stays decoded while it plays, so an animation over this budget shows its first frame. + if count > 1, let first = CGImageSourceCreateThumbnailAtIndex(source, 0, animationOptions as CFDictionary), + first.bytesPerRow * first.height * count <= animationByteBudget { + var frames: [(image: UIImage, delay: Double)] = [(UIImage(cgImage: first), frameDuration(source, 0))] + for index in 1.. 1 { return UIImage.animatedImage(with: timeline, duration: Double(timeline.count) * tick) } + } + return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) } + } + + nonisolated private static func frameDuration(_ source: CGImageSource, _ index: Int) -> Double { + let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any] + let gif = properties?[kCGImagePropertyGIFDictionary] as? [CFString: Any] + let png = properties?[kCGImagePropertyPNGDictionary] as? [CFString: Any] + let delay = gif?[kCGImagePropertyGIFUnclampedDelayTime] as? Double + ?? gif?[kCGImagePropertyGIFDelayTime] as? Double + ?? png?[kCGImagePropertyAPNGUnclampedDelayTime] as? Double + ?? png?[kCGImagePropertyAPNGDelayTime] as? Double + ?? 0.1 + // Browsers treat near-zero delays as 0.1s. + return delay < 0.011 ? 0.1 : delay + } +} + +private let animationByteBudget = 64 * 1024 * 1024 + +private extension Array { + subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil } +} + +/// One zoomable page. Its content never exceeds its bounds at the fitted zoom, so a vertical +/// drag has nothing to scroll and always reaches the dismiss gesture. +private final class T3ImageViewerPage: UIView, UIScrollViewDelegate { + let scroll = UIScrollView() + let imageView = UIImageView() + private let spinner = UIActivityIndicatorView(style: .large) + private let failure = UIStackView() + private var spinnerDelay: DispatchWorkItem? + private var laidOutSize = CGSize.zero + private(set) var isFull = false + var onRetry: (() -> Void)? + + override init(frame: CGRect) { + super.init(frame: frame) + scroll.delegate = self + scroll.showsVerticalScrollIndicator = false + scroll.showsHorizontalScrollIndicator = false + scroll.contentInsetAdjustmentBehavior = .never + scroll.decelerationRate = .fast + scroll.alwaysBounceVertical = false + scroll.alwaysBounceHorizontal = false + scroll.bouncesZoom = true + addSubview(scroll) + imageView.contentMode = .scaleAspectFill + imageView.clipsToBounds = true + imageView.isAccessibilityElement = true + imageView.accessibilityTraits = .image + scroll.addSubview(imageView) + spinner.color = .white + spinner.hidesWhenStopped = true + addSubview(spinner) + configureFailure() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + private func configureFailure() { + let icon = UIImageView(image: UIImage(systemName: "exclamationmark.triangle")) + icon.tintColor = UIColor(white: 1, alpha: 0.8) + icon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 28, weight: .regular) + let label = UILabel() + label.text = "This image could not be loaded." + label.textColor = UIColor(white: 1, alpha: 0.8) + label.font = .preferredFont(forTextStyle: .subheadline) + label.adjustsFontForContentSizeCategory = true + label.textAlignment = .center + label.numberOfLines = 0 + var configuration = UIButton.Configuration.gray() + configuration.title = "Try Again" + configuration.cornerStyle = .capsule + configuration.baseForegroundColor = .white + configuration.baseBackgroundColor = UIColor(white: 1, alpha: 0.18) + let retry = UIButton(configuration: configuration, primaryAction: UIAction { [weak self] _ in self?.onRetry?() }) + failure.axis = .vertical + failure.alignment = .center + failure.spacing = 12 + failure.isHidden = true + for view in [icon, label, retry] { failure.addArrangedSubview(view) } + addSubview(failure) + } + + var image: UIImage? { imageView.image } + + func setImage(_ image: UIImage, full: Bool) { + guard full || !isFull else { return } + let previous = imageView.image?.size + imageView.image = image + isFull = full + stopLoading() + failure.isHidden = true + let ratio = { (size: CGSize) in size.width / max(size.height, 1) } + // A sharper copy of the same picture keeps the reader's zoom; a different shape starts over. + if previous == nil || abs(ratio(previous ?? .zero) - ratio(image.size)) > 0.01 { laidOutSize = .zero } + setNeedsLayout() + } + + /// Gives back a far-away page's decoded original, keeping the thumbnail until it returns. + func release(to placeholder: UIImage?) { + guard isFull else { return } + isFull = false + imageView.image = placeholder + laidOutSize = .zero + setNeedsLayout() + setLoading() + } + + func setLoading() { + failure.isHidden = true + imageView.alpha = 1 + guard imageView.image == nil, spinnerDelay == nil else { return } + let work = DispatchWorkItem { [weak self] in self?.spinner.startAnimating() } + spinnerDelay = work + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work) + } + + func setFailed(retryable: Bool) { + stopLoading() + guard !isFull else { return } + failure.arrangedSubviews.last?.isHidden = !retryable + failure.isHidden = false + // A thumbnail stays visible behind the message, dimmed. + imageView.alpha = imageView.image == nil ? 1 : 0.35 + } + + private func stopLoading() { + spinnerDelay?.cancel() + spinnerDelay = nil + spinner.stopAnimating() + imageView.alpha = 1 + } + + var isZoomed: Bool { scroll.zoomScale > scroll.minimumZoomScale + 0.01 } + + func resetZoom(animated: Bool) { scroll.setZoomScale(scroll.minimumZoomScale, animated: animated) } + + override func layoutSubviews() { + super.layoutSubviews() + scroll.frame = bounds + spinner.center = CGPoint(x: bounds.midX, y: bounds.midY) + let width = min(bounds.width - 48, 320) + let height = failure.systemLayoutSizeFitting(CGSize(width: width, height: 0), + withHorizontalFittingPriority: .required, + verticalFittingPriority: .fittingSizeLevel).height + failure.frame = CGRect(x: (bounds.width - width) / 2, y: (bounds.height - height) / 2, width: width, height: height) + guard bounds.size != laidOutSize, let size = imageView.image?.size, size.width > 0, size.height > 0 else { return } + laidOutSize = bounds.size + let fit = min(bounds.width / size.width, bounds.height / size.height) + scroll.minimumZoomScale = 1 + scroll.zoomScale = 1 + imageView.transform = .identity + imageView.frame = CGRect(x: 0, y: 0, width: size.width * fit, height: size.height * fit) + scroll.contentSize = imageView.frame.size + // Enough to fill the screen and then some, or to see the original's pixels. + let fill = max(bounds.width / imageView.frame.width, bounds.height / imageView.frame.height) + let pixels = 1 / fit / (window?.screen.scale ?? 2) + scroll.maximumZoomScale = max(3, fill * 1.5, pixels) + centerImage() + } + + /// The fitted frame of the image, for the opening transition. + func fittedFrame(in view: UIView) -> CGRect { + layoutIfNeeded() + return imageView.convert(imageView.bounds, to: view) + } + + func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView } + + func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() } + + private func centerImage() { + let content = scroll.contentSize + imageView.center = CGPoint(x: max(content.width, scroll.bounds.width) / 2, + y: max(content.height, scroll.bounds.height) / 2) + } + + func toggleZoom(at point: CGPoint) { + if isZoomed { resetZoom(animated: true); return } + guard imageView.image != nil else { return } + let location = convert(point, to: imageView) + let fill = max(scroll.bounds.width / imageView.bounds.width, scroll.bounds.height / imageView.bounds.height) + let scale = min(scroll.maximumZoomScale, fill > 1.2 ? fill : 2.5) + let width = scroll.bounds.width / scale + let height = scroll.bounds.height / scale + scroll.zoom(to: CGRect(x: location.x - width / 2, y: location.y - height / 2, width: width, height: height), + animated: true) + } +} + +/// System bars, so UIKit places Close, the title, Save and Share: at the top and bottom of an iPhone, +/// and in the side bar of an unfolded iPhone Duo. +private final class T3ImageViewerNavigation: UINavigationController { + init(viewer: T3ImageViewerController) { + super.init(rootViewController: viewer) + modalPresentationStyle = .overFullScreen + modalPresentationCapturesStatusBarAppearance = true + overrideUserInterfaceStyle = .dark + view.backgroundColor = .clear + if #unavailable(iOS 26.0) { + // Before iOS 26 bars at the scroll edge are transparent; iOS 26 gives them its edge blur instead. + let bar = UINavigationBarAppearance() + bar.configureWithDefaultBackground() + navigationBar.scrollEdgeAppearance = bar + navigationBar.compactScrollEdgeAppearance = bar + let tools = UIToolbarAppearance() + tools.configureWithDefaultBackground() + toolbar.scrollEdgeAppearance = tools + toolbar.compactScrollEdgeAppearance = tools + } + setNavigationBarHidden(true, animated: false) + setToolbarHidden(true, animated: false) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override var childForStatusBarHidden: UIViewController? { topViewController } + override var childForStatusBarStyle: UIViewController? { topViewController } + override var childForHomeIndicatorAutoHidden: UIViewController? { topViewController } +} + +final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate { + var sourceView: (Int) -> UIView? = { _ in nil } + var fileForPage: (Int) -> URL? = { _ in nil } + var onRetry: (Int) -> Void = { _ in } + var onPageChange: (Int) -> Void = { _ in } + var onDismissed: () -> Void = {} + + private let titles: [String] + private var currentIndex: Int + private let backdrop = UIView() + private let pager = UIScrollView() + private var pages: [T3ImageViewerPage] = [] + private let titleLabel = UILabel() + private let counterLabel = UILabel() + private lazy var dismissPan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:))) + private var chromeHidden = false + private var chromeHiddenBeforeDrag = false + private var dragAnchor = CGPoint.zero + private var transitioning = true + private var closeRequested = false + private var closing = false + private var revealed = false + private var revealWaiters: [CheckedContinuation] = [] + private var laidOutSize = CGSize.zero + private var isLayingOut = false + private lazy var saveItem = UIBarButtonItem( + title: "Save to Photos", image: UIImage(systemName: "square.and.arrow.down"), + primaryAction: UIAction { [weak self] _ in self?.save() }) + private lazy var shareItem = UIBarButtonItem( + systemItem: .action, primaryAction: UIAction { [weak self] _ in self?.share() }) + private static let pageGap: CGFloat = 20 + + init(titles: [String], selectedIndex: Int) { + self.titles = titles + currentIndex = selectedIndex + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override var prefersStatusBarHidden: Bool { chromeHidden } + override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } + override var prefersHomeIndicatorAutoHidden: Bool { chromeHidden } + override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .clear + backdrop.backgroundColor = .black + backdrop.alpha = 0 + view.addSubview(backdrop) + pager.isPagingEnabled = true + pager.showsHorizontalScrollIndicator = false + pager.showsVerticalScrollIndicator = false + pager.contentInsetAdjustmentBehavior = .never + pager.alwaysBounceVertical = false + pager.delegate = self + pager.isHidden = true + view.addSubview(pager) + for index in titles.indices { + let page = T3ImageViewerPage() + page.imageView.accessibilityLabel = titles[index] + page.onRetry = { [weak self] in self?.onRetry(index) } + page.scroll.panGestureRecognizer.require(toFail: dismissPan) + page.setLoading() + pages.append(page) + pager.addSubview(page) + } + pager.panGestureRecognizer.require(toFail: dismissPan) + dismissPan.delegate = self + dismissPan.maximumNumberOfTouches = 1 + view.addGestureRecognizer(dismissPan) + let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:))) + doubleTap.numberOfTapsRequired = 2 + pager.addGestureRecognizer(doubleTap) + let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap)) + singleTap.require(toFail: doubleTap) + pager.addGestureRecognizer(singleTap) + configureChrome() + updateTitle() + } + + private func configureChrome() { + navigationItem.leftBarButtonItem = UIBarButtonItem( + systemItem: .close, primaryAction: UIAction { [weak self] _ in self?.close() }) + if #unavailable(iOS 26.0) { + // Before iOS 26 a navigation item has no subtitle, so the count sits under the title by hand. + titleLabel.font = .preferredFont(forTextStyle: .headline) + counterLabel.font = .preferredFont(forTextStyle: .caption1) + counterLabel.textColor = .secondaryLabel + for label in [titleLabel, counterLabel] { + label.textAlignment = .center + label.adjustsFontForContentSizeCategory = true + label.lineBreakMode = .byTruncatingMiddle + } + let titles = UIStackView(arrangedSubviews: [titleLabel, counterLabel]) + titles.axis = .vertical + titles.alignment = .center + navigationItem.titleView = titles + } + toolbarItems = [.flexibleSpace(), saveItem, shareItem] + setContentScrollView(pager, for: .top) + setContentScrollView(pager, for: .bottom) + } + + /// Shows or hides the bars through UIKit, which also moves them out of an iPhone Duo's side bar. + private func setBarsVisible(_ visible: Bool) { + navigationController?.setNavigationBarHidden(!visible, animated: true) + navigationController?.setToolbarHidden(!visible, animated: true) + } + + private func updateTitle() { + updateActions() + let title = titles[safe: currentIndex] + let counter = titles.count > 1 ? "\(currentIndex + 1) of \(titles.count)" : nil + navigationItem.title = title + if #available(iOS 26.0, *) { navigationItem.subtitle = counter } + titleLabel.text = title + counterLabel.text = counter + counterLabel.isHidden = counter == nil + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + backdrop.frame = view.bounds + guard view.bounds.size != laidOutSize else { return } + laidOutSize = view.bounds.size + // Resizing the pager scrolls it; that must not move the reader to another page. + isLayingOut = true + defer { isLayingOut = false } + // Pages sit a gap apart, like Photos, so the pager is a gap wider than the screen. + let pageWidth = view.bounds.width + Self.pageGap + pager.frame = CGRect(x: -Self.pageGap / 2, y: 0, width: pageWidth, height: view.bounds.height) + for (index, page) in pages.enumerated() { + page.transform = .identity + page.frame = CGRect(x: CGFloat(index) * pageWidth + Self.pageGap / 2, y: 0, + width: view.bounds.width, height: view.bounds.height) + } + pager.contentSize = CGSize(width: pageWidth * CGFloat(pages.count), height: view.bounds.height) + pager.contentOffset = CGPoint(x: CGFloat(currentIndex) * pageWidth, y: 0) + } + + func setImage(_ image: UIImage, at index: Int, full: Bool) { + guard let page = pages[safe: index] else { return } + page.setImage(image, full: full) + updateActions() + } + + func setLoading(at index: Int) { pages[safe: index]?.setLoading() } + + func release(at index: Int, placeholder: UIImage?) { + pages[safe: index]?.release(to: placeholder) + updateActions() + } + + func setFailed(at index: Int, retryable: Bool) { + pages[safe: index]?.setFailed(retryable: retryable) + updateActions() + } + + /// Save and Share act on the original, so they wait until the current page shows it. + private func updateActions() { + let ready = pages[safe: currentIndex]?.isFull == true + saveItem.isEnabled = ready + shareItem.isEnabled = ready + } + + // MARK: Transitions + + private var reduceMotion: Bool { UIAccessibility.isReduceMotionEnabled } + + private func visibleSource(_ index: Int) -> UIView? { + guard !reduceMotion, let source = sourceView(index), source.window === view.window, !source.isHidden else { return nil } + let frame = source.convert(source.bounds, to: view) + guard frame.width > 1, frame.height > 1, view.bounds.intersects(frame) else { return nil } + return source + } + + private static func cornerRadius(of view: UIView) -> CGFloat { + var queue = [view] + var depth = 0 + while !queue.isEmpty, depth < 4 { + for candidate in queue where candidate.layer.cornerRadius > 0 { return candidate.layer.cornerRadius } + queue = queue.flatMap(\.subviews) + depth += 1 + } + return 0 + } + + private func makeTransitionView(_ image: UIImage, frame: CGRect) -> UIImageView { + let transition = UIImageView(image: image) + transition.contentMode = .scaleAspectFill + transition.clipsToBounds = true + transition.frame = frame + view.addSubview(transition) + return transition + } + + /// Returns once the open transition has finished and the thumbnails are on screen again. + func untilRevealed() async { + guard !revealed else { return } + await withCheckedContinuation { revealWaiters.append($0) } + } + + func animateIn() { + view.layoutIfNeeded() + let page = pages[currentIndex] + let reveal = { [weak self] in + guard let self else { return } + self.pager.isHidden = false + self.transitioning = false + self.revealed = true + for waiter in self.revealWaiters { waiter.resume() } + self.revealWaiters.removeAll() + self.setNeedsStatusBarAppearanceUpdate() + UIAccessibility.post(notification: .screenChanged, argument: page.imageView) + if self.closeRequested { self.close() } + } + guard let image = page.image, let source = visibleSource(currentIndex) else { + pager.isHidden = false + pager.alpha = 0 + setBarsVisible(true) + UIView.animate(withDuration: reduceMotion ? 0.2 : 0.25, animations: { + self.backdrop.alpha = 1 + self.pager.alpha = 1 + }, completion: { _ in reveal() }) + return + } + let transition = makeTransitionView(image, frame: source.convert(source.bounds, to: view)) + transition.layer.cornerRadius = Self.cornerRadius(of: source) + let sourceAlpha = source.alpha + source.alpha = 0 + let target = page.fittedFrame(in: view) + let animator = UIViewPropertyAnimator(duration: 0.42, dampingRatio: 0.86) { + transition.frame = target + transition.layer.cornerRadius = 0 + self.backdrop.alpha = 1 + } + setBarsVisible(true) + animator.addCompletion { _ in + source.alpha = sourceAlpha + transition.removeFromSuperview() + reveal() + } + animator.startAnimation() + } + + /// Closes back into the current page's thumbnail, or away in the drag's direction when it is gone. + func close(velocity: CGPoint = .zero) { + closeRequested = true + guard !transitioning, !closing else { return } + closing = true + transitioning = true + setNeedsStatusBarAppearanceUpdate() + setBarsVisible(false) + let page = pages[currentIndex] + guard let image = page.image else { + UIView.animate(withDuration: 0.2, animations: { self.view.alpha = 0 }, completion: { _ in self.finishClose() }) + return + } + let transition = makeTransitionView(image, frame: page.imageView.convert(page.imageView.bounds, to: view)) + pager.isHidden = true + guard let source = visibleSource(currentIndex) else { + let direction: CGFloat = velocity.y < 0 ? -1 : 1 + let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeIn) { + transition.center.y += direction * self.view.bounds.height + self.backdrop.alpha = 0 + if self.reduceMotion { transition.alpha = 0 } + } + animator.addCompletion { _ in self.finishClose() } + animator.startAnimation() + return + } + let sourceAlpha = source.alpha + source.alpha = 0 + let target = source.convert(source.bounds, to: view) + let radius = Self.cornerRadius(of: source) + let speed = hypot(velocity.x, velocity.y) + let distance = hypot(target.midX - transition.center.x, target.midY - transition.center.y) + let initial = distance > 0 ? CGVector(dx: velocity.x / distance, dy: velocity.y / distance) : .zero + let timing = UISpringTimingParameters(dampingRatio: 0.88, initialVelocity: speed > 0 ? initial : .zero) + let animator = UIViewPropertyAnimator(duration: 0.4, timingParameters: timing) + animator.addAnimations { + transition.frame = target + transition.layer.cornerRadius = radius + self.backdrop.alpha = 0 + } + animator.addCompletion { _ in + source.alpha = sourceAlpha + self.finishClose() + } + animator.startAnimation() + } + + private func finishClose() { + presentingViewController?.dismiss(animated: false) { [onDismissed] in onDismissed() } + } + + // MARK: Gestures + + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { + guard gestureRecognizer === dismissPan else { return true } + guard !transitioning, !pager.isDragging, !pager.isDecelerating, + let page = pages[safe: currentIndex], !page.isZoomed + else { return false } + let velocity = dismissPan.velocity(in: view) + return abs(velocity.y) > abs(velocity.x) + } + + @objc private func handleDismissPan(_ gesture: UIPanGestureRecognizer) { + let page = pages[currentIndex] + let translation = gesture.translation(in: view) + switch gesture.state { + case .began: + chromeHiddenBeforeDrag = chromeHidden + dragAnchor = gesture.location(in: page) + setChromeHidden(true) + case .changed: + // Shrink around the finger, as Photos does, so the touched spot stays under it. + let progress = min(1, abs(translation.y) / (view.bounds.height / 2)) + let scale = 1 - 0.3 * progress + let offset = CGPoint(x: dragAnchor.x - page.bounds.midX, y: dragAnchor.y - page.bounds.midY) + page.transform = CGAffineTransform(translationX: translation.x + (1 - scale) * offset.x, + y: translation.y + (1 - scale) * offset.y).scaledBy(x: scale, y: scale) + backdrop.alpha = 1 - progress + case .ended, .cancelled, .failed: + let velocity = gesture.velocity(in: view) + let flung = abs(velocity.y) > 800 && velocity.y * translation.y > 0 + if gesture.state == .ended, flung || abs(translation.y) > 120 { + close(velocity: velocity) + } else { + UIViewPropertyAnimator(duration: 0.35, dampingRatio: 0.8) { + page.transform = .identity + self.backdrop.alpha = 1 + }.startAnimation() + setChromeHidden(chromeHiddenBeforeDrag) + } + default: + break + } + } + + @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) { + guard !transitioning, let page = pages[safe: currentIndex] else { return } + page.toggleZoom(at: gesture.location(in: page)) + } + + @objc private func handleSingleTap() { + guard !transitioning else { return } + setChromeHidden(!chromeHidden) + } + + private func setChromeHidden(_ hidden: Bool) { + guard chromeHidden != hidden else { return } + chromeHidden = hidden + setBarsVisible(!hidden) + UIView.animate(withDuration: 0.2) { self.setNeedsStatusBarAppearanceUpdate() } + setNeedsUpdateOfHomeIndicatorAutoHidden() + } + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + guard scrollView === pager, !transitioning, !isLayingOut, pager.bounds.width > 0 else { return } + let index = Int((pager.contentOffset.x / pager.bounds.width).rounded()) + guard pages.indices.contains(index), index != currentIndex else { return } + pages[currentIndex].resetZoom(animated: false) + currentIndex = index + updateTitle() + onPageChange(index) + } + + private func scroll(to index: Int) { + guard pages.indices.contains(index), !transitioning else { return } + pager.setContentOffset(CGPoint(x: CGFloat(index) * pager.bounds.width, y: 0), animated: !reduceMotion) + } + + // MARK: Share, keyboard and accessibility + + private func save() { + let image = pages[currentIndex].isFull ? pages[currentIndex].image : nil + // Original bytes keep the format and metadata; an SVG only has its rendered image. The copy + // belongs to this save, since closing the viewer deletes its files before Photos may read them. + let original = fileForPage(currentIndex).flatMap { file -> URL? in + guard file.pathExtension.lowercased() != "svg", let source = CGImageSourceCreateWithURL(file as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil } + let copy = FileManager.default.temporaryDirectory.appendingPathComponent("t3-save-\(UUID().uuidString)") + .appendingPathComponent(file.lastPathComponent) + do { + try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.copyItem(at: file, to: copy) + return copy + } catch { + return nil + } + } + guard original != nil || image != nil else { return } + let cleanUp = { if let original { try? FileManager.default.removeItem(at: original.deletingLastPathComponent()) } } + PHPhotoLibrary.requestAuthorization(for: .addOnly) { [weak self] status in + guard status == .authorized || status == .limited else { + cleanUp() + DispatchQueue.main.async { self?.showSaveError("Allow T3 Code to add photos in Settings.") } + return + } + PHPhotoLibrary.shared().performChanges({ + if let original { + PHAssetCreationRequest.forAsset().addResource(with: .photo, fileURL: original, options: nil) + } else if let image { + PHAssetChangeRequest.creationRequestForAsset(from: image) + } + }, completionHandler: { saved, error in + cleanUp() + DispatchQueue.main.async { + if saved { + self?.confirmSaved() + } else { + self?.showSaveError(error?.localizedDescription ?? "Photos could not save this image.") + } + } + }) + } + } + + private func confirmSaved() { + UINotificationFeedbackGenerator().notificationOccurred(.success) + UIAccessibility.post(notification: .announcement, argument: "Saved to Photos") + saveItem.image = UIImage(systemName: "checkmark") + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in + self?.saveItem.image = UIImage(systemName: "square.and.arrow.down") + } + } + + private func showSaveError(_ message: String) { + let alert = UIAlertController(title: "Could not save image", message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } + + private func share() { + let page = pages[currentIndex] + let item: Any? = fileForPage(currentIndex) ?? (page.isFull ? page.image : nil) + guard let item else { return } + let sheet = UIActivityViewController(activityItems: [item], applicationActivities: nil) + sheet.popoverPresentationController?.sourceItem = shareItem + present(sheet, animated: true) + } + + override var canBecomeFirstResponder: Bool { true } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + becomeFirstResponder() + } + + override var keyCommands: [UIKeyCommand]? { + [ + UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(handleEscape)), + UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(handlePrevious)), + UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(handleNext)), + ] + } + + @objc private func handleEscape() { close() } + @objc private func handlePrevious() { scroll(to: currentIndex - 1) } + @objc private func handleNext() { scroll(to: currentIndex + 1) } + + override func accessibilityPerformEscape() -> Bool { + close() + return true + } + + override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool { + switch direction { + case .left: scroll(to: currentIndex + 1) + case .right: scroll(to: currentIndex - 1) + default: return false + } + UIAccessibility.post(notification: .pageScrolled, argument: counterLabel.text) + return true + } +} diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift index 932ed1d0a3e5e..3b43334b1262d 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift @@ -7,21 +7,28 @@ final class T3PresentationSources { init(_ view: UIView) { self.view = view } } - private var entries: [String: Entry] = [:] + /// The same file embedded twice registers twice; removing one copy keeps the other. + private var entries: [String: [Entry]] = [:] func register(_ view: UIView, identifier: String) { - entries[identifier] = Entry(view) + var list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view } + list.append(Entry(view)) + entries[identifier] = list } func remove(_ view: UIView, identifier: String) { - if entries[identifier]?.view == nil || entries[identifier]?.view === view { - entries.removeValue(forKey: identifier) - } + let list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view } + entries[identifier] = list.isEmpty ? nil : list } func view(for identifier: String) -> UIView? { - // Use the child bounds, not the wrapper's potentially stretched layout bounds. - entries[identifier]?.view?.subviews.first + let views = (entries[identifier] ?? []).compactMap(\.view) + // Prefer an on-screen copy, the latest first; use the child bounds, not the wrapper's stretched ones. + let source = views.last(where: { view in + guard let window = view.window else { return false } + return window.bounds.intersects(view.convert(view.bounds, to: window)) + }) ?? views.last + return source?.subviews.first } } diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift index 6732f2dae2f18..065eba4331036 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift @@ -20,6 +20,10 @@ final class T3ScrollEdgeBleedView: ExpoView { /// React Native's clipping, saved while bleeding. React Native only rewrites it when the /// `overflow` style changes, so it stays off while bleeding. private var containerClipped: Bool? + /// The bar's side is read from the root view controller, whose traits can settle after this + /// view's own during a fold; with no size change after that, nothing else would recheck. + private weak var observedWindow: UIWindow? + private var windowTraitRegistration: (any UITraitChangeRegistration)? required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -38,9 +42,33 @@ final class T3ScrollEdgeBleedView: ExpoView { override func didMoveToWindow() { super.didMoveToWindow() + observeWindowTraits() if window == nil { detach() } else { setNeedsLayout() } } + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + setNeedsLayout() + } + + private func observeWindowTraits() { + guard observedWindow !== window else { return } + if let observedWindow, let windowTraitRegistration { + observedWindow.unregisterForTraitChanges(windowTraitRegistration) + } + observedWindow = window + windowTraitRegistration = nil + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), let window { + windowTraitRegistration = window.registerForTraitChanges( + UITraitCollection.systemTraitsAffectingVerticalBarEdge + ) { [weak self] (_: UIWindow, _: UITraitCollection) in + self?.setNeedsLayout() + } + } + #endif + } + override func didAddSubview(_ subview: UIView) { super.didAddSubview(subview) setNeedsLayout() diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 243490678c530..9df738d37fa67 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -40,7 +40,7 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private let composeButton = UIButton(type: .system) private lazy var tabBarTrailing = tabBar.trailingAnchor.constraint(equalTo: trailingAnchor) private var itemsByTab: [String: UITabBarItem] = [:] - var tabs = ["threads", "pullRequests", "usage", "settings"] { + var tabs = ["threads", "pullRequests", "issues", "usage", "settings"] { didSet { if tabs != oldValue { updateItems() } } } var selectedTab = "threads" { didSet { updateSelection() } } @@ -56,6 +56,9 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { composeButton.isHidden = !showsCompose tabBarTrailing.constant = showsCompose ? (compact ? -64 : -76) : 0 setNeedsLayout() + // JS moves this view's edge by the same amount, so the bar keeps its frame and won't lay + // itself out; compose is placed only from that layout. + tabBar.setNeedsLayout() } } var appearance = "light" { @@ -106,10 +109,11 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "usage": "Usage", "settings": "Settings"] + let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"] + let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] for (tab, label) in labels { - let icon = tab == "pullRequests" ? pullRequestIcon : UIImage(systemName: symbols[tab] ?? "circle") + let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) item.accessibilityLabel = label item.accessibilityIdentifier = "workspace-tab-\(tab)" diff --git a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt index ad0de07025105..7991383590dee 100644 --- a/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt +++ b/apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalCanvasView.kt @@ -230,9 +230,7 @@ internal class TerminalCanvasView(context: Context) : View(context) { if (text.isNotEmpty() && flags and FLAG_INVISIBLE == 0) { configureTextPaint(flags, currentFrame.cellForegrounds[index]) canvas.drawText(text, left, top + baselineOffsetPx, paint) - if (flags and FLAG_OVERLINE != 0) { - canvas.drawRect(left, top + 1f, right, top + max(2f, density), paint) - } + drawOverline(canvas, flags, left, top, right) } } } @@ -335,11 +333,18 @@ internal class TerminalCanvasView(context: Context) : View(context) { if (text.isNotEmpty() && flags and FLAG_INVISIBLE == 0) { configureTextPaint(flags, currentFrame.background) canvas.drawText(text, left, top + baselineOffsetPx, paint) + drawOverline(canvas, flags, left, top, right) } } } } + private fun drawOverline(canvas: Canvas, flags: Int, left: Float, top: Float, right: Float) { + if (flags and FLAG_OVERLINE != 0) { + canvas.drawRect(left, top + 1f, right, top + max(2f, density), paint) + } + } + private fun columnAt(px: Float): Int { val cols = frame?.cols ?: return 0 return ((px - contentPadding) / cellWidthPx).toInt().coerceIn(0, max(cols - 1, 0)) diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png new file mode 100644 index 0000000000000..1e55bbd87a57f Binary files /dev/null and b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable-xxhdpi/t3_widget_hatch_tile.png differ diff --git a/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml new file mode 100644 index 0000000000000..8125e99ad560e --- /dev/null +++ b/apps/mobile/modules/t3-widget-expiry/android/src/main/res/drawable/t3_widget_hatch.xml @@ -0,0 +1,4 @@ + + diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 4ea021a0b6db9..f58db658bcc4b 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.50.tgz", + "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.58.tgz", "react-native-svg": "15.16.1", "react-native-webview": "14.0.1", "react-native-worklets": "0.13.1", diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index dac9e50afe68d..3466172fdbb0a 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -38,6 +38,11 @@ import { PullRequestReviewersScreen } from "./features/pull-requests/PullRequest import { PullRequestLabelsScreen } from "./features/pull-requests/PullRequestLabelsScreen"; import { PullRequestEditScreen } from "./features/pull-requests/PullRequestEditScreen"; import { PullRequestFilterSearchScreen } from "./features/pull-requests/PullRequestFilterSearchScreen"; +import { IssueAssigneesScreen } from "./features/issues/IssueAssigneesScreen"; +import { IssueEditScreen } from "./features/issues/IssueEditScreen"; +import { IssueLabelsScreen } from "./features/issues/IssueLabelsScreen"; +import { IssueFilterSearchScreen } from "./features/issues/IssueFilterSearchScreen"; +import { IssueRouteScreen } from "./features/issues/IssueRouteScreen"; import { RenderErrorBoundary, RenderFailureView, @@ -97,6 +102,10 @@ import { SettingsDiagnosticsRouteScreen } from "./features/diagnostics/SettingsD import { SettingsProviderAccountsRouteScreen } from "./features/settings/SettingsProviderAccountsRouteScreen"; import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen"; import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; +import { + SettingsIssueTrackerRouteScreen, + SettingsSourceControlProviderRouteScreen, +} from "./features/settings/SettingsSourceControlDetailRouteScreens"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; @@ -191,7 +200,15 @@ const SETTINGS_SCREENS = { SettingsEnvironmentSourceControl: createNativeStackScreen({ screen: SettingsEnvironmentSourceControlRouteScreen, linking: "settings/source-control", - options: settingsPage("Source control"), + options: settingsPage("Source control & issues"), + }), + SettingsSourceControlProvider: createNativeStackScreen({ + screen: SettingsSourceControlProviderRouteScreen, + options: settingsPage("Provider"), + }), + SettingsIssueTracker: createNativeStackScreen({ + screen: SettingsIssueTrackerRouteScreen, + options: settingsPage("Issue tracker"), }), SettingsEnvironmentAgentBehavior: createNativeStackScreen({ screen: SettingsThreadsRouteScreen, @@ -571,6 +588,27 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: PullRequestEditScreen, options: sheetRoute({ detent: 0.75, androidFit: true }), }), + Issue: createNativeStackScreen({ + screen: IssueRouteScreen, + linking: "issues/:environmentId/:projectId/:tracker/:scope/:issueKey", + options: pageRoute({ duoMinimize: "never" }), + }), + IssueEdit: createNativeStackScreen({ + screen: IssueEditScreen, + options: sheetRoute({ detent: 0.75, androidFit: true }), + }), + IssueLabels: createNativeStackScreen({ + screen: IssueLabelsScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueAssignees: createNativeStackScreen({ + screen: IssueAssigneesScreen, + options: SEARCH_SHEET_ROUTE, + }), + IssueFilterSearch: createNativeStackScreen({ + screen: IssueFilterSearchScreen, + options: SEARCH_SHEET_ROUTE, + }), Thread: createNativeStackScreen({ screen: ThreadRouteScreen, linking: { path: "threads/:environmentId?/:threadId?", alias: ["new/draft"] }, diff --git a/apps/mobile/src/components/ComposerSurface.tsx b/apps/mobile/src/components/ComposerSurface.tsx new file mode 100644 index 0000000000000..7cabdfd5faa92 --- /dev/null +++ b/apps/mobile/src/components/ComposerSurface.tsx @@ -0,0 +1,283 @@ +import { useState, type ReactNode } from "react"; +import { I18nManager, Platform, type ViewStyle } from "react-native"; +import Animated, { + FadeIn, + type LayoutAnimationFunction, + ReduceMotion, + useAnimatedStyle, + useDerivedValue, + useSharedValue, + withTiming, +} from "react-native-reanimated"; + +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { useAdaptiveWorkspaceLayout } from "../features/layout/AdaptiveWorkspaceLayout"; +import { useSidebarWorkspaceTabs } from "../features/layout/workspace/useSystemWorkspaceTabBar"; +import { useAndroidFloatingTabs } from "../features/settings/appearance/AppearancePreferencesProvider"; +import { compactEditorInsets } from "../features/threads/compactEditorInsets"; +import { + useDeviceType, + useDuoBottomBarInset, + useNativeLayoutMetrics, +} from "../native/native-layout-metrics"; +import type { ScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; +import { MOBILE_TYPOGRAPHY } from "../lib/typography"; +import { useUniwindTheme } from "../lib/useUniwindTheme"; +import { GlassSurface } from "./ui/GlassSurface"; + +const COLLAPSED_EDITOR_DEFAULT_INSET = 6; +// iOS puts line-height slack above glyphs. DM Sans's lowercase midline is +// descender (0.31em) + half x-height (0.504em) above the line bottom. +const LOWERCASE_MIDLINE_EM = 0.562; + +function lowercaseMidline(text: ScaledTextRole): number { + return text.lineHeight - LOWERCASE_MIDLINE_EM * text.fontSize; +} + +function collapsedEditorInset(text: ScaledTextRole): number { + const shift = lowercaseMidline(text) - lowercaseMidline(MOBILE_TYPOGRAPHY.body); + return Math.max(0, Math.round(COLLAPSED_EDITOR_DEFAULT_INSET - shift)); +} + +const EXPANDED_EDITOR_INSET = 14; +// Room under the expanded editor for the toolbar row. +const EXPANDED_EDITOR_BOTTOM = 52; + +export function useCompactComposerEditor(text: ScaledTextRole, value: string, animate: boolean) { + const [contentSize, setContentSize] = useState({ width: 0, height: 0 }); + const [compactWidth, setCompactWidth] = useState(0); + const contentHeight = contentSize.height; + const rowWidth = useSharedValue(0); + const editorX = useSharedValue(0); + const editorWidth = useSharedValue(0); + const inset = + Platform.OS === "android" ? COLLAPSED_EDITOR_DEFAULT_INSET : collapsedEditorInset(text); + const minimum = Math.max(INLINE_EDITOR_HEIGHT, Math.ceil(text.lineHeight) + 2 * inset); + const height = Math.max( + minimum, + Math.min(text.lineHeight * 4 + 2 * inset, contentHeight + 2 * inset), + ); + // A line that fits the expanded editor may still overflow its compact slot. + // Compare its measured width too so widening cannot trigger a collapse loop. + const isExpanded = + value.length > 0 && + (contentHeight > text.lineHeight * 1.5 || + (compactWidth > 0 && contentSize.width > compactWidth)); + const compactRowHeight = Math.max(44, minimum); + const compactBottom = (compactRowHeight - minimum) / 2; + const isRTL = I18nManager.isRTL; + const expandedRowHeight = height + EXPANDED_EDITOR_BOTTOM; + const expansion = useDerivedValue(() => { + const target = isExpanded ? 1 : 0; + return animate + ? withTiming(target, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : target; + }); + const editorStyle = useAnimatedStyle(() => { + const compactInsets = compactEditorInsets({ + slotX: editorX.value, + slotWidth: editorWidth.value, + rowWidth: rowWidth.value, + isRTL, + }); + const progress = expansion.value; + // Hanging from the row top lets the text ride the growing edge and ignore the stale + // height measured while it still wrapped in the compact slot. Layout props only: + // Reanimated applies transforms frames ahead of layout, which tore the text from its frame. + return { + position: "absolute", + overflow: "hidden", + // The compact slot is unknown until its first layout, so the editor would draw over the + button. + opacity: isExpanded || editorWidth.value > 0 ? 1 : 0, + height, + top: compactBottom * (1 - progress), + left: compactInsets.left + (EXPANDED_EDITOR_INSET - compactInsets.left) * progress, + // Snapping the far edge keeps the line from rewrapping while the near edge moves. + right: isExpanded ? EXPANDED_EDITOR_INSET : compactInsets.right, + }; + }); + const containerStyle = useAnimatedStyle(() => ({ + height: compactRowHeight + (expandedRowHeight - compactRowHeight) * expansion.value, + })); + return { + isExpanded, + containerStyle, + // The expanded toolbar takes the row the text is leaving; reveal it once the text has lifted. + // An entering animation hides it from its first frame, which a shared-value opacity cannot. + toolbarControlsEntering: + animate && isExpanded + ? FadeIn.delay(COMPOSER_TRANSITION_DURATION_MS / 2) + .duration(COMPOSER_TRANSITION_DURATION_MS / 2) + .reduceMotion(ReduceMotion.System) + : undefined, + editorStyle, + onRowLayout: (event: { nativeEvent: { layout: { width: number } } }) => { + rowWidth.set(event.nativeEvent.layout.width); + }, + onEditorLayout: (event: { nativeEvent: { layout: { x: number; width: number } } }) => { + // The expanded toolbar gives this slot to the model control. Keep the + // compact geometry for the return transition, rather than recording zero. + if (!isExpanded) { + editorX.set(event.nativeEvent.layout.x); + editorWidth.set(event.nativeEvent.layout.width); + setCompactWidth(Math.max(0, event.nativeEvent.layout.width - 8)); + } + }, + editorProps: { + singleLineCentered: !isExpanded, + scrollEnabled: Platform.OS === "android" || contentHeight >= text.lineHeight * 4, + contentInsetVertical: inset, + onContentSizeChange: (size: { width: number; height: number }) => { + setContentSize(size); + }, + style: { flex: 1 }, + }, + }; +} + +export const COMPOSER_TRANSITION_DURATION_MS = 220; +// Side panes animate dock width; nested horizontal transitions would make the surface trail the toolbar. +const composerHeightTransition: LayoutAnimationFunction = (values) => { + "worklet"; + const timing = { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }; + return { + initialValues: { + originX: values.targetOriginX, + originY: values.currentOriginY, + width: values.targetWidth, + height: values.currentHeight, + }, + animations: { + originX: values.targetOriginX, + originY: withTiming(values.targetOriginY, timing), + width: values.targetWidth, + height: withTiming(values.targetHeight, timing), + }, + }; +}; +const COMPOSER_LAYOUT_TRANSITION = Platform.OS === "android" ? undefined : composerHeightTransition; +// Share of the one-row composer the draft keeps; a long model name truncates first. +export const INLINE_EDITOR_MIN_WIDTH = "40%"; +const INLINE_EDITOR_HEIGHT = 36; + +const AnimatedGlassSurface = Animated.createAnimatedComponent(GlassSurface); + +export function ComposerSurface(props: { + readonly children: ReactNode; + readonly style: ViewStyle; + readonly animateLayout?: boolean; +}) { + const colors = useUniwindTheme(); + const targetBorderRadius = + typeof props.style.borderRadius === "number" ? props.style.borderRadius : 0; + const shouldAnimate = props.animateLayout !== false && Platform.OS !== "android"; + const animatedBorderRadius = useDerivedValue(() => + shouldAnimate + ? withTiming(targetBorderRadius, { + duration: COMPOSER_TRANSITION_DURATION_MS, + reduceMotion: ReduceMotion.System, + }) + : targetBorderRadius, + ); + const borderCurve = props.style.borderCurve; + const animatedShapeStyle = useAnimatedStyle(() => ({ + borderRadius: animatedBorderRadius.value, + ...(borderCurve ? { borderCurve } : {}), + })); + const layoutTransition = shouldAnimate ? COMPOSER_LAYOUT_TRANSITION : undefined; + + // Animate every native frame or glass and content jump to final height inside the clip. + return ( + + + {null} + + + {props.children} + + + ); +} + +/** Space below the composer pill, inside the bottom inset it is given. */ +export const COMPOSER_BOTTOM_GUTTER = 6; + +/** Control size and pill shape: larger beside a sidebar tab picker and on iPad. */ +export function useComposerChrome() { + const { layout } = useAdaptiveWorkspaceLayout(); + const floatingSidebarComposer = useAndroidFloatingTabs() && layout.usesSplitView; + const sidebarWorkspaceTabs = useSidebarWorkspaceTabs(); + const deviceType = useDeviceType(); + const usesLargeControls = sidebarWorkspaceTabs === "picker" || deviceType === "pad"; + return { + usesLargeControls, + controlSize: usesLargeControls ? ("large" as const) : ("regular" as const), + borderRadius: usesLargeControls ? 31 : 27, + paddingVertical: usesLargeControls ? 9 : floatingSidebarComposer ? 6 : 2, + }; +} + +/** + * The inset below a composer pinned to the bottom of a page. Fixed while the keyboard animates: + * changing it at keyboardDidHide makes the composer land low, then jump back above the safe area. + */ +export function useComposerBottomInset() { + const insets = useSafeAreaInsets(); + const windowMetrics = useNativeLayoutMetrics(); + const { layout } = useAdaptiveWorkspaceLayout(); + const bottomBarInset = useDuoBottomBarInset(); + const hasSidebarTabBar = useSidebarWorkspaceTabs() === "picker"; + // A pushed screen temporarily inherits the outgoing tab bar's safe area. + // Use the window edge so hiding that bar cannot move the composer mid-push. + const bottomSafeArea = + Platform.OS === "ios" ? (windowMetrics?.safeArea.bottom ?? insets.bottom) : insets.bottom; + // The pill already adds its own gutter; iPad and Duo align its edge with the native bar. + const alignedBottomInset = + bottomBarInset ?? + (Platform.OS === "ios" && Platform.isPad + ? Math.max(bottomSafeArea, 12) - (layout.usesSplitView ? 5 : 0) + : undefined); + // The Duo's floating sidebar pill ends three points below the composer's usual gutter. + return Math.max( + 0, + (alignedBottomInset !== undefined + ? alignedBottomInset - COMPOSER_BOTTOM_GUTTER + : Math.max(bottomSafeArea, 12)) - (hasSidebarTabBar ? 3 : 0), + ); +} + +/** The editor's text style: the composer's scaled role in the theme's foreground color. */ +export function useComposerTextStyle(text: ScaledTextRole) { + return { ...text, color: useUniwindTheme()["--color-foreground"] }; +} diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index b34c27bd471f3..5333af3ea577a 100644 --- a/apps/mobile/src/components/ui/AppSymbol.android.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.android.tsx @@ -1,6 +1,7 @@ import type { Icon } from "@tabler/icons-react-native/types"; /* Package-root imports eagerly register the entire Tabler icon set in Metro. */ import IconAdjustmentsHorizontal from "@tabler/icons-react-native/IconAdjustmentsHorizontal"; +import IconAlarm from "@tabler/icons-react-native/IconAlarm"; import IconAlignLeft from "@tabler/icons-react-native/IconAlignLeft"; import IconAlertCircle from "@tabler/icons-react-native/IconAlertCircle"; import IconAlertTriangle from "@tabler/icons-react-native/IconAlertTriangle"; @@ -91,6 +92,7 @@ import IconListNumbers from "@tabler/icons-react-native/IconListNumbers"; import IconMenu2 from "@tabler/icons-react-native/IconMenu2"; import IconMessageCircleQuestion from "@tabler/icons-react-native/IconMessageCircleQuestion"; import IconMessage from "@tabler/icons-react-native/IconMessage"; +import IconMail from "@tabler/icons-react-native/IconMail"; import IconMessageDots from "@tabler/icons-react-native/IconMessageDots"; import IconMessagePlus from "@tabler/icons-react-native/IconMessagePlus"; import IconMinus from "@tabler/icons-react-native/IconMinus"; @@ -148,6 +150,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, "arrow.branch": IconGitBranch, "arrow.left": IconArrowLeft, "arrow.right": IconArrowRight, @@ -188,6 +191,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "circle.inset.filled": IconCircleDot, "circle.dashed.inset.filled": IconCircleDot, "calendar.badge.clock": IconCalendarClock, + alarm: IconAlarm, clock: IconClock, timer: IconClock, "face.smiling": IconMoodPlus, @@ -208,6 +212,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { ellipsis: IconDots, moon: IconMoon, "ellipsis.circle": IconDotsCircleHorizontal, + "envelope.badge": IconMail, "exclamationmark.triangle": IconAlertTriangle, "exclamationmark.circle": IconAlertCircle, eye: IconEye, @@ -300,6 +305,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon @@ -311,6 +317,7 @@ const SF_ICON_LOOKUP: Partial< | "git.pull-request.closed" | "git.pull-request.draft" | "git.commit" + | "git.issue" | "file.diff" | "robot", Icon diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx index 146a9ccb305e7..896765db5d233 100644 --- a/apps/mobile/src/components/ui/AppSymbol.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.tsx @@ -4,6 +4,7 @@ import IconGitCommit from "@tabler/icons-react-native/IconGitCommit"; import IconGitPullRequestClosed from "@tabler/icons-react-native/IconGitPullRequestClosed"; import IconGitPullRequestDraft from "@tabler/icons-react-native/IconGitPullRequestDraft"; import type { SFSymbol } from "expo-symbols"; +import IconCircleDot from "@tabler/icons-react-native/IconCircleDot"; import IconGitPullRequest from "@tabler/icons-react-native/IconGitPullRequest"; import IconFileDiff from "@tabler/icons-react-native/IconFileDiff"; import IconRobot from "@tabler/icons-react-native/IconRobot"; @@ -23,6 +24,7 @@ const CUSTOM_ICONS = { "git.pull-request.closed": IconGitPullRequestClosed, "git.pull-request.draft": IconGitPullRequestDraft, "git.commit": IconGitCommit, + "git.issue": IconCircleDot, robot: IconRobot, }; diff --git a/apps/mobile/src/components/ui/FilePreviewSession.tsx b/apps/mobile/src/components/ui/FilePreviewSession.tsx index a7a60ce5555b4..c9d950a3b58ac 100644 --- a/apps/mobile/src/components/ui/FilePreviewSession.tsx +++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx @@ -11,7 +11,12 @@ import { } from "../../lib/attachmentDownload"; import { usePreviewPresentation } from "../../lib/previewPresentation"; import { refreshAssetUrl } from "../../state/assets"; -import { filePreviewGallery, filePreviewKey, filePreviewName } from "../../lib/filePreviewGallery"; +import { + filePreviewGallery, + filePreviewKey, + filePreviewName, + filePreviewSourceIdentifier, +} from "../../lib/filePreviewGallery"; import { FilePreviewGallery } from "./FilePreviewGallery"; import type { MediaActionsSource } from "../../lib/mediaActionsSource"; import type { @@ -155,6 +160,7 @@ function ResolvedFilePreview( return { ...item, name: filePreviewName(item), + sourceIdentifier: filePreviewSourceIdentifier(item), ...(uri ? { uri } : uri === null ? { failed: true } : {}), }; }); diff --git a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx index 3913eaa47557b..db5cf357a900a 100644 --- a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx +++ b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx @@ -74,11 +74,11 @@ function ConfiguredConnectOnboardingRouteScreen() { contentInsetAdjustmentBehavior="automatic" showsVerticalScrollIndicator={false} className="flex-1" - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} contentContainerStyle={{ gap: 16, paddingHorizontal: 20, paddingTop: 16, + paddingBottom: Math.max(insets.bottom, 18) + 18, }} refreshControl={} > diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx index 22a266c8db9ac..b0d78ef3acbce 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx @@ -47,7 +47,21 @@ vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children })); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, - AppTextInput: () => null, + AppTextInput: ({ + accessibilityLabel, + value, + onChangeText, + }: { + accessibilityLabel: string; + value: string; + onChangeText: (value: string) => void; + }) => ( + onChangeText(event.currentTarget.value)} + /> + ), })); vi.mock("../../components/ui/FrostedCutout", () => ({ FrostedCutout: () => null })); vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); @@ -104,3 +118,40 @@ it("does not show another feature's error as a pairing failure", () => { // Leaving the form must not wipe an error that belongs to another screen. expect(harness.pendingConnectionError).toBe("Could not send the message."); }); + +it("splits a pasted pairing link and preserves the code during address edits", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + vi.stubGlobal("__DEV__", false); + harness.pendingConnectionError = null; + const container = document.createElement("div"); + const root = createRoot(container); + + try { + act(() => root.render()); + const address = container.querySelector('input[aria-label="Address"]')!; + const code = container.querySelector('input[aria-label="Code"]')!; + const enter = (input: HTMLInputElement, value: string) => { + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + value, + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + }; + + enter(code, "manual-code"); + enter(address, " http://100.82.53.91:3773/pair#token=test-pairing-code\n"); + expect(address.value).toBe("http://100.82.53.91:3773"); + expect(code.value).toBe("test-pairing-code"); + + enter(code, "replacement-code"); + for (const value of ["", "100.82.53.92:3773", "http://100.82.53.92:3773/"]) { + enter(address, value); + expect(address.value).toBe(value); + expect(code.value).toBe("replacement-code"); + } + } finally { + act(() => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 80f2ecc77c02d..44d2da810ca16 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -96,7 +96,13 @@ function PairingForm({ }; const handleHostChange = (value: string) => { - setHostInput(value); + const pairing = parsePairingUrl(value); + if (pairing.code) { + setHostInput(pairing.host); + setCodeInput(pairing.code); + } else { + setHostInput(value); + } clearError(); }; @@ -196,10 +202,10 @@ function PairingForm({ keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false} className="flex-1" - contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }} contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 4, + paddingBottom: Math.max(insets.bottom, 18) + 18, }} > diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx index 2d29be6d8b5ec..8957f95c8a97e 100644 --- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx +++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsx @@ -219,6 +219,7 @@ function setup(integrated = false) { const onDebug: NonNullable = (event) => handlePullRequestDiffDebugEvent(event, { rowCount: data.rows.length, + lastShownRowIndex: data.rows.length - 1, targetFileId, focusIndex: -1, isIos: true, diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index ee28a19e1e48d..9050776b5be3e 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -2,8 +2,6 @@ import { uuidv4 } from "../../lib/uuid"; import { ThreadUndoNotice } from "./ThreadUndoNotice"; import { use } from "react"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; -import * as Arr from "effect/Array"; -import * as Order from "effect/Order"; import { useNavigation } from "@react-navigation/native"; import { useMemo, useState } from "react"; import { Platform } from "react-native"; @@ -41,7 +39,7 @@ import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; import { WorkspaceListEmptyDetail } from "../layout/workspace/WorkspaceListEmptyDetail"; import { WorkspaceListHeader } from "../layout/workspace/WorkspaceListHeader"; -import { buildHomeListFilterMenuItems } from "./home-list-filter-menu"; +import { buildHomeListFilterMenuItems, homeListFilterEnvironments } from "./home-list-filter-menu"; export function HomeRouteScreen() { const nativePrimaryColumn = use(NativePrimaryColumnContext); @@ -108,19 +106,7 @@ export function HomeRouteScreen() { const pendingTasks = usePendingNewTasks(); const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(selectThreadRoute); - const connectionStateByEnvironmentId = new Map( - workspaceEnvironments.map( - (environment) => [environment.environmentId, environment.connectionState] as const, - ), - ); - const environments = Arr.sort( - Object.values(savedConnectionsById).map((connection) => ({ - environmentId: connection.environmentId, - label: connection.environmentLabel, - connectionState: connectionStateByEnvironmentId.get(connection.environmentId) ?? "available", - })), - Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label), - ); + const environments = homeListFilterEnvironments(workspaceEnvironments); const availableEnvironmentIds = useMemo( () => new Set(environments.map((environment) => environment.environmentId)), [environments], diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index e151b46c60231..d494391003e18 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, @@ -204,7 +204,6 @@ export function HomeScreen(props: HomeScreenProps) { ); const columnMetrics = useNativeColumnLayoutMetrics(); const activeNewTask = useActiveNewTask(); - const selectedThreadKey = activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null); const fullSwipeWidth = primaryColumn && columnMetrics ? columnMetrics.width - 20 : undefined; const queuedThreadKeys = useQueuedThreadKeys(); const openSwipeableRef = useRef(null); @@ -408,6 +407,7 @@ export function HomeScreen(props: HomeScreenProps) { const { layout: threadListV2Layout, items: threadListV2Items, + selectedThreadKey, contentOnlyThreadKeys, olderSettledShelf, } = useThreadListV2({ @@ -431,7 +431,7 @@ export function HomeScreen(props: HomeScreenProps) { workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded, - selectedThreadKey, + selectedThreadKey: activeNewTask ? null : (primaryColumn?.selectedThreadKey ?? null), }); // Called as `props.onSelectThread(...)`, the compiler would cache this handler on the whole // props object, which is new on every render of Home's parent. @@ -708,6 +708,12 @@ export function HomeScreen(props: HomeScreenProps) { detail={`Looking for "${props.searchQuery}" in messages.`} variant={Platform.OS === "android" ? "plain" : undefined} /> + ) : hasSearchQuery && threadSearch.failed ? ( + ) : hasSearchQuery ? ( { settleLaunchSplashHomeRows(); diff --git a/apps/mobile/src/features/home/home-list-filter-menu.test.ts b/apps/mobile/src/features/home/home-list-filter-menu.test.ts new file mode 100644 index 0000000000000..a6c6b95984e9b --- /dev/null +++ b/apps/mobile/src/features/home/home-list-filter-menu.test.ts @@ -0,0 +1,35 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import type { WorkspaceEnvironment } from "../../state/workspaceModel"; +import { homeListFilterEnvironments } from "./home-list-filter-menu"; + +function environment( + environmentId: string, + environmentLabel: string, + isEnabled: boolean, +): WorkspaceEnvironment { + return { + environmentId: environmentId as EnvironmentId, + environmentLabel, + displayUrl: "", + isRelayManaged: false, + isEnabled, + connectionState: isEnabled ? "connected" : "available", + connectionError: null, + connectionErrorTraceId: null, + }; +} + +it("offers only switched-on environments, sorted by label", () => { + expect( + homeListFilterEnvironments([ + environment("env-studio", "Studio", true), + environment("env-laptop", "Laptop", false), + environment("env-desk", "Desk", true), + ]), + ).toEqual([ + { environmentId: "env-desk", label: "Desk", connectionState: "connected" }, + { environmentId: "env-studio", label: "Studio", connectionState: "connected" }, + ]); +}); diff --git a/apps/mobile/src/features/home/home-list-filter-menu.ts b/apps/mobile/src/features/home/home-list-filter-menu.ts index 617c3fa0988ef..1d6da0e8d765c 100644 --- a/apps/mobile/src/features/home/home-list-filter-menu.ts +++ b/apps/mobile/src/features/home/home-list-filter-menu.ts @@ -1,12 +1,28 @@ import type { EnvironmentId } from "@t3tools/contracts"; +import * as Arr from "effect/Array"; +import * as Order from "effect/Order"; import type { AppBarMenuItem } from "../../components/ui/AppBar.types"; +import type { WorkspaceEnvironment } from "../../state/workspaceModel"; export interface HomeListFilterMenuEnvironment { readonly environmentId: EnvironmentId; readonly label: string; } +export function homeListFilterEnvironments(environments: ReadonlyArray) { + return Arr.sort( + environments + .filter((environment) => environment.isEnabled) + .map((environment) => ({ + environmentId: environment.environmentId, + label: environment.environmentLabel, + connectionState: environment.connectionState, + })), + Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label), + ); +} + export interface HomeListFilterMenuProject { readonly key: string; readonly label: string; diff --git a/apps/mobile/src/features/home/home-route-visibility.test.tsx b/apps/mobile/src/features/home/home-route-visibility.test.tsx index dae399420944a..1dba3c32a0dc3 100644 --- a/apps/mobile/src/features/home/home-route-visibility.test.tsx +++ b/apps/mobile/src/features/home/home-route-visibility.test.tsx @@ -41,6 +41,7 @@ function setup() { presented: true, selectedThreadKey: "env-1:thread-1", selectedPullRequestKey: null, + selectedIssueKey: null, }; return { registry, diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index 5a0305ca23a86..40c7c58f15f31 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -52,6 +52,8 @@ const COMPACT_ACTION_CIRCLE_SIZE = 28; const COMPACT_ACTION_ICON_SIZE = 13; // At the default app text size, "Unarchive", the longest label, fills its slot at about 1.12x. const ACTION_LABEL_MAX_FONT_SCALE = 1.1; +const ACTION_LABEL_MIN_HEIGHT = 14; +const ACTION_LABEL_OFFSET = 2; const THREAD_SWIPE_ACTIONS_WIDTH = ACTION_ITEM_WIDTH * 2; const THREAD_SWIPE_SPRING = { @@ -82,6 +84,14 @@ function swipeActionsWidth(hasSecondaryAction: boolean) { return hasSecondaryAction ? THREAD_SWIPE_ACTIONS_WIDTH : ACTION_ITEM_WIDTH; } +function fullActionStackHeight(labelLineHeight: number, fontScale: number) { + const labelHeight = labelLineHeight * Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE); + // The offset shifts the label after centering, so it needs room on both sides. + return ( + ACTION_CIRCLE_SIZE + ACTION_LABEL_OFFSET * 2 + Math.max(ACTION_LABEL_MIN_HEIGHT, labelHeight) + ); +} + function resolveSecondaryAction(input: { readonly close: () => void; readonly onDelete: () => void; @@ -226,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; @@ -239,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; @@ -259,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); @@ -268,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; @@ -284,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) => { @@ -292,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(() => { @@ -336,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); @@ -344,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( @@ -422,7 +461,12 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { const handleSwipeableClose = useCallback(() => { if (swipeableRef.current) onSwipeableClose?.(swipeableRef.current); }, [onSwipeableClose]); - const compactActions = props.compactActions === true; + const { fontScale } = useWindowDimensions(); + const fullActionsHeight = fullActionStackHeight(useScaledTextRole("micro").lineHeight, fontScale); + const [measuredRowHeight, setMeasuredRowHeight] = useState(0); + const compactActions = + props.compactActions === true || + (measuredRowHeight > 0 && measuredRowHeight < fullActionsHeight); const { secondaryAction, threadTitle } = props; // Swipeable calls this on every render; returning the previous element while nothing it shows // changed keeps a selection change from re-rendering the hidden actions. @@ -439,6 +483,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { actionStyle, backgroundColor, compactActions, + measuredRowHeight, fullSwipeAction, fullSwipeThreshold, handleFullSwipeArmedChange, @@ -462,6 +507,7 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { - { - rowHeight.set(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 */ + } + + + + ); } @@ -538,6 +587,7 @@ function SwipeActionButton(props: { readonly label: string; readonly menu?: ThreadSwipeAction["menu"]; readonly onPress: () => void; + readonly rowHeight: number; readonly stretchesOnFullSwipe: boolean; readonly translation: SharedValue; }) { @@ -551,7 +601,13 @@ function SwipeActionButton(props: { const circleSize = props.compact ? COMPACT_ACTION_CIRCLE_SIZE : ACTION_CIRCLE_SIZE; const iconSize = props.compact ? COMPACT_ACTION_ICON_SIZE : ACTION_ICON_SIZE; const { fontScale } = useWindowDimensions(); - const labelLineHeight = useScaledTextRole("micro").lineHeight; + // Even compact actions can outgrow a short row at large app text sizes; shrink the label's + // leading to the room left under the circle. + const labelRoom = + props.compact && props.rowHeight > 0 + ? (props.rowHeight - circleSize) / Math.min(fontScale, ACTION_LABEL_MAX_FONT_SCALE) + : Infinity; + const labelLineHeight = Math.min(useScaledTextRole("micro").lineHeight, labelRoom); // Android scales lineHeight by the full font scale, past maxFontSizeMultiplier. const labelTextStyle = { lineHeight: @@ -691,7 +747,11 @@ function SwipeActionButton(props: { {/* An offset, not padding: padding would grow the box and move the circle at 1x. */} @@ -743,6 +803,7 @@ function ThreadSwipeActions(props: { readonly fullSwipeThreshold: number; readonly onFullSwipeArmedChange: (armed: boolean) => void; readonly primaryAction: ThreadSwipeAction; + readonly rowHeight: number; readonly secondaryAction: ThreadSwipeSecondaryAction | null; readonly translation: SharedValue; }) { @@ -782,6 +843,7 @@ function ThreadSwipeActions(props: { icon={props.primaryAction.icon} label={props.primaryAction.label} onPress={props.primaryAction.onPress} + rowHeight={props.rowHeight} stretchesOnFullSwipe={fullSwipeIsPrimary} translation={props.translation} /> @@ -797,6 +859,7 @@ function ThreadSwipeActions(props: { label={secondaryAction.label} menu={secondaryAction.menu} onPress={secondaryAction.onPress} + rowHeight={props.rowHeight} stretchesOnFullSwipe={!fullSwipeIsPrimary} translation={props.translation} /> diff --git a/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx b/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx new file mode 100644 index 0000000000000..6d182964084a7 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueAssigneesScreen.tsx @@ -0,0 +1,106 @@ +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useAtom } from "@effect/atom-react"; +import { + issueAssigneeHeld, + issueAssigneesAfterPicks, + issuePicksAfterFailedWrite, + issuePicksFor, + issueWriteAfterPicks, + noIssuePicks, +} from "@t3tools/client-runtime/issue-selection"; +import { isSelected, toggleSelection } from "@t3tools/client-runtime/pull-request-selection"; +import type { IssueAssigneeCandidate } from "@t3tools/contracts"; +import { useEffect, useState } from "react"; + +import * as Dialog from "../../components/ui/Dialog"; +import { issueEnvironment, refreshIssueLists } from "../../state/issues"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { PullRequestAvatar } from "../pull-requests/PullRequestPresentation"; +import { IssueCandidatesSheet } from "./IssueCandidatesSheet"; +import { issueParamsKey, issueTarget, type IssueParams } from "./issueParams"; +import { issueAssigneePicksFamily } from "./issuePicks"; +import { issueCommandError, useIssueAccess } from "./issuePresentation"; + +export function IssueAssigneesScreen({ route }: StaticScreenProps) { + const navigation = useNavigation(); + const target = issueTarget(route.params); + const detail = useEnvironmentQuery(issueEnvironment.detail(target)).data; + const access = useIssueAccess(route.params, detail); + const result = useEnvironmentQuery(issueEnvironment.candidates(target)); + const update = useAtomCommand(issueEnvironment.update, { reportFailure: false }); + const [query, setQuery] = useState(""); + // The atom carries a closed sheet's picks to the next one; this sheet's own live here. + const [stored, setStored] = useAtom(issueAssigneePicksFamily(issueParamsKey(route.params))); + // Picks against an older read are dropped once, when the sheet opens. + const [picks, setPicks] = useState(() => + detail ? issuePicksFor(stored, detail, false) : noIssuePicks(), + ); + const own = detail ? issuePicksFor(picks, detail, true) : noIssuePicks(); + // What was last sent is read from the atom, so a write that fails while this sheet is open is + // sent again when it closes. + const current = { ...own, written: stored.basis === detail ? stored.written : null }; + const draft = current.draft; + const allowed = access?.assignees === true; + const held = (candidate: IssueAssigneeCandidate) => + detail ? issueAssigneeHeld(detail, candidate) : false; + const needle = query.trim().toLowerCase(); + const candidates = (result.data?.assignees ?? []).filter((candidate) => + `${candidate.login} ${candidate.name ?? ""}`.toLowerCase().includes(needle), + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- picks are sent when the sheet leaves the navigation stack, however it is dismissed + useEffect( + () => + navigation.addListener("beforeRemove", () => { + if (!detail) return; + const assignees = issueWriteAfterPicks( + issueAssigneesAfterPicks(detail, draft), + detail.assignees.map((actor) => actor.login), + current.written, + ); + if (assignees === null) return; + const sent = { ...current, written: assignees }; + setStored(sent); + void update({ ...target, input: { ...target.input, assignees } }).then((response) => { + const failure = issueCommandError(response); + if (failure === null) return refreshIssueLists(target.environmentId); + // Picks made after this write was sent are kept. + setStored((latest) => issuePicksAfterFailedWrite(latest, sent)); + Dialog.alert("Couldn't change assignees", failure); + }); + }), + [navigation, detail, draft, current, setStored, update, target], + ); + return ( + ({ + key: candidate.id, + title: candidate.login, + ...(candidate.name ? { subtitle: candidate.name } : {}), + leading: , + // Sent when the sheet closes; a failure puts the tracker's answer back. + selected: isSelected(draft, candidate.id, held(candidate)), + }))} + allowed={allowed} + notice={ + detail && !allowed + ? (access?.blocked ?? "Changing assignees needs triage access on this tracker.") + : null + } + pending={result.isPending && !result.data} + loadError={result.data ? null : result.error} + onRetry={result.refresh} + truncated={result.data?.truncated === true} + onToggle={(id) => { + const candidate = candidates.find((entry) => entry.id === id); + if (candidate) { + setPicks({ ...current, draft: toggleSelection(draft, id, candidate, held(candidate)) }); + } + }} + /> + ); +} diff --git a/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx new file mode 100644 index 0000000000000..e4d859e2e5d71 --- /dev/null +++ b/apps/mobile/src/features/issues/IssueCandidatesSheet.tsx @@ -0,0 +1,120 @@ +import { LegendList } from "@legendapp/list/react-native"; +import type { ReactNode } from "react"; +import { Platform, View } from "react-native"; + +import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { EmptyState } from "../../components/ui/EmptyState"; +import { SelectionRow } from "../../components/ui/SelectionRow"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; +import { PullRequestSearchSheet } from "../pull-requests/PullRequestSearchSheet"; + +interface Candidate { + readonly key: string; + readonly title: string; + readonly subtitle?: string; + readonly leading: ReactNode; + readonly selected: boolean; +} + +/** The searchable checklist behind the label and assignee pickers. */ +export function IssueCandidatesSheet(props: { + readonly title: string; + readonly noun: "labels" | "people"; + readonly query: string; + readonly onQueryChange: (query: string) => void; + readonly candidates: ReadonlyArray; + readonly allowed: boolean; + readonly notice: string | null; + readonly pending: boolean; + readonly loadError: string | null; + readonly onRetry: () => void; + readonly truncated: boolean; + readonly onToggle: (key: string) => void; +}) { + const searching = props.query.trim().length > 0; + return ( + + {({ paddingBottom }) => ( + candidate.key} + extraData={props.candidates} + estimatedItemSize={64} + recycleItems + className="flex-1" + contentInsetAdjustmentBehavior="automatic" + automaticallyAdjustKeyboardInsets={Platform.OS === "ios"} + keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"} + keyboardShouldPersistTaps="handled" + showsVerticalScrollIndicator={false} + contentContainerStyle={{ paddingHorizontal: 16, paddingTop: 16, paddingBottom }} + ListHeaderComponent={ + props.notice ? ( + + {props.notice} + {props.loadError && props.candidates.length > 0 ? ( + + + + + + + + ); +} diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index be674b66520d2..b99591c92b112 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -6,6 +6,7 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell import { DEFAULT_CLIENT_SETTINGS, EnvironmentId, + type LocalApi, ProjectId, ThreadId, type ScopedThreadRef, @@ -25,6 +26,7 @@ import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/en import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; +import { readLocalApi } from "../localApi"; import type { Project } from "../types"; import Sidebar from "./Sidebar"; import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; @@ -42,6 +44,7 @@ vi.mock("../hooks/useThreadRouteTarget", { spy: true }); vi.mock("./sidebar/SidebarThreadRow", { spy: true }); vi.mock("../state/session", { spy: true }); vi.mock("../state/use-orchestration-command", { spy: true }); +vi.mock("../localApi", { spy: true }); vi.mock(import("../state/server"), async (original) => { const { Atom } = await import("effect/reactivity"); const { compileResolvedKeybindingsConfig } = await import("@t3tools/shared/keybindings"); @@ -261,6 +264,45 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread menu", () => { + it("tells the menu whether the keyboard opened it", async () => { + const activeProject = project("active"); + const thread = threadShell(activeProject.id, 0); + const threadRef = { environmentId: activeProject.environmentId, threadId: thread.id }; + const show = vi.fn().mockResolvedValue(null); + vi.mocked(readLocalApi).mockReturnValue({ contextMenu: { show } } as unknown as LocalApi); + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue([thread]); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef: threadRef, + }); + await using screen = await render( + + + , + ); + const row = screen.getByText("Thread 0").first(); + await expect.element(row).toBeInTheDocument(); + row.element().closest("[data-sidebar-row]")!.focus(); + await userEvent.keyboard("{Shift>}{F10}{/Shift}"); + await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(1)); + expect(show.mock.lastCall?.[2]).toBe("keyboard"); + await userEvent.click(row, { button: "right" }); + await vi.waitFor(() => expect(show).toHaveBeenCalledTimes(2)); + expect(show.mock.lastCall?.[2]).toBe("mouse"); + }); +}); + describe("sidebar settled pagination", () => { it("keeps the viewport in place when showing more settled threads", async () => { using stack = new DisposableStack(); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 28ce205264ec3..58eee43daa6ef 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1,3 +1,4 @@ +import { resolveListedAncestorThreadRef } from "@t3tools/client-runtime/state/threads"; import { presentThreadShell } from "@t3tools/client-runtime/state/models"; import { threadKey } from "@t3tools/client-runtime/state/entities"; import { isThreadWorking as isSidebarThreadWorking } from "@t3tools/client-runtime/state/thread-inbox"; @@ -11,7 +12,6 @@ import { deleteSelectedThreadEntries, getFallbackThreadIdAfterDelete, hasUnseenCompletion, - resolveSidebarRowThreadRef, orderItemsByPreferredIds, pinOrderKeyBetween, resolveSidebarSweepKeys, @@ -159,8 +159,15 @@ describe("sidebar thread lineage helpers", () => { }); expect( - resolveSidebarRowThreadRef(ref(remote), [parent, remote], new Set([threadKey(ref(remote))])), + resolveListedAncestorThreadRef( + ref(remote), + [parent, remote], + new Set([threadKey(ref(remote))]), + ), ).toEqual(ref(parent)); + expect(resolveListedAncestorThreadRef(ref(remote), [parent, remote], new Set())).toEqual( + ref(remote), + ); }); it("walks local and remote ancestry without confusing equal ids on different machines", () => { @@ -184,8 +191,10 @@ describe("sidebar thread lineage helpers", () => { const threads = [remote, parent, grandchild]; const delegated = new Set([threadKey(ref(remote))]); - expect(resolveSidebarRowThreadRef(ref(remote), threads, delegated)).toEqual(ref(parent)); - expect(resolveSidebarRowThreadRef(ref(grandchild), threads, delegated)).toEqual(ref(parent)); + expect(resolveListedAncestorThreadRef(ref(remote), threads, delegated)).toEqual(ref(parent)); + expect(resolveListedAncestorThreadRef(ref(grandchild), threads, delegated)).toEqual( + ref(parent), + ); }); it("keeps a remote task's own row when its parent is unavailable", () => { @@ -201,11 +210,11 @@ describe("sidebar thread lineage helpers", () => { delegatedFrom: { environmentId, threadId: parent.id, title: parent.title }, }); - expect(resolveSidebarRowThreadRef(ref(remote), [parent, remote], new Set())).toEqual( + expect(resolveListedAncestorThreadRef(ref(remote), [parent, remote], new Set())).toEqual( ref(remote), ); expect( - resolveSidebarRowThreadRef(ref(remote), [remote], new Set([threadKey(ref(remote))])), + resolveListedAncestorThreadRef(ref(remote), [remote], new Set([threadKey(ref(remote))])), ).toEqual(ref(remote)); }); @@ -230,47 +239,7 @@ describe("sidebar thread lineage helpers", () => { }); const delegated = new Set([threadKey(firstRef), threadKey(secondRef)]); - expect(resolveSidebarRowThreadRef(firstRef, [first, second], delegated)).toEqual(firstRef); - }); - - it("maps an open subagent to its nearest visible ancestor's sidebar row", () => { - const environmentId = EnvironmentId.make("environment-row"); - const otherEnvironmentId = EnvironmentId.make("environment-other"); - const subagentOf = (id: string, parentId: ThreadId, environment = environmentId) => - makeThreadFixture({ - id: ThreadId.make(id), - environmentId: environment, - lineage: { - rootThreadId: parentId, - parentThreadId: parentId, - relationshipToParent: "subagent", - }, - }); - const root = makeThreadFixture({ id: ThreadId.make("thread-root"), environmentId }); - const fork = makeThreadFixture({ - id: ThreadId.make("thread-fork"), - environmentId, - lineage: { - rootThreadId: root.id, - parentThreadId: root.id, - relationshipToParent: "fork", - }, - }); - const child = subagentOf("thread-child", root.id); - const grandchild = subagentOf("thread-grandchild", child.id); - const forkChild = subagentOf("thread-fork-child", fork.id); - const orphan = subagentOf("thread-orphan", ThreadId.make("thread-missing")); - const elsewhere = subagentOf("thread-elsewhere", root.id, otherEnvironmentId); - const threads = [root, fork, child, grandchild, forkChild, orphan, elsewhere]; - - expect(resolveSidebarRowThreadRef(ref(child), threads, new Set())).toEqual(ref(root)); - expect(resolveSidebarRowThreadRef(ref(grandchild), threads, new Set())).toEqual(ref(root)); - expect(resolveSidebarRowThreadRef(ref(forkChild), threads, new Set())).toEqual(ref(fork)); - expect(resolveSidebarRowThreadRef(ref(elsewhere), threads, new Set())).toEqual(ref(elsewhere)); - expect(resolveSidebarRowThreadRef(ref(orphan), threads, new Set())).toEqual(ref(orphan)); - const loopA = subagentOf("thread-loop-a", ThreadId.make("thread-loop-b")); - const loopB = subagentOf("thread-loop-b", loopA.id); - expect(resolveSidebarRowThreadRef(ref(loopA), [loopA, loopB], new Set())).toEqual(ref(loopA)); + expect(resolveListedAncestorThreadRef(firstRef, [first, second], delegated)).toEqual(firstRef); }); }); @@ -454,6 +423,19 @@ describe("resolveSidebarRowStatus", () => { // A runtime failure without a failed run has no date, so a visit cannot settle it. expect(resolveSidebarRowStatus({ ...opened, latestRun: null })).toBe("failed"); }); + + it("does not show a stopped run as an unseen completion", () => { + for (const status of ["interrupted", "cancelled"] as const) { + const stopped = { + ...failed, + runtime: { ...failedRuntime, status, lastError: null }, + latestRun: { ...makeLatestRun(), status }, + lastVisitedAt: "2026-03-09T10:01:00.000Z", + }; + expect(hasUnseenCompletion(stopped)).toBe(false); + expect(resolveThreadStatusPill({ thread: stopped })).toBeNull(); + } + }); }); describe("searchSidebarThreads", () => { @@ -1746,6 +1728,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal: { observedKey: "environment-test:other", pendingKey: null }, routeKey: hiddenKey, + routeKeyInPlace: false, isSearching: false, scopedProjectKeys, delegatedUnderParent: new Set(), @@ -1760,6 +1743,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal: { observedKey: hiddenKey, pendingKey: null }, routeKey: hiddenKey, + routeKeyInPlace: false, isSearching: false, scopedProjectKeys, delegatedUnderParent: new Set(), @@ -1776,6 +1760,7 @@ describe("resolveSidebarRouteReveal", () => { resolveSidebarRouteReveal({ reveal, routeKey, + routeKeyInPlace: false, isSearching: false, scopedProjectKeys, delegatedUnderParent: new Set(), @@ -1790,6 +1775,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.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 1057e474674d6..b2a8c2faea95f 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -18,7 +18,6 @@ import { } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; import { - isListedThreadLineage, type ContextMenuItem, type EnvironmentId, type ResolvedKeybindingsConfig, @@ -583,41 +582,6 @@ export async function deleteSelectedThreadEntries< return { deletedThreadKeys, firstFailure }; } -export function isSidebarHiddenThread(thread: Pick): boolean { - return !isListedThreadLineage(thread.lineage); -} - -// Hidden local and remote tasks use their nearest visible ancestor's row. -// A missing parent or cycle leaves the original route unchanged. -export function resolveSidebarRowThreadRef( - ref: ScopedThreadRef, - threads: readonly Pick< - SidebarThreadSummary, - "id" | "environmentId" | "lineage" | "delegatedFrom" - >[], - delegatedUnderParent: ReadonlySet, -): ScopedThreadRef { - const visited = new Set(); - let current = ref; - while (true) { - const key = threadKey(current); - if (visited.has(key)) return ref; - visited.add(key); - const thread = threads.find( - (thread) => thread.id === current.threadId && thread.environmentId === current.environmentId, - ); - if (thread === undefined) return ref; - if (!isShownUnderParent(current, thread.lineage, delegatedUnderParent)) return current; - const parent = isSidebarHiddenThread(thread) - ? thread.lineage.parentThreadId === null - ? null - : scopeThreadRef(current.environmentId, thread.lineage.parentThreadId) - : thread.delegatedFrom; - if (parent === null || parent === undefined) return ref; - current = scopeThreadRef(parent.environmentId, parent.threadId); - } -} - /** Offline environments the sidebar hides, and the open thread's row it lists anyway. */ export interface SidebarHiddenEnvironments { readonly environmentIds: ReadonlySet; @@ -889,6 +853,9 @@ export function resolveThreadLastVisitedAt( export function hasUnseenCompletion(thread: ThreadStatusInput): boolean { if (!thread.latestRun?.completedAt) return false; + if (thread.latestRun.status === "interrupted" || thread.latestRun.status === "cancelled") { + return false; + } const completedAt = Date.parse(thread.latestRun.completedAt); if (Number.isNaN(completedAt)) return false; if (!thread.lastVisitedAt) return false; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 3144be7035291..e8dd257ee0a3f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -55,11 +55,15 @@ import { } from "@t3tools/client-runtime/environment"; import { AuthOrchestrationOperateScope, + type ContextMenuSource, ProjectId, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; -import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads"; +import { + resolveListedAncestorThreadRef, + type OlderSettledScope, +} from "@t3tools/client-runtime/state/threads"; import { CheckIcon, @@ -212,7 +216,6 @@ import { useThreadJumpHintsVisible, type SidebarListItem, type SidebarSection, - resolveSidebarRowThreadRef, } from "./Sidebar.logic"; import { createSidebarCollisionDetection, @@ -1150,7 +1153,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const routeRowThreadRef = routeThreadRef === null ? null - : resolveSidebarRowThreadRef(routeThreadRef, threads, scopedDelegatedUnderParent); + : resolveListedAncestorThreadRef(routeThreadRef, threads, scopedDelegatedUnderParent); const routeRowThreadKey = routeRowThreadRef === null ? null : scopedThreadKey(routeRowThreadRef); // Only a hidden environment's open row is kept, so other navigation leaves the partition memoized. const keptThreadKey = @@ -1160,6 +1163,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const hiddenEnvironments = hiddenEnvironmentIds === null ? null : { environmentIds: hiddenEnvironmentIds, keptThreadKey }; 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 @@ -1168,6 +1174,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const { widensScope: revealWidensScope } = resolveSidebarRouteReveal({ reveal: routeReveal, routeKey: routeRowThreadKey, + routeKeyInPlace, isSearching: isSearchingThreads, scopedProjectKeys: chosenScopeProjectKeys, delegatedUnderParent: scopedDelegatedUnderParent, @@ -1194,7 +1201,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, @@ -1303,7 +1310,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve void handleNewThread(scopeProjectRef(group.environmentId, group.id)); }); const handleProjectFolderContextMenu = useStableCallback( - (group: SidebarProjectSnapshot, position: { x: number; y: number }) => { + ( + group: SidebarProjectSnapshot, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => { const api = readLocalApi(); if (!api) return; void (async () => { @@ -1322,6 +1333,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve { id: "project-settings", label: "Project settings", icon: "settings" }, ], position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2338,7 +2350,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleMultiSelectContextMenu = useStableCallback( - async (position: { x: number; y: number }) => { + async (position: { x: number; y: number }, source: ContextMenuSource) => { const api = readLocalApi(); if (!api) return; const selectedThreadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; @@ -2436,6 +2448,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ], position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -2589,7 +2602,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleDraftContextMenu = useStableCallback( - (draftId: DraftId, position: { x: number; y: number }) => { + (draftId: DraftId, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); const session = useComposerDraftStore.getState().getDraftSession(draftId); @@ -2611,6 +2624,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve hasProject: projectGroup != null, }), position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2640,14 +2654,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleThreadContextMenu = useStableCallback( - (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { + (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); if (!api) return; const threadKey = scopedThreadKey(threadRef); const selectionState = useThreadSelectionStore.getState(); if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { - await handleMultiSelectContextMenu(position); + await handleMultiSelectContextMenu(position, source); return; } const thread = threadByKeyRef.current.get(threadKey); @@ -2714,6 +2728,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve snoozePresets, }), position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -3341,7 +3356,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve role="status" className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground" > - {threadSearch.isPending ? "Searching thread messages…" : "No threads found"} + {threadSearch.isPending + ? "Searching thread messages…" + : threadSearch.failed + ? "Couldn't search thread messages" + : "No threads found"}

) ) : null} diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index a7b7da0a6b53b..5217b068f9a35 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -8,7 +8,7 @@ import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; -import { BackgroundThreadContext } from "./chat/backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -229,7 +229,9 @@ export function ThreadRouteView({ className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh" inert={background} > - {view} + + {view} + {background ? null : redirect} ); diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx index f9990ea7d0c45..7632d01b5f907 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx @@ -208,6 +208,8 @@ vi.mock("../hooks/useSettings", async () => { return { useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) => select(DEFAULT_CLIENT_SETTINGS), + ensureClientSettingsHydrated: async () => {}, + getClientSettings: () => DEFAULT_CLIENT_SETTINGS, }; }); diff --git a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx index 667c19fe4718c..c320bdef82563 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx @@ -149,6 +149,19 @@ describe("citation comment caret", () => { await userEvent.keyboard("!"); expect(input.value).toBe(`${comment}!`); }); + + it("saves with Tab then Enter after typing a comment", async () => { + using _source = setup(); + const onSave = vi.fn(() => true); + await using _screen = await mount(undefined, onSave); + await vi.waitFor(() => expect(document.activeElement).toBe(textarea())); + + await userEvent.keyboard("agreed"); + await userEvent.keyboard("{Tab}"); + await userEvent.keyboard("{Enter}"); + + expect(onSave).toHaveBeenCalledWith("agreed"); + }); }); describe("citation comment popup position", () => { diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index cdd8e1249cfc7..76247ad2ccde8 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -114,22 +114,27 @@ export function AssistantCitationCommentEditor({ ) : null}
- - + {/* Wrap as a pair so the recording pill never pushes Save alone onto a new row under Cancel. */} +
+ + +
); diff --git a/apps/web/src/components/chat/AssistantCitationSource.tsx b/apps/web/src/components/chat/AssistantCitationSource.tsx index cf2e950e96abd..1df13bdda1f7d 100644 --- a/apps/web/src/components/chat/AssistantCitationSource.tsx +++ b/apps/web/src/components/chat/AssistantCitationSource.tsx @@ -204,6 +204,14 @@ function observeAssistantCitationSource({ if (rect.bottom <= scrollRect.top || rect.top >= scrollRect.bottom) return; activation.scrolled = true; request.onComplete(); + // Screen readers follow focus, not scroll; leave someone already typing alone. + const active = root.ownerDocument.activeElement; + if ( + !(active instanceof HTMLElement) || + !(active.isContentEditable || active.matches("input, textarea, select")) + ) { + root.focus({ preventScroll: true }); + } if (!range) { toastManager.add({ type: "warning", @@ -359,6 +367,8 @@ export function AssistantCitationSource({ return (
{ - const preview = buildExpandedImagePreview(composerImages, imageId); + const preview = buildExpandedImagePreview( + composerImages, + imageId, + copyComposerSnapshotStable, + ); if (preview) onExpandImage(preview); }, openFile: setPreviewFileId, @@ -1142,6 +1152,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const backgroundThread = use(BackgroundThreadContext); + const hiddenThread = use(HiddenThreadContext); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to keydown, window blur and the desktop paste-as-text event to arm plain-text paste useEffect(() => { // A background composer listens on its own form, so it never hears the main composer's keys. @@ -1444,7 +1455,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [record]; + return [ + record.kind === "image" && attachment.type === "image" && attachment.source + ? { ...record, source: attachment.source } + : record, + ]; }), ]; if (records.length === 0) return null; @@ -1456,6 +1471,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles); return fragment; }; + const copyComposerSnapshot = async (imageId: string) => { + const image = composerImages.find((candidate) => candidate.id === imageId); + if (!image) throw new Error("Snapshot is no longer available."); + const contextId = toKindScopedComposerContextId("image", image.id); + const fragment = buildContextClipboardFragment([contextId]); + if (!fragment || !image.previewUrl) throw new Error("The snapshot is not ready to copy."); + await copySnapshot( + image.previewUrl, + formatComposerContextReference({ kind: "image", contextId, label: image.name }), + fragment, + ); + }; + const copyComposerSnapshotStable = useStableCallback(copyComposerSnapshot); const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); const { loadThreadTranscript, @@ -1943,6 +1971,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) projectName, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, disabled: dictationDisabled, + label: activeThread?.title ?? null, + presented: !hiddenThread, + // A question's answer lives only in this composer, so only the thread draft outlives it. + persistentDraft: questionAttachmentTarget + ? undefined + : { + readStoredText: () => readComposerDraftPrompt(composerDraftTarget), + commitStoredText: (text) => { + const live = resolveLiveComposerDraftTarget(composerDraftTarget); + if (live !== null) setComposerDraftPrompt(live, text); + }, + // The route, not the draft target: a queued-message edit has a draft id but no route. + open: () => + void (routeKind === "draft" && typeof composerDraftTarget === "string" + ? navigate({ + to: "/draft/$draftId", + params: buildDraftThreadRouteParams(composerDraftTarget), + }) + : navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(routeThreadRef), + })), + }, readDraft: () => { const snapshot = readComposerSnapshot(); return { @@ -2379,14 +2430,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); const handleSubmitMessage = (event: React.MouseEvent) => { event.preventDefault(); + const running = phase === "running" || phase === "connecting"; + const alternateModifier = event.metaKey || event.ctrlKey; submitComposer( event, resolveComposerDispatchMode({ - running: phase === "running" || phase === "connecting", - alternateModifier: event.metaKey || event.ctrlKey, + running, + alternateModifier, activeTurnDefault: followUpBehavior, canSteer, }), + running && alternateModifier ? "alternate" : undefined, ); }; const handleSubmitMessageStable = useStableCallback(handleSubmitMessage); @@ -2569,6 +2623,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) allImages={composerImages} resolvedTheme={resolvedTheme} onExpandImage={onExpandImage} + onCopySnapshot={copyComposerSnapshotStable} onShowMore={expandMobileComposer} /> ) : null; @@ -2647,6 +2702,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // An open question owns the space above the composer. Only a machine problem, // which is why an answer could not go through, stays beside it. const replyTo = composerDraft?.replyTo ?? null; + const draftRunsLocally = composerRunsDraftLocally({ + text: prompt, + holdsOnlyText: + composerImages.length + composerFiles.length === 0 && + composerSendState.sendableTerminalContexts.length === 0 && + composerPreviewAnnotations.length === 0 && + composerReviewComments.length === 0 && + composerThreadContexts.length === 0 && + composerEnvironmentContexts.length === 0 && + replyTo === null, + sideChat: props.sideChatAvailable === true || (props.sideChatDisabledReason ?? null) !== null, + usageLimits: props.onUsageLimitsCommand !== undefined, + codexFeedback: selectedProvider === "codex" && multipleModelSelections === null, + freshSession: props.onFreshSession !== undefined, + }); const replyBannerItems: readonly ComposerBannerStackItem[] = replyTo ? [ { @@ -2902,9 +2972,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { files, folders } = splitTransferredFiles(event.clipboardData); const plainText = event.clipboardData.getData("text/plain"); const bypassAutoAttachment = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); + const pastedContext = + !isLiteralPendingAnswer && + (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; if ( folders.length > 0 || - (activeThreadId && + (!pastedContext && + activeThreadId && files.length > 0 && shouldHandleComposerAttachmentPaste({ files, plainText })) ) { @@ -2917,7 +2991,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return; } - if ((readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0) return; + if (pastedContext) return; if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3470,6 +3544,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId={environmentId} attachmentDraftTarget={attachmentDraftTarget} canOperateThread={canOperateThread} + onCopySnapshot={copyComposerSnapshotStable} onExpandImage={onExpandImage} onFileOpen={onFileOpen} onRemoveImage={removeComposerImage} @@ -3949,11 +4024,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) reserveContextWindowMeter={reserveContextWindowMeter} activeThreadModelDisplayName={activeThreadModelDisplayName} pendingAction={pendingPrimaryAction} - // A side-chat command starts a side chat; it never queues or steers the turn. - isRunning={ - (phase === "running" || phase === "connecting") && - !(props.sideChatAvailable === true && parseSideChatCommand(prompt) !== null) - } + isRunning={(phase === "running" || phase === "connecting") && !draftRunsLocally} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} followUpBehavior={followUpBehavior} @@ -4009,6 +4080,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) finishShortcutLabel={dictationShortcutLabel} cancelShortcutLabel="Esc" level={speechInput.level} + recordingStartedAt={speechInput.recordingStartedAt} disabled={dictationDisabled} onStart={() => void speechInput.start()} onStop={() => void speechInput.stop()} diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index ca98b4d2f6c79..59115804e4972 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -149,6 +149,7 @@ export function ComposerAttachmentMediaRow({ attachmentDraftTarget, canOperateThread, onExpandImage, + onCopySnapshot, onFileOpen, onRemoveImage, onRemoveFile, @@ -167,6 +168,7 @@ export function ComposerAttachmentMediaRow({ readonly environmentId: EnvironmentId; readonly attachmentDraftTarget: ScopedThreadRef | DraftId; readonly canOperateThread: boolean; + readonly onCopySnapshot: (imageId: string) => Promise; readonly onExpandImage: (preview: ExpandedImagePreview) => void; readonly onFileOpen: (attachment: ChatFileAttachment) => void; readonly onRemoveImage: (imageId: string) => void; @@ -224,7 +226,7 @@ export function ComposerAttachmentMediaRow({ aria-label={`Preview ${image.name}`} disabled={!ready} onClick={() => { - const preview = buildExpandedImagePreview(images, image.id); + const preview = buildExpandedImagePreview(images, image.id, onCopySnapshot); if (!preview) return; onExpandImage(preview); }} @@ -254,6 +256,7 @@ export function ComposerAttachmentMediaRow({ {source?.kind === "snap-shot" ? ( onCopySnapshot(ready.id) : undefined} className={cn( upload?.status === "uploading" && "bottom-4", upload?.status === "failed" && "bottom-8", @@ -586,11 +589,13 @@ export function ComposerRestingImagePreviews({ allImages, resolvedTheme, onExpandImage, + onCopySnapshot, onShowMore, }: { readonly images: ReadonlyArray; readonly allImages: ReadonlyArray; readonly resolvedTheme: "light" | "dark"; + readonly onCopySnapshot: (imageId: string) => Promise; readonly onExpandImage: (preview: ExpandedImagePreview) => void; readonly onShowMore: () => void; }) { @@ -606,7 +611,7 @@ export function ComposerRestingImagePreviews({ aria-label={`Preview ${image.name}`} onPointerDown={(event) => event.preventDefault()} onClick={() => { - const preview = buildExpandedImagePreview(allImages, image.id); + const preview = buildExpandedImagePreview(allImages, image.id, onCopySnapshot); if (preview) onExpandImage(preview); }} > diff --git a/apps/web/src/components/chat/ComposerSpeechButton.tsx b/apps/web/src/components/chat/ComposerSpeechButton.tsx index ca9ef2a278ad6..9f7eb4f37ab74 100644 --- a/apps/web/src/components/chat/ComposerSpeechButton.tsx +++ b/apps/web/src/components/chat/ComposerSpeechButton.tsx @@ -43,18 +43,25 @@ function formatElapsed(seconds: number) { return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; } -function RecordingStatus(props: { level: number; recordingLimitSeconds?: number | undefined }) { - const [elapsedSeconds, setElapsedSeconds] = useState(0); +function RecordingStatus(props: { + level: number; + recordingStartedAt?: number | null | undefined; + recordingLimitSeconds?: number | undefined; +}) { + const { recordingStartedAt } = props; + const [elapsedSeconds, setElapsedSeconds] = useState(() => + recordingStartedAt ? Math.max(0, Math.floor((Date.now() - recordingStartedAt) / 1_000)) : 0, + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the timer displaying the native recording duration useEffect(() => { - const startedAt = Date.now(); + const startedAt = recordingStartedAt ?? Date.now(); const timer = window.setInterval( () => setElapsedSeconds(Math.floor((Date.now() - startedAt) / 1_000)), 250, ); return () => window.clearInterval(timer); - }, []); + }, [recordingStartedAt]); return ( <> @@ -125,6 +132,7 @@ export function ComposerSpeechRecordingPill(props: { finishShortcutLabel?: string | null; cancelShortcutLabel?: string | null; level: number; + recordingStartedAt?: number | null | undefined; recordingLimitSeconds?: number | undefined; /** Compact matches the `xs` buttons beside text-field editors. */ size?: "default" | "compact"; @@ -181,6 +189,7 @@ export function ComposerSpeechRecordingPill(props: { {recording ? ( ) : ( diff --git a/apps/web/src/components/chat/ComposerStashMenu.test.ts b/apps/web/src/components/chat/ComposerStashMenu.test.ts index efabfc93c42dd..b3d5016de6d1c 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.test.ts +++ b/apps/web/src/components/chat/ComposerStashMenu.test.ts @@ -1,3 +1,7 @@ +import { + formatComposerContextReference, + toComposerContextId, +} from "@t3tools/shared/composerContextReferences"; import { describe, expect, it } from "vite-plus/test"; import { stashEntrySnippet } from "./ComposerStashMenu"; @@ -15,4 +19,13 @@ describe("stashEntrySnippet", () => { expect(stashEntrySnippet(entry(`${"a".repeat(89)}😀 and more`))).toBe(`${"a".repeat(89)}…`); expect(stashEntrySnippet(entry(`${"a".repeat(88)}😀 and more`))).toBe(`${"a".repeat(88)}😀…`); }); + + it("shows context chips by their label", () => { + const file = formatComposerContextReference({ + kind: "file", + contextId: toComposerContextId("readme"), + label: "README.md", + }); + expect(stashEntrySnippet(entry(`Summarize ${file} please`))).toBe("Summarize README.md please"); + }); }); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 15f19f0b3ed3f..4262d40bbc73b 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -1,6 +1,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; import { RelativeTime } from "../RelativeTime"; import { cn } from "~/lib/utils"; @@ -14,7 +15,11 @@ function missingImageCount(entry: PromptStashEntry): number { } export function stashEntrySnippet(entry: PromptStashEntry): string { - const trimmed = assistantCitationsToPlainText(entry.prompt).trim().replace(/\s+/g, " "); + const trimmed = assistantCitationsToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ) + .trim() + .replace(/\s+/g, " "); if (trimmed.length > 0) { if (trimmed.length <= SNIPPET_MAX_CHARS) return trimmed; // Never end on a lone high surrogate, the first half of an emoji. diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx index 26c741cd8b8df..772f83cb149c0 100644 --- a/apps/web/src/components/chat/DraftHeroHeadline.tsx +++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx @@ -16,7 +16,7 @@ import { useProjectPin } from "~/hooks/useProjectGroupUpdate"; import { useScratchProject } from "~/hooks/useScratchProject"; import { isTriagePrompt } from "@t3tools/shared/triagePrompt"; import { useClientSettings } from "~/hooks/useSettings"; -import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions"; +import { seedDraftModelSelection } from "~/lib/seedDraftModelSelection"; import { deriveLogicalProjectKeyFromSettings, pickableProjectGroups, @@ -27,11 +27,7 @@ import { projectGroupsSpanEnvironments, } from "~/sidebarProjectGrouping"; import { useProjects } from "~/state/entities"; -import { - useEnvironments, - usePrimaryEnvironmentId, - useEnvironmentProviders, -} from "~/state/environments"; +import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments"; import { ProjectEnvironmentBadge } from "../ProjectEnvironmentBadge"; import { ProjectFavicon } from "../ProjectFavicon"; import { isProjectPinShortcut, ProjectPinButton } from "../ProjectPinButton"; @@ -51,9 +47,6 @@ import { InlineButton } from "../ui/button"; import { DraftProjectName } from "./DraftProjectName"; import { DraftHeroProjectHeading } from "./DraftHeroProjectHeading"; import { TriageDraftHero } from "./TriageDraftHero"; -import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; -import { resolveProjectDefaultProviderModelSelection } from "../../providerInstances"; -import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; const ADD_PROJECT_VALUE = "add-project"; @@ -75,7 +68,6 @@ export function DraftHeroHeadline({ }: DraftHeroHeadlineProps) { const projects = useProjects(); const { environments } = useEnvironments(); - const providersByEnvironment = useEnvironmentProviders(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); const setLogicalProjectDraftThreadId = useComposerDraftStore( @@ -86,8 +78,6 @@ export function DraftHeroHeadline({ const isTriageDraftPrompt = useComposerDraftStore((store) => draftId ? isTriagePrompt(store.getComposerDraft(draftId)?.prompt ?? "") : false, ); - const applyStickyState = useComposerDraftStore((store) => store.applyStickyState); - const setModelSelection = useComposerDraftStore((store) => store.setModelSelection); const openAddProject = () => openCommandPalette({ open: "add-project" }); const { scratchEnvironmentId, scratchWorkspaceRootFor, openScratchProject } = useScratchProject(); const openProjectDraft = useNewThreadHandler(); @@ -186,51 +176,13 @@ export function DraftHeroHeadline({ return; } pendingScratchRef.current = null; - const currentDraft = getComposerDraft(draftId); - if (!composerDraftHasUserContent(currentDraft)) { - void openProjectDraft(scopeProjectRef(project.environmentId, project.id)); + const projectRef = scopeProjectRef(project.environmentId, project.id); + if (!composerDraftHasUserContent(getComposerDraft(draftId))) { + void openProjectDraft(projectRef); return; } - setLogicalProjectDraftThreadId( - logicalProjectKey, - scopeProjectRef(project.environmentId, project.id), - draftId, - ); - if (!hasExplicitComposerModelSelection(currentDraft)) { - applyStickyState(draftId); - const environmentConfig = environments.find( - (environment) => environment.environmentId === project.environmentId, - )?.serverConfig; - const environmentSettings = environmentConfig?.settings; - const defaultSelection = environmentSettings - ? resolveProjectSettings(environmentSettings, project.id, project).settings - .defaultModelSelection - : project.defaultModelSelection; - const fallbackResolution = resolveNewThreadModelSelection({ - defaultSelection: - defaultSelection ?? - (useComposerDraftStore.getState().stickyActiveProvider !== null || !environmentSettings - ? null - : resolveProjectDefaultProviderModelSelection( - providersByEnvironment.get(project.environmentId) ?? [], - environmentSettings, - project.id, - )), - fallbackSelection: environmentSettings?.fallbackModelSelection ?? null, - providers: providersByEnvironment.get(project.environmentId) ?? [], - ...(environmentSettings ? { settings: environmentSettings } : {}), - projectId: project.id, - now: Date.now(), - }); - const defaultModelSelection = fallbackResolution.fallback - ? fallbackResolution.selection - : defaultSelection; - if (defaultModelSelection) { - setModelSelection(draftId, defaultModelSelection, { - replaceOptions: true, - }); - } - } + setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId); + seedDraftModelSelection(draftId, projectRef); }; const startScratch = async (): Promise => { if (scratchTargetEnvironmentId === null || isScratchDraft) { diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 2d70c5f2ef1dc..a539994d01862 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -18,6 +18,7 @@ import { MediaVideoPlayer } from "../media/MediaVideoPlayer"; import { isContextMenuOpen } from "../../contextMenuFallback"; import { SnapShotAccessibilityData, + SnapShotCopyButton, SnapShotContentsButton, snapShotAccessibilityDetails, } from "./SnapShotAttachmentDetails"; @@ -277,6 +278,11 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ ) : item.source ? ( ) : null} + {item.onCopySnapshot && ( +
+ +
+ )}
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.tsx b/apps/web/src/components/chat/ExpandedImagePreview.tsx index 0eec6753f8e96..ddd2990000119 100644 --- a/apps/web/src/components/chat/ExpandedImagePreview.tsx +++ b/apps/web/src/components/chat/ExpandedImagePreview.tsx @@ -27,6 +27,7 @@ export interface ExpandedImageItem { /** Revoke this owned object URL; other blob URLs belong to the timeline. */ ownsSrc?: boolean; source?: SnapShotSource; + onCopySnapshot?: (() => Promise) | undefined; autoPlay?: boolean; originalUrl?: string; srcFragment?: string; @@ -162,6 +163,7 @@ export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => export function buildExpandedImagePreview( images: ReadonlyArray, selectedImageId: string, + onCopySnapshot?: (id: string) => Promise, ): ExpandedImagePreview | null { const selected = images.find((image) => image.id === selectedImageId); if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) { @@ -202,7 +204,12 @@ export function buildExpandedImagePreview( src: image.src, name: image.name, mimeType: image.mimeType, - ...(image.source?.kind === "snap-shot" ? { source: image.source } : {}), + ...(image.source?.kind === "snap-shot" + ? { + source: image.source, + onCopySnapshot: onCopySnapshot ? () => onCopySnapshot(image.id) : undefined, + } + : {}), })), index: selectedIndex, }; diff --git a/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx b/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx new file mode 100644 index 0000000000000..3bc724fe1962a --- /dev/null +++ b/apps/web/src/components/chat/GlobalVoiceInputIndicator.tsx @@ -0,0 +1,52 @@ +import { useVoiceTranscriptionDestination } from "../../speech/useEnvironmentSpeechInput"; +import { + useRetainedVoiceInputSession, + useVoiceInputSessionActivity, + useVoiceInputSessionSnapshot, + useVoiceOwnerPresented, +} from "../../speech/voiceInputSession"; +import { Button } from "../ui/button"; +import { ComposerSpeechRecordingPill } from "./ComposerSpeechButton"; + +/** + * Keeps the chosen destination's dictation alive across navigation and, while the draft it + * records into is off screen, shows it so it can be finished, cancelled, or returned to. + */ +export function GlobalVoiceInputIndicator({ hidden = false }: { hidden?: boolean }) { + const { prepared, grantId, cloudProvider, cloudModel } = useVoiceTranscriptionDestination(); + const session = useRetainedVoiceInputSession({ prepared, grantId, cloudProvider, cloudModel }); + const { state, target, recordingStartedAt } = useVoiceInputSessionSnapshot(session); + const presented = useVoiceOwnerPresented(target?.ownerKey ?? null); + const { level } = useVoiceInputSessionActivity( + hidden || presented ? null : session, + target?.ownerKey ?? null, + ); + if (hidden || !session || !target || state.phase === "idle" || presented) return null; + + return ( +
+
+ + void session.start(target)} + onStop={() => void session.stop()} + onCancel={() => session.cancel()} + onSkipPostProcessing={() => session.skipPostProcessing()} + /> +
+
+ ); +} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index 5d0238fb1f3af..53e575bd5bc99 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -1,3 +1,4 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; import { useAssetUrlState } from "../../assets/assetUrls"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { @@ -42,6 +43,7 @@ interface MarkdownFileLinkProps { threadRef?: ScopedThreadRef | undefined; onOpen?: (() => Promise>) | undefined; onOpenInPanel: (panelPath: string, line: number | undefined) => void; + resolveDragPath: () => Promise; resolveCopyPaths: () => Promise>; openInEditorMenuLabel: string; onOpenInBrowser?: (() => Promise>) | undefined; @@ -73,7 +75,9 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ onReveal, revealLabel, resolveCopyPaths, + resolveDragPath, }: MarkdownFileLinkProps) { + const nativeDrag = useNativeFileDrag(environmentId, resolveDragPath); const handleOpenInEditor = () => { if (!onOpen) { return; @@ -328,6 +332,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ render={ hasPrimaryAction ? ( } @@ -362,6 +367,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ ) : ( } @@ -418,6 +424,7 @@ function areMarkdownFileLinkPropsEqual( previous.onOpenMedia === next.onOpenMedia && previous.onReveal === next.onReveal && previous.resolveCopyPaths === next.resolveCopyPaths && + previous.resolveDragPath === next.resolveDragPath && previous.revealLabel === next.revealLabel ); } diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index fc20323c1c449..cb35ed33f7096 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -36,6 +36,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { readonly cause: Parameters[0]["cause"]; @@ -90,6 +91,7 @@ export function McpAppFrame(props: { }) { const { app } = props; const theme = useHtmlRenderTheme(); + const nativeTitlebarHeight = useNativeTitlebarHeight(); const frameRef = useRef(null); const boxRef = useRef(null); const [width, setWidth] = useState(0); @@ -453,6 +455,8 @@ export function McpAppFrame(props: { ? "fixed inset-0 m-0 flex h-dvh max-h-none w-dvw max-w-none flex-col border-0 bg-background p-0" : "block! static! m-0 border-0 bg-transparent p-0 text-inherit", )} + // Keep the header clear of the native window controls. + style={fullscreen ? { paddingTop: nativeTitlebarHeight } : undefined} > {fullscreen ? (
{ expect((globalThis as { __t3Xss?: number }).__t3Xss).toBeUndefined(); }); + it("shows the spaces typed at the start of user lines, where find also matches them", async () => { + const source = "Plan\n Step one\n\tDetail"; + await using screen = await renderTimeline([ + message(source), + message(source, { role: "assistant" }, "assistant-1"), + ]); + const [user, assistant] = screen.container.querySelectorAll( + "[data-timeline-row-kind=message]", + ); + expect(user?.querySelector("[data-user-message-body]")?.innerText).toBe(source); + expect(assistant?.querySelector(".chat-markdown")?.innerText).toBe( + "Plan Step one Detail", + ); + const query = " Step one"; + const indexed = searchableMessageSegments({ role: "user", text: source, streaming: false }); + const ranges = collectThreadFindRanges(screen.container, query); + expect(ranges.map(({ rowId, range }) => [rowId, range.toString()])).toEqual([ + [user?.closest("[data-timeline-row-id]")?.getAttribute("data-timeline-row-id"), query], + ]); + expect( + indexed?.reduce((count, segment) => count + countThreadSearchOccurrences(segment, query), 0), + ).toBe(ranges.length); + }); + it("keeps single tildes in user paths literal without changing double tildes or assistant text", async () => { const source = "Install the skill as ~/folder-a/skills/x, then follow the guide (~/folder-a/guide.md)."; @@ -1262,6 +1288,21 @@ describe("MessagesTimeline citations", () => { ); }); + it("moves focus to the cited response so screen readers follow it", async () => { + await using _screen = await renderTimeline( + [ + message("A question", {}, "question"), + message("the cited answer", { role: "assistant" }, "cited"), + ], + { citationRequest: CITATION_REQUEST, citationHistory: { _tag: "found" } }, + ); + await vi.waitFor(() => { + const cited = document.querySelector("[data-citation-highlighted]"); + expect(cited?.textContent).toContain("the cited answer"); + expect(cited?.contains(document.activeElement)).toBe(true); + }); + }); + it("opens the superseded attempt that folds the cited response", async () => { const runId = RunId.make("run-steered"); const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({ @@ -2091,7 +2132,7 @@ it("renders automatic compaction as one live divider that finishes with its reas await expect .element( screen.getByRole("separator", { - name: "Context automatically compacted before cache expiry 899K → 19K tokens", + name: "Auto-compacted before cache expiry 899K → 19K tokens", }), ) .toBeVisible(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 1cd8066dbcd32..f834c7cc355b9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -686,7 +686,7 @@ describe("deriveMessagesTimelineRows", () => { active: true, label: "Compacting before the cache expires…", }, - "Context automatically compacted before cache expiry", + "Auto-compacted before cache expiry", ], ["onReturn", { kind: "working", compacting: true }, "Context compacted before sending"], [undefined, { kind: "context-compaction", active: true }, undefined], diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 00ae66675191f..87bacfd7ca2a2 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -66,6 +66,7 @@ import { type ProviderInstanceEntry, } from "../../providerInstances"; import { providerModelKey, sortProviderModelItems } from "../../modelOrdering"; +import { hasRuntimeModelCatalog } from "../../providerModels"; type ModelPickerItem = { slug: string; @@ -113,9 +114,7 @@ function shouldIncludeModelPickerOption(input: { if (isProviderInstancePickerReady(input.entry)) return true; return ( input.entry.enabled && - (input.entry.driverKind === "opencode" || - input.entry.driverKind === "antigravity" || - input.entry.driverKind === "cursor") && + hasRuntimeModelCatalog(input.entry.driverKind) && input.entry.instanceId === input.activeInstanceId && input.option.slug === input.activeModel && input.option.isUnavailable === true @@ -549,13 +548,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const flatModels = (() => { const out: ModelPickerItem[] = []; + const seenKeys = new Set(); for (const [instanceId, models] of modelOptionsByInstance) { const entry = entryByInstanceId.get(instanceId); if (!entry) { continue; } for (const model of models) { + const key = modelPickerModelKey(instanceId, model.slug); if ( + seenKeys.has(key) || !shouldIncludeModelPickerOption({ entry, option: model, @@ -565,6 +567,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ) { continue; } + seenKeys.add(key); out.push({ slug: model.slug, name: model.name, diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index da9d7d50a5396..cc246a1f9967c 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -232,7 +232,7 @@ describe("open in editor announcement", () => { using _timers = fakeTimers(); const regions = () => [...document.querySelectorAll('body > [aria-live="polite"]')]; const spoken = async () => { - await act(async () => vi.runAllTimers()); + await act(async () => vi.advanceTimersByTime(250)); return regions() .map((region) => region.textContent) .join(""); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx index d7d333b23fee6..96a12b3389b94 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -4,6 +4,7 @@ import { ProviderInstanceId, type ModelSelection, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -183,6 +184,73 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo await expect.element(search).not.toBeInTheDocument(); }); +it("lists a model reported twice by one provider once, with contiguous jump shortcuts", async () => { + const instanceId = ProviderInstanceId.make("claude"); + const entries = deriveProviderInstanceEntries([ + { + instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }, + ]); + const options = new Map([ + [ + instanceId, + ["a", "b", "c", "c", "d", "d"].map((slug) => ({ + slug, + name: `Model ${slug.toUpperCase()}`, + })), + ], + ]); + const keybindings = compileResolvedKeybindingsConfig( + ([1, 2, 3, 4, 5, 6] as const).map((index) => ({ + key: `mod+${index}`, + command: `modelPicker.jump.${index}` as const, + when: "modelPickerOpen", + })), + ); + + await using screen = await render( + {}} + />, + ); + await screen.getByRole("button", { name: "Choose model" }).click(); + await expect.element(page.getByRole("option", { name: /Model A/ })).toBeVisible(); + await vi.waitFor(() => + expect( + page + .getByRole("option") + .elements() + .map((row) => [ + row.textContent?.match(/Model [A-Z]/)?.[0], + row.querySelector("kbd")?.textContent?.slice(-1), + ]), + ).toEqual([ + ["Model A", "1"], + ["Model B", "2"], + ["Model C", "3"], + ["Model D", "4"], + ]), + ); +}); + it("opens on the active provider when every favorite belongs to a disabled provider", async () => { const entries = deriveProviderInstanceEntries( ["Codex", "Claude"].map((name) => ({ diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx index 8781327b5e8ad..4f4daf7c798b4 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx @@ -1,11 +1,18 @@ import { RegistryContext } from "@effect/atom-react"; import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads"; -import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentId, + MessageId, + OrchestrationV2DispatchCommandError, + ThreadId, +} from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { formatComposerContextReference, toComposerContextId, } from "@t3tools/shared/composerContextReferences"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity"; @@ -16,6 +23,7 @@ import { page } from "vite-plus/test/browser"; const state = vi.hoisted(() => ({ threadState: null as unknown as Atom.Writable>, workflow: null as unknown, + commandResult: undefined as unknown, })); vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({ @@ -66,7 +74,7 @@ vi.mock(import("../../state/threads"), async (importOriginal) => { vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({ ...(await importOriginal()), - useAtomCommand: (() => async () => undefined) as never, + useAtomCommand: (() => async () => state.commandResult) as never, })); vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({ @@ -80,12 +88,14 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/th import { act, render as renderUi } from "../../../test/render"; import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures"; +import { ToastProvider } from "../ui/toast"; import { QueuedRunsControl } from "./QueuedRunsControl"; import { ExpandedImageDialog } from "./ExpandedImageDialog"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; function setup() { state.workflow = null; + state.commandResult = undefined; } const baseProps = { @@ -399,3 +409,37 @@ it("does not re-render while assistant text streams into the thread", async () = await act(() => registry.set(state.threadState, thread("Hello there", true))); expect(renders).toBeGreaterThan(settled); }); + +it("tells the user why Send now was rejected", async () => { + setup(); + const reason = "Target run run:active is stopping and cannot be steered."; + state.workflow = { + activeRun: { id: "run:active" }, + canPromoteToSteer: true, + queuedRuns: [ + { + run: { id: "run:queued", userMessageId: "message:queued" }, + text: "Follow up", + attachments: [], + }, + ], + }; + state.commandResult = AsyncResult.failure( + Cause.fail( + new OrchestrationV2DispatchCommandError({ + commandId: CommandId.make("command:promote"), + commandType: "queued-message.promote-to-steer", + message: reason, + detail: reason, + }), + ), + ); + await using _screen = await renderUi( + + + , + ); + + await page.getByRole("button", { name: "Send now" }).click(); + await vi.waitFor(() => expect(page.getByText(reason).element()).toBeVisible()); +}); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 8972bf468448b..49cbc8f050eea 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -1,4 +1,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { @@ -34,6 +38,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { isImageAttachment, type ChatImageAttachment, type ChatMessage } from "../../types"; import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; +import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { GuestMessageName } from "./guestMessageStyle"; @@ -168,19 +173,27 @@ export function QueuedRunsControl({ if (!canSendRun(freshContext) || steerInFlightRef.current) return; steerInFlightRef.current = true; setBusyRunId(queuedRunId); - if (workflow?.canSendNow) { - await resume({ - environmentId: props.environmentId, - input: { threadId: props.threadId, runId: queuedRunId }, - }); - } else if (activeRun !== null) { - await promote({ - environmentId: props.environmentId, - input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, - }); - } + const result = workflow?.canSendNow + ? await resume({ + environmentId: props.environmentId, + input: { threadId: props.threadId, runId: queuedRunId }, + }) + : activeRun !== null + ? await promote({ + environmentId: props.environmentId, + input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id }, + }) + : null; steerInFlightRef.current = false; setBusyRunId(null); + if (result?._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Could not send queued message", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } }; useImperativeHandle(ref, () => ({ diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 5ba6985e19d21..6b8de5aca8ecc 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -1,6 +1,7 @@ import type { EditorId, EnvironmentId, + IssueTrackerKind, PreviewAnnotationPayload, ProjectId, ResolvedKeybindingsConfig, @@ -19,6 +20,7 @@ import { PersistentThreadTerminalPanel, type PersistentThreadTerminalPanelProps, } from "../PersistentThreadTerminals"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; import { pullRequestPanelContext } from "../pullRequest/pullRequestDetail.logic"; import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; import { PullRequestDetailGhost } from "../pullRequest/PullRequestGhosts"; @@ -77,6 +79,7 @@ export function RightPanelSurfaceContent(props: { readonly onCloseSurface: (surface: RightPanelSurface) => void; readonly terminal: RightPanelTerminalProps; readonly pullRequest: RightPanelPullRequestProps; + readonly issuesSupported: boolean; readonly files: RightPanelFileProps; readonly sideChatParentPanel: SideChatParentPanel; }) { @@ -171,6 +174,40 @@ export function RightPanelSurfaceContent(props: { /> ); } + case "issue": + if (!props.pullRequest.capabilityKnown) return ; + if (!props.issuesSupported) { + return ( + + ); + } + return ( + { + useRightPanelStore.getState().openPullRequest(threadRef, { + projectId: reference.projectId, + repository: reference.repository, + number: reference.number, + ...(reference.host ? { host: reference.host } : {}), + }); + }} + /> + ); case "pull-requests": return ; case "side-chat": diff --git a/apps/web/src/components/chat/SkillInlineText.tsx b/apps/web/src/components/chat/SkillInlineText.tsx index 1d126e913290b..05c46ec676965 100644 --- a/apps/web/src/components/chat/SkillInlineText.tsx +++ b/apps/web/src/components/chat/SkillInlineText.tsx @@ -13,6 +13,7 @@ import { SKILL_CHIP_ICON_SVG } from "../composerInlineChip"; import { ContextChipPopover } from "../contextChipParts"; import { Button } from "../ui/button"; import { GroupMemberChip } from "./GroupMemberChip"; +import { PopoverClose } from "../ui/popover"; import { ModelMentionChip } from "./ModelMentionChip"; function SkillInlineText(props: { @@ -171,9 +172,12 @@ export function SkillChipPopover(props: {

{props.label}

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

{props.onViewInstructions ? ( - + ) : null}
diff --git a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx index 07f16c8794e98..826b335469d09 100644 --- a/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx +++ b/apps/web/src/components/chat/SnapShotAttachmentDetails.tsx @@ -1,6 +1,6 @@ import type { SnapShotSource } from "@t3tools/contracts"; -import { ImageIcon, TextIcon } from "lucide-react"; -import { Suspense } from "react"; +import { CheckIcon, CopyIcon, ImageIcon, TextIcon } from "lucide-react"; +import { Suspense, useRef, useState } from "react"; import { useRenderedAppearance } from "../../hooks/useTheme"; import { cn } from "../../lib/utils"; @@ -8,6 +8,10 @@ import { RenderErrorBoundary } from "../RenderErrorBoundary"; import { Button } from "../ui/button"; import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + ANCHORED_COPY_TOAST_TIMEOUT_MS, + showAnchoredCopyErrorToast, +} from "../ui/anchoredCopyToast"; import { HighlightedTokens } from "./HighlightedTokens"; export const SNAP_SHOT_ATTACHMENT_FRAME_CLASS = @@ -71,14 +75,64 @@ function snapShotIncludesAccessibility(source: SnapShotSource): boolean { return Boolean(source.accessibility || source.accessibleText?.trim()); } +export function SnapShotCopyButton({ + onCopy, + side = "top", +}: { + onCopy: () => Promise; + side?: "top" | "right" | "bottom" | "left"; +}) { + const ref = useRef(null); + const [copied, setCopied] = useState(false); + + return ( + + { + event.stopPropagation(); + void onCopy().then( + () => { + setCopied(true); + setTimeout(() => setCopied(false), ANCHORED_COPY_TOAST_TIMEOUT_MS); + }, + (error: unknown) => + showAnchoredCopyErrorToast( + ref, + error instanceof Error ? error : new Error(String(error)), + ), + ); + }} + size="xs" + variant="ghost-muted" + /> + } + > + {copied ? ( + + Copy snapshot + + ); +} + export function SnapShotContentsButton({ source, className, side = "top", + onCopySnapshot, }: { source: SnapShotSource; className?: string; side?: "top" | "right" | "bottom" | "left"; + onCopySnapshot?: (() => Promise) | undefined; }) { const includesAccessibility = snapShotIncludesAccessibility(source); const ContentsIcon = includesAccessibility ? TextIcon : ImageIcon; @@ -111,7 +165,14 @@ export function SnapShotContentsButton({
- Accessibility data +
+ Accessibility data + {onCopySnapshot && ( +
+ +
+ )} +
{accessibilityDetails ? ( Promise) | undefined; className?: string; }) { return ( @@ -157,7 +220,11 @@ export function SnapShotAttachmentDetails({
{source.appName} - +
{source.windowTitle || "Captured window"} diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index 50b50273ba965..d89bea79080da 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -129,7 +129,7 @@ export function SubagentTooltipContent(props: { showBadge={showInstanceBadge && entry?.accentColor !== undefined} badgeContent="none" badgeClassName="h-2 min-w-2 px-0" - iconClassName="size-3 shrink-0 grayscale opacity-60" + iconClassName="size-3 shrink-0 opacity-60" /> ) : ( diff --git a/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx new file mode 100644 index 0000000000000..b529cd6afe6a1 --- /dev/null +++ b/apps/web/src/components/chat/ThreadDetailsIssueRows.tsx @@ -0,0 +1,43 @@ +import { threadIssueKeyOf, type ThreadIssueLink } from "@t3tools/contracts"; +import type { MouseEvent as ReactMouseEvent } from "react"; + +import { cn } from "~/lib/utils"; + +import { IssueGlyph } from "../issue/issuePresentation"; +import { ThreadDetailsControl } from "./ThreadDetailsControl"; +import { + THREAD_DETAILS_PANEL_ICON_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, +} from "./threadDetailsPanelStyles"; + +/** + * The thread details panel's issue rows, one per linked issue, beside the pull request rows. A + * row names the issue as it was when linked and opens it in the right panel, which reads its + * live state. + */ +export function ThreadDetailsIssueRows({ + links, + onOpenLink, +}: { + links: ReadonlyArray; + onOpenLink: (event: ReactMouseEvent, link: ThreadIssueLink) => void; +}) { + if (links.length === 0) return null; + return ( + <> + {links.map((link) => ( + onOpenLink(event, link)} + > + + + {link.displayKey}: {link.title} + + + ))} + + ); +} diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index f2f41be10f958..1c3fa1a3899fc 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerKind, ProjectId, SourceControlProviderKind, ThreadId, @@ -119,6 +120,7 @@ import { act, render as renderUi } from "../../../test/render"; import { useComposerDraftStore } from "~/composerDraftStore"; import { useUiStateStore } from "~/uiStateStore"; import { ThreadDetailsPrRow } from "./ThreadDetailsPrRow"; +import { ThreadDetailsIssueRows } from "./ThreadDetailsIssueRows"; import { ThreadDetailsThreadPrRows } from "./ThreadDetailsPrRows"; const threadRef: ScopedThreadRef = { @@ -173,7 +175,6 @@ it("merges with the last selected merge method", async () => { status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} />, ); @@ -202,7 +203,6 @@ it("requires a new merge click after passing checks become pending and pass agai status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} /> ); @@ -266,7 +266,6 @@ it("adds the failing checks to a given composer instead of opening a new thread" status={null} project={null} label="Test PR" - openAriaLabel="Open PR" onOpen={vi.fn()} composerTarget={threadRef} />, @@ -333,3 +332,66 @@ it.each([ `using ${expected}`, ); }); + +it("names a linked pull request row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + state.projects = [repositoryProject]; + state.pullRequests = [ + { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + linkedAt: "2026-10-30T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ]; + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Test PR"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/pull request/i); + expect(name).toContain("#1"); + expect(name).toContain("Test PR"); +}); + +it("names a linked issue row by its kind, number and title, not its URL", async () => { + await using screen = await setup(); + await act(async () => { + await screen.rerender( + , + ); + }); + const row = [...screen.container.querySelectorAll("button")].find((button) => + button.textContent?.includes("Sidebar flickers on resize"), + )!; + const name = row.getAttribute("aria-label") ?? row.textContent ?? ""; + expect(name).not.toContain("https://"); + expect(name).toMatch(/issue/i); + expect(name).toContain("#123"); + expect(name).toContain("Sidebar flickers on resize"); +}); diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index acf9629a10347..c067632980156 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -94,7 +94,6 @@ export function ThreadDetailsPrRow({ status, project, label, - openAriaLabel, onOpen, onActed, onStopWatching, @@ -107,7 +106,6 @@ export function ThreadDetailsPrRow({ status: PrStatusIndicator | null; project: EnvironmentProject | null; label: string; - openAriaLabel: string; onOpen: (event: ReactMouseEvent) => void; onActed?: () => void; onStopWatching?: (() => void) | undefined; @@ -265,6 +263,15 @@ export function ThreadDetailsPrRow({ ); + const stateLabel = ( + statePresentation ?? + (pr ? resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }) : null) + )?.label.toLowerCase(); + const title = (detail?.title ?? pr?.title)?.trim(); + const openAriaLabel = `${capitalizeTerm(terminology.singular)} #${number}${ + stateLabel ? `, ${stateLabel}` : "" + }${title ? `: ${title}` : ""}`; + const rowTooltip = detail === null || statePresentation === null ? ( diff --git a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx index 65f796341d3fe..31ea6c6865a4c 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRows.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRows.tsx @@ -71,7 +71,6 @@ function ThreadDetailsPrLinkRow({ status={prStatusIndicator(pr, linked?.sourceControlProvider)} project={project} label={`#${link.number}${link.snapshot === null ? "" : `: ${link.snapshot.title}`}`} - openAriaLabel={link.url} onOpen={onOpen} onStopWatching={onStopWatching} composerTarget={composerTarget} @@ -207,7 +206,6 @@ export function ThreadDetailsThreadPrRows({ status={displayed.status} project={rowProject} label={`#${number}${pr?.title.trim() ? `: ${pr.title}` : ""}`} - openAriaLabel={url} onOpen={(event) => openPrLink(event, url)} composerTarget={composerTarget} {...(onActed ? { onActed } : {})} diff --git a/apps/web/src/components/chat/ThreadFindBar.tsx b/apps/web/src/components/chat/ThreadFindBar.tsx index 466cd929a7580..5ef0485ff4f50 100644 --- a/apps/web/src/components/chat/ThreadFindBar.tsx +++ b/apps/web/src/components/chat/ThreadFindBar.tsx @@ -1,9 +1,13 @@ -import { useEffect, useRef, type KeyboardEvent } from "react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"; import { cn } from "~/lib/utils"; -import { formatThreadFindCount } from "./threadFind"; +import { + formatThreadFindCount, + nextThreadFindAnnouncement, + type ThreadFindAnnouncement, +} from "./threadFind"; import { THREAD_DETAILS_CARD_GAP } from "./threadDetailsCardLayout"; interface ThreadFindBarProps { @@ -14,6 +18,10 @@ interface ThreadFindBarProps { readonly status: "loading" | "error" | null; readonly onRetry: () => void; readonly activeIndex: number; + /** Bumped by each user search or step; background refreshes keep it. */ + readonly navigationId: number; + /** Whether the label shows the outcome of `navigationId`: a count or a failure. */ + readonly settled: boolean; readonly focusRequestId: number; readonly onQueryChange: (query: string) => void; readonly onNext: () => void; @@ -37,8 +45,6 @@ export function ThreadFindBar(props: ThreadFindBarProps) { props.open, ]); - if (!props.open) return null; - const hasQuery = props.query.trim().length > 0; const noResults = hasQuery && !props.status && props.matchCount === 0; let label = ""; @@ -47,6 +53,17 @@ export function ThreadFindBar(props: ThreadFindBarProps) { } if (props.status === "loading") label = "Searching…"; if (props.status === "error") label = "Search failed"; + const [storedAnnouncement, setAnnouncement] = useState(null); + const announcement = nextThreadFindAnnouncement(storedAnnouncement, { + navigationId: props.navigationId, + text: label, + settled: props.settled || props.status === "loading", + provisional: props.status !== null, + }); + if (announcement !== storedAnnouncement) setAnnouncement(announcement); + + if (!props.open) return null; + const navigationDisabled = props.matchCount === 0 || props.status === "loading" || props.counting === true; const handleKeyDown = (event: KeyboardEvent) => { @@ -87,8 +104,11 @@ export function ThreadFindBar(props: ThreadFindBarProps) { onKeyDown={handleKeyDown} /> + + {announcement.text} + { + setup(); + state.projection = { ...(state.projection as Record), runs: [] }; + await using screen = await render( + , + { router: "/environment/fork" }, + ); + + const mergeBack = screen.getByRole("button", { name: "Merge back to source conversation" }); + await userEvent.hover(mergeBack); + await vi.waitFor(() => + expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe( + "Complete a run in this fork before merging it back", + ), + ); + + state.commandSucceeds = true; + await mergeBack.click({ force: true }); + expect(screen.router?.state.location.pathname).toBe("/environment/fork"); +}); + it("shows a delegated-from thread's full title in its tooltip even when its environment is unavailable", async () => { setup(); const longTitle = "Parent task delegated from another machine that has a long description"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 52f1b9c17bf9c..ed19f9f61fe2c 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -930,7 +930,7 @@ export function ThreadRelationshipsPanel(props: { ? `Merge back to ${parentTitle}` : "Merge back to source conversation" } - disabled={!canMerge || busyAction !== null} + aria-disabled={!canMerge || busyAction !== null || undefined} onClick={() => void merge()} > {busyAction === "merge" ? ( diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index f7acdab25b977..dca5e33d8851d 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -209,7 +209,6 @@ export function TimelineMinimap({ onMouseDown={(event) => event.preventDefault()} type="button" > -
{items.map((item, index) => { const top = `${resolveTimelineMinimapTopPercent(index, items.length)}%`; const activeDistance = diff --git a/apps/web/src/components/chat/TimelineRowParts.tsx b/apps/web/src/components/chat/TimelineRowParts.tsx index 549b9c7a422f9..c881b845dd21a 100644 --- a/apps/web/src/components/chat/TimelineRowParts.tsx +++ b/apps/web/src/components/chat/TimelineRowParts.tsx @@ -41,14 +41,22 @@ export function TimelineRowTimestamp({ ); } -export function ActivityShimmerOverlay({ children }: { children: ReactNode }) { +export function ActivityShimmerOverlay({ + children, + className, +}: { + children: ReactNode; + className?: string; +}) { return ( - {children} + + {children} + ); diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 1dd33eacd4649..d6c80ea241cc6 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,3 +1,4 @@ +import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { @@ -103,7 +104,7 @@ const MEDIA_EDGE_CLASS_NAME = "relative after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:ring-1 after:ring-inset after:ring-black/9 dark:after:ring-white/12"; const BUBBLE_CHIP_CLASS_NAME = - "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]"; + "[&_[data-slot=context-chip]]:[--context-chip-message-ink:var(--context-chip-message)]"; function UserFileCard({ file, @@ -598,6 +599,25 @@ function UserTimelineRow({ row }: { row: Extract { + const image = userImages.find((candidate) => candidate.id === id); + const record = resolvedContext.records + .map(asKnownContextRecord) + .find((candidate) => candidate?.kind === "image" && candidate.attachmentId === id); + if (!image?.previewUrl || record?.kind !== "image") + throw new Error("Snapshot is no longer available."); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ctx.activeThreadEnvironmentId, messageId: row.message.id }, + records: [{ ...record, ...(image.source ? { source: image.source } : {}) }], + }); + if (!fragment) throw new Error("The snapshot is too large to copy."); + await copySnapshotToClipboard( + image.previewUrl, + formatComposerContextReference(record), + fragment, + ); + }; const onBodyCopyCapture = (event: React.ClipboardEvent) => { if (resolvedContext.records.length === 0 || !event.clipboardData) return; const selection = window.getSelection(); @@ -664,7 +684,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(userImages, image.id); + const preview = buildExpandedImagePreview(userImages, image.id, copySnapshot); if (preview) onImageExpand(preview); }} onOpenFile={onFileOpen} @@ -740,7 +760,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(regularImages, image.id); + const preview = buildExpandedImagePreview(regularImages, image.id, copySnapshot); if (!preview) return; ctx.onImageExpand(preview); }} @@ -775,7 +795,10 @@ function UserTimelineRow({ row }: { row: Extract )} {image.previewUrl && image.source?.kind === "snap-shot" ? ( - + copySnapshot(image.id)} + /> ) : null}
))} diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index ec6a15041c016..84c3a5b65896a 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -34,7 +34,7 @@ import { MenuTrigger, } from "../ui/menu"; import { useComposerDraftStore, DraftId } from "../../composerDraftStore"; -import { getProviderModelCapabilities } from "../../providerModels"; +import { getProviderModelCapabilities, keepsUnavailableModelOptions } from "../../providerModels"; import { cn } from "~/lib/utils"; import { Badge } from "../ui/badge"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -122,7 +122,7 @@ function getSelectedTraits( ) { const caps = getProviderModelCapabilities(models, model, provider, planModeEnabled); const modelIsUnavailable = - (provider === "opencode" || provider === "cursor") && + keepsUnavailableModelOptions(provider, model) && !models.some((candidate) => candidate.slug === normalizeModelSlug(model, provider)); const descriptors = modelIsUnavailable ? buildUnavailableModelOptionDescriptors( diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 6db8100def51d..f7a6d74070909 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -1,4 +1,6 @@ import { ProjectKnowledgeContextChip } from "../projectKnowledge/ProjectKnowledgeContextChip"; +import { useNativeFileDrag } from "../../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isSvgAttachment } from "@t3tools/shared/image"; import { useRenderedAppearance } from "../../hooks/useTheme"; @@ -74,11 +76,15 @@ function UserMessageMentionChip(props: { copyMarkdown: string; }) { const ctx = use(TimelineRowCtx); + const nativeDrag = useNativeFileDrag(ctx.activeThreadEnvironmentId, () => + resolvePathLinkTarget(props.record.path, ctx.workspaceRoot ?? ""), + ); return ( } aria-label={`Preview ${props.record.path}`} diff --git a/apps/web/src/components/chat/backgroundThread.ts b/apps/web/src/components/chat/backgroundThread.ts index b3dfee09a663c..e402bc5e62165 100644 --- a/apps/web/src/components/chat/backgroundThread.ts +++ b/apps/web/src/components/chat/backgroundThread.ts @@ -5,3 +5,6 @@ import { createContext } from "react"; * parent's panel; its global shortcuts and listeners stand down. */ export const BackgroundThreadContext = createContext(false); + +/** True only for a thread kept mounted out of sight under Settings or Usage. */ +export const HiddenThreadContext = createContext(false); diff --git a/apps/web/src/components/chat/composerProviderState.test.tsx b/apps/web/src/components/chat/composerProviderState.test.tsx index 54a6fd3d6bf99..a45d895953fff 100644 --- a/apps/web/src/components/chat/composerProviderState.test.tsx +++ b/apps/web/src/components/chat/composerProviderState.test.tsx @@ -151,26 +151,39 @@ describe("getComposerProviderState", () => { expect(state.modelOptionsForDispatch).toEqual(selections(["agent", "build"])); }); - it("preserves explicit options when the selected model is absent from the catalog", () => { - const state = getComposerProviderState({ - provider: ProviderDriverKind.make("opencode"), + it.each([ + { + driver: "opencode", model: "opencode/kimi-k3", - models: [ - { - slug: "opencode/big-pickle", - name: "Big Pickle", - isCustom: false, - capabilities: {}, - }, - ], - modelOptions: selections(["variant", "max"], ["agent", "build"]), - planModeEnabled: false, - }); + catalogModel: "opencode/big-pickle", + options: selections(["variant", "max"], ["agent", "build"]), + }, + { + driver: "pi", + model: "anthropic/claude-sonnet-4", + catalogModel: "default", + options: selections(["thinking", "high"]), + }, + { + driver: "acpRegistry", + model: "gateway/chosen-model", + catalogModel: "default", + options: selections(["reasoning", "high"]), + }, + ])( + "preserves explicit $driver options when the selected model is absent from the catalog", + ({ driver, model, catalogModel, options }) => { + const state = getComposerProviderState({ + provider: ProviderDriverKind.make(driver), + model, + models: [{ slug: catalogModel, name: catalogModel, isCustom: false, capabilities: {} }], + modelOptions: options, + planModeEnabled: false, + }); - expect(state.modelOptionsForDispatch).toEqual( - selections(["variant", "max"], ["agent", "build"]), - ); - }); + expect(state.modelOptionsForDispatch).toEqual(options); + }, + ); it("validates options for a known model selected through a legacy alias", () => { const state = getComposerProviderState({ diff --git a/apps/web/src/components/chat/composerProviderState.tsx b/apps/web/src/components/chat/composerProviderState.tsx index 3e6d932191e3f..2bad287673c33 100644 --- a/apps/web/src/components/chat/composerProviderState.tsx +++ b/apps/web/src/components/chat/composerProviderState.tsx @@ -17,7 +17,7 @@ import { } from "@t3tools/shared/model"; import type { DraftId } from "../../composerDraftStore"; -import { getProviderModelCapabilities } from "../../providerModels"; +import { getProviderModelCapabilities, keepsUnavailableModelOptions } from "../../providerModels"; import { getReasoningTraitStep, type PromptUltrathink, @@ -86,7 +86,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com promptInjectionState = "none", planModeEnabled, } = input; - if (provider === "opencode" || provider === "cursor") { + if (keepsUnavailableModelOptions(provider, model)) { const normalizedModel = normalizeModelSlug(model, provider); const modelIsInCatalog = models.some((candidate) => candidate.slug === normalizedModel); if (!modelIsInCatalog) { diff --git a/apps/web/src/components/chat/copySnapshot.test.ts b/apps/web/src/components/chat/copySnapshot.test.ts new file mode 100644 index 0000000000000..9ac7080f7b0f7 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.test.ts @@ -0,0 +1,75 @@ +import { ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + decodeComposerContextClipboardHtml, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { expect, it } from "vite-plus/test"; + +import { copySnapshot } from "./copySnapshot"; + +it.each([false, true])( + "preserves image bytes and snapshot metadata, custom format rejected: %s", + async (rejectCustom) => { + class Item { + constructor(readonly data: Record>) {} + } + let clipboard: Item | undefined; + const write = async ([item]: Item[]) => { + if (rejectCustom && item?.data[COMPOSER_CONTEXT_CLIPBOARD_MIME]) + throw new Error("Unsupported format"); + clipboard = item; + await Promise.all(Object.values(item!.data)); + }; + const originals = { + navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"), + ClipboardItem: Object.getOwnPropertyDescriptor(globalThis, "ClipboardItem"), + }; + using _globals = { + [Symbol.dispose]() { + for (const key of ["navigator", "ClipboardItem"] as const) { + const descriptor = originals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { clipboard: { write } }, + }); + Object.defineProperty(globalThis, "ClipboardItem", { configurable: true, value: Item }); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [ + { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "Snapshot", + attachmentId: "snapshot", + name: "snapshot.png", + mimeType: "image/png", + sizeBytes: 3, + source: { + kind: "snap-shot", + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, + }, + ], + })!; + const image = "data:image/png;base64,AQID"; + await copySnapshot(image, "Snapshot", fragment); + const png = await clipboard!.data["image/png"]!; + expect(png.type).toBe("image/png"); + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual([1, 2, 3]); + expect( + decodeComposerContextClipboardHtml(await (await clipboard!.data["text/html"]!).text()), + ).toEqual(JSON.parse(fragment)); + expect(await (await clipboard!.data["text/plain"]!).text()).toBe("Snapshot"); + }, +); diff --git a/apps/web/src/components/chat/copySnapshot.ts b/apps/web/src/components/chat/copySnapshot.ts new file mode 100644 index 0000000000000..118121e753647 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.ts @@ -0,0 +1,33 @@ +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextClipboardHtml, +} from "@t3tools/shared/composerContextClipboard"; + +import { readMediaPng } from "../media/mediaContent"; + +export async function copySnapshot(src: string, text: string, fragment: string): Promise { + if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") { + throw new Error("Snapshot copying requires a secure browser connection."); + } + const formats = { + "image/png": readMediaPng(src), + "text/plain": new Blob([text], { type: "text/plain" }), + "text/html": new Blob([encodeComposerContextClipboardHtml(text, fragment)], { + type: "text/html", + }), + }; + // Start writing within the click gesture, before the image fetch or decode completes. + try { + await navigator.clipboard.write([ + new ClipboardItem({ + ...formats, + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: new Blob([fragment], { + type: COMPOSER_CONTEXT_CLIPBOARD_MIME, + }), + }), + ]); + } catch { + // HTML carries the same snapshot metadata when custom clipboard formats are unsupported. + await navigator.clipboard.write([new ClipboardItem(formats)]); + } +} diff --git a/apps/web/src/components/chat/markdownFragments.ts b/apps/web/src/components/chat/markdownFragments.ts index 90a419039053e..9acacb8c65fe2 100644 --- a/apps/web/src/components/chat/markdownFragments.ts +++ b/apps/web/src/components/chat/markdownFragments.ts @@ -68,7 +68,7 @@ type HeadingHastNode = { children?: HeadingHastNode[]; }; -function githubHeadingSlug(text: string): string { +export function githubHeadingSlug(text: string): string { return text .trim() .toLowerCase() diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx index 2574f25fc0431..38ecff7666508 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.tsx @@ -5,16 +5,25 @@ import { } from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; import ReactMarkdown from "react-markdown"; +import remarkMath from "remark-math"; +import type { PluggableList } from "unified"; import { describe, expect, it } from "vite-plus/test"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; +import { rehypeHeadingIds } from "./markdownFragments"; + +const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. -const html = (source: string) => +const renderMarkdown = (source: string, math = false) => renderToStaticMarkup( {source} , @@ -22,9 +31,27 @@ const html = (source: string) => .replace(/>\s+<") .trim(); +const html = (source: string) => renderMarkdown(source); + +const punctuatedHeadings = ["Step 1: Install", "Done:", "apps/web", "Fix (web)", "What's next?"]; + describe("splitMarkdownBlocks", () => { it.each([ "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).", + "## Step 1: Install\n\n## Step 1: Install\n\n[second](#step-1-install-1)", + "## /home/a/b.ts\n\n## home/a/b.ts", + "## see https://x.com/a\n\n## see httpsxcoma", + "## Done:\n\n## Done", + "## `Setup`\n\n## Setup", + "## a ` x ` b\n\n## a x b", + "# Setup\n\n# $$ Setup $$\n\n[second](#setup-1)", + "# Setup\n\n# Setup\n\n[Second setup](#setup-1)", + "\ufeff# Setup\n\n# Setup\n\n[second](#setup-1)", + "> Setup\n> ===\n\n> Setup\n> ===", + "# onetwo\n\none\ntwo\n===", + "# Setup\n\n# Setup\n\n[second](#setup-1)", + "# Setup\n\npara\n\n- a\n\n ```\n b\nx\n\nSetup\n===\n", + "Setup\n===\n\n> ## **Setup**\n\n- # [Setup](https://example.com)\n\n```sh\n# Setup\n```", "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.", "1. first\n\n2. second\n\nText\n\n3) restarted", "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend", @@ -39,18 +66,29 @@ describe("splitMarkdownBlocks", () => { ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => { for (let end = 0; end <= text.length; end++) { const source = text.slice(0, end); - const blocks = splitMarkdownBlocks(source); - expect(blocks?.join("")).toBe(source); - expect(blocks!.map(html).join("")).toBe(html(source)); + const blocks = splitMarkdownBlocks(source) ?? [source]; + expect(blocks.join("")).toBe(source); + expect(blocks.map(html).join("")).toBe(html(source)); + expect(blocks.map((block) => renderMarkdown(block, true)).join("")).toBe( + renderMarkdown(source, true), + ); } }); + it.each(punctuatedHeadings)("keeps splitting headings with prose punctuation: %s", (heading) => { + expect(splitMarkdownBlocks(`## ${heading}\n\nNext paragraph.`)).toEqual([ + `## ${heading}\n\n`, + "Next paragraph.", + ]); + }); + it("splits only between closed blocks", () => { expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([ "a\n\n", "```\nb\n\nc\n```\n\n- d\n\n- e\n\n", "f", ]); + expect(splitMarkdownBlocks("a\n\n---\n\nb")).toEqual(["a\n\n", "---\n\n", "b"]); }); it.each([ diff --git a/apps/web/src/components/chat/markdownStreamBlocks.ts b/apps/web/src/components/chat/markdownStreamBlocks.ts index 107d5d0143c72..36decaa301838 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.ts +++ b/apps/web/src/components/chat/markdownStreamBlocks.ts @@ -1,3 +1,5 @@ +import { githubHeadingSlug } from "./markdownFragments"; + // Definitions, footnotes, raw HTML, container directives and display math can tie blocks together. const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m; // A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span. @@ -7,13 +9,22 @@ const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/; // Claude insight fences render as one callout, so they stay in one block until the closing rule. const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; +// An ATX heading, also inside a list item or blockquote; group 1 is its text. +const ATX_HEADING_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/; +// Setext headings may span a paragraph and containers, so leave their parsing to the renderer. +const SETEXT_UNDERLINE_PATTERN = + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*(?:=+|-+)[ \t]*$/; /** * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it - * would inside the whole text. Returns null when the text uses syntax that spans blocks. + * would inside the whole text. Returns null when the text uses syntax that spans blocks, such as + * headings with the same slug, whose ids are numbered across the whole text. */ export function splitMarkdownBlocks(text: string): string[] | null { - if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null; + // remark-parse strips a leading BOM before recognizing the first heading. + if (text.startsWith("\ufeff") || text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) + return null; const blocks: string[] = []; let blockStart = 0; let lineStart = 0; @@ -21,11 +32,35 @@ export function splitMarkdownBlocks(text: string): string[] | null { let fenceIndent = 0; let afterBlankLine = false; let insightIndent: string | null = null; + const headingKeys = new Set(); + const needsWholeHeading = (headingText: string | undefined) => { + if (headingText === undefined) return false; + // Inline syntax and path/directive colons need the renderer before their slug is known. + if (/[`*_~[\]<&\\!$]|:(?!\s|$)/.test(headingText)) return true; + const key = githubHeadingSlug(headingText); + if (!key) return false; + if (headingKeys.has(key)) return true; + headingKeys.add(key); + return false; + }; + const headingNeedsWholeDocument = (line: string, mayUnderline = true) => + (mayUnderline && SETEXT_UNDERLINE_PATTERN.test(line)) || + needsWholeHeading(ATX_HEADING_PATTERN.exec(line)?.[1]); + // Only a line right after paragraph text can underline it; elsewhere "---" is a thematic break. + let afterContentLine = false; for (const line of text.split("\n")) { const opener = FENCE_PATTERN.exec(line)?.[1]; + const mayUnderline = afterContentLine; + afterContentLine = false; if (fence !== null) { // A line left of an indented fence may end the list item holding it, which isn't tracked. - if (/\S/.test(line.slice(0, fenceIndent))) break; + if (/\S/.test(line.slice(0, fenceIndent))) { + const rest = text.slice(lineStart).split("\n"); + for (const restLine of rest) { + if (headingNeedsWholeDocument(restLine)) return null; + } + break; + } if ( opener && opener[0] === fence[0] && @@ -40,6 +75,8 @@ export function splitMarkdownBlocks(text: string): string[] | null { } else if (line.trim() === "") { afterBlankLine = true; } else { + if (headingNeedsWholeDocument(line, mayUnderline)) return null; + afterContentLine = opener === undefined; if ( afterBlankLine && insightIndent === null && diff --git a/apps/web/src/components/chat/threadFind.test.ts b/apps/web/src/components/chat/threadFind.test.ts new file mode 100644 index 0000000000000..43b1c75b07f0d --- /dev/null +++ b/apps/web/src/components/chat/threadFind.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vite-plus/test"; +import { nextThreadFindAnnouncement, type ThreadFindAnnouncement } from "./threadFind"; + +type Step = Omit & { readonly provisional?: boolean }; + +function replay(steps: readonly Step[]) { + let current: ThreadFindAnnouncement | null = null; + const spoken: string[] = []; + for (const step of steps) { + const next = nextThreadFindAnnouncement(current, { provisional: false, ...step }); + if (next.text !== (current?.text ?? "")) spoken.push(next.text); + current = next; + } + return spoken; +} + +describe("nextThreadFindAnnouncement", () => { + it("speaks each settled search or step once and stays silent through streamed refreshes", () => { + expect( + replay([ + { navigationId: 1, text: "Searching…", settled: true, provisional: true }, + { navigationId: 1, text: "1/…", settled: false }, + { navigationId: 1, text: "1/3", settled: true }, + { navigationId: 1, text: "1/…", settled: false }, + { navigationId: 1, text: "1/4", settled: true }, + { navigationId: 2, text: "1/4", settled: false }, + { navigationId: 2, text: "2/4", settled: true }, + { navigationId: 2, text: "2/5", settled: true }, + ]), + ).toEqual(["Searching…", "1/3", "2/4"]); + }); + + it("speaks a failure and the result of retrying it", () => { + expect( + replay([ + { navigationId: 1, text: "Search failed", settled: true, provisional: true }, + { navigationId: 1, text: "1/3", settled: true }, + { navigationId: 1, text: "1/4", settled: true }, + ]), + ).toEqual(["Search failed", "1/3"]); + }); + + it("speaks a new search that ends on the same count as the last one", () => { + expect( + replay([ + { navigationId: 1, text: "Searching…", settled: true, provisional: true }, + { navigationId: 1, text: "0/0", settled: true }, + { navigationId: 2, text: "Searching…", settled: true, provisional: true }, + { navigationId: 2, text: "0/0", settled: true }, + ]), + ).toEqual(["Searching…", "0/0", "Searching…", "0/0"]); + }); +}); diff --git a/apps/web/src/components/chat/threadFind.ts b/apps/web/src/components/chat/threadFind.ts index d0a265ceb13fa..98bff31c95996 100644 --- a/apps/web/src/components/chat/threadFind.ts +++ b/apps/web/src/components/chat/threadFind.ts @@ -23,3 +23,28 @@ export function stepThreadFindIndex(index: number, total: number, delta: number) export function formatThreadFindCount(index: number, total: number): string { return total <= 0 ? "0/0" : `${clampThreadFindIndex(index, total) + 1}/${total}`; } + +export interface ThreadFindAnnouncement { + readonly navigationId: number; + readonly text: string; + /** The label shows the outcome of `navigationId`: a count, a search or a failure. */ + readonly settled: boolean; + /** "Searching…" or a failure: spoken, but a later count for the same navigation is too. */ + readonly provisional: boolean; +} + +/** + * What the find counter's live region says: the settled outcome of each + * user search or step, once. Background refreshes during streaming keep the + * navigation, so they stay silent. A new query passes through "Searching…", + * so its count is spoken even when it equals the last one. + */ +export function nextThreadFindAnnouncement( + previous: ThreadFindAnnouncement | null, + next: ThreadFindAnnouncement, +): ThreadFindAnnouncement { + if (!next.settled) return previous ?? { ...next, text: "" }; + if (previous?.navigationId !== next.navigationId) return next; + if (previous.settled && !previous.provisional) return previous; + return previous.text === next.text ? previous : next; +} diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.ts index 776cd39096a8a..aa752812cd223 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.test.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from "vite-plus/test"; -import { MessageId } from "@t3tools/contracts"; -import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; +import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; +import { + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + formatComposerContextReference, + toComposerContextId, +} from "@t3tools/shared/composerContextReferences"; import { deriveTimelineMinimapItems, resolveTimelineMinimapPreview } from "./timelineMinimapItems"; @@ -45,4 +50,32 @@ describe("resolveTimelineMinimapPreview", () => { }); expect(preview?.assistantText).toBe("Started a thread and Fix CI."); }); + + it("previews a quote, a context chip and a file link in the user's message as their text", () => { + const quote = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("env-1"), + threadId: ThreadId.make("thread-1"), + messageId: MessageId.make("assistant-1"), + text: "The cache misses on a cold start.", + start: 0, + end: 33, + prefix: "", + suffix: "", + }); + const file = formatComposerContextReference({ + kind: "file", + contextId: toComposerContextId("readme"), + label: "README.md", + }); + const preview = resolveTimelineMinimapPreview({ + id: "turn-1", + rowIndex: 0, + userText: `${quote}\nWhere do ${file} and [math.ts](src/math.ts) cover this?`, + assistantText: null, + }); + expect(preview?.userText).toBe( + "The cache misses on a cold start. Where do README.md and math.ts cover this?", + ); + }); }); diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 386abbaa013a3..151a02d88175e 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -1,5 +1,9 @@ +import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; -import { isAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; +import { + isAttachmentOnlyBootstrapPrompt, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; import type { Nodes } from "mdast"; import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; @@ -94,8 +98,12 @@ export function markdownPlainText(markdown: string): string { return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); } -function compactMinimapPreview(text: string | null | undefined) { - const compact = text?.replace(/\s+/g, " ").trim() ?? ""; +// The tooltip shows a few lines; bound parsing work for long messages and streaming responses. +function markdownMinimapPreview(markdown: string | null) { + if (markdown === null) return null; + const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + .replace(/\s+/g, " ") + .trim(); return compact.length > 0 ? compact : null; } @@ -106,12 +114,14 @@ export function resolveTimelineMinimapPreview( ? null : { ...item, - userText: compactMinimapPreview(item.userText), - // The tooltip shows three lines; bound parsing work while long responses stream. - assistantText: compactMinimapPreview( - item.assistantText === null + // Before markdown parsing, which would reduce a citation link to "Assistant quote". + userText: markdownMinimapPreview( + item.userText === null ? null - : markdownNodeText(markdownPreviewParser.parse(item.assistantText.slice(0, 1_500))), + : assistantCitationsToPlainText( + replaceComposerContextReferences(item.userText, (reference) => reference.label), + ), ), + assistantText: markdownMinimapPreview(item.assistantText), }; } diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index e2bf9676b8b6d..d48e965895ddd 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -48,6 +48,7 @@ function deferred() { it.each([ { kind: "file", edit: "delete" }, { kind: "image", edit: "delete" }, + { kind: "image", edit: "retain" }, { kind: "file", edit: "undo" }, { kind: "file", edit: "retain" }, { kind: "file", edit: "switch" }, @@ -124,7 +125,17 @@ it.each([ const attachment = ( kind === "file" ? { ...attachmentFields, kind: "file" as const } - : { ...attachmentFields, kind: "image" as const } + : { + ...attachmentFields, + kind: "image" as const, + source: { + kind: "snap-shot" as const, + appName: "Finder", + windowTitle: "Downloads", + capturedAt: "2026-01-01T00:00:00.000Z", + accessibleText: "Downloads", + }, + } ) satisfies ComposerContextRecord; const annotation = { version: 1, @@ -182,6 +193,10 @@ it.each([ const draft = store.getComposerDraft(target)!; expect(draft.prompt).toBe(promptRef.current); const attachments = kind === "file" ? draft.files : draft.images; + if (kind === "image" && edit === "retain") + expect(draft.images[0]?.source).toEqual( + attachment.kind === "image" ? attachment.source : undefined, + ); expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index c1dac7cb64ed7..22fac79cd51e2 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -246,6 +246,7 @@ export function useComposerContextImport(input: { sizeBytes: file.size, previewUrl: URL.createObjectURL(file), file, + ...(record.source ? { source: record.source } : {}), }, ], { diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index bde49ca4f191d..a0c5a6f0888da 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -189,6 +189,7 @@ interface ComposerSendInput { readonly activeThreadKey: string | null; readonly activeThreadBranch: string | null; readonly activeProject: EnvironmentProject | null; + readonly activeProjectIsScratch: boolean; readonly activeProjectDefaultModelSelection: ModelSelection | null; readonly activeProposedPlan: LatestProposedPlanState | null; readonly activeMessageCount: number; @@ -293,6 +294,7 @@ export function useComposerSend(input: ComposerSendInput) { activeThreadKey, activeThreadBranch, activeProject, + activeProjectIsScratch, activeProjectDefaultModelSelection, activeProposedPlan, activeMessageCount, @@ -727,6 +729,7 @@ export function useComposerSend(input: ComposerSendInput) { replyTo, }, setThreadError, + { dispatchMode, submissionIntent }, ); return; } @@ -981,6 +984,7 @@ export function useComposerSend(input: ComposerSendInput) { sendEnvMode, worktreePath: activeThread.worktreePath, activeThreadBranch, + isScratchProject: activeProjectIsScratch, resumeCompactionTokens, keepFullHistory, phase, diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx index 3b23abfcb7c9a..1a6e2b038832c 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx @@ -39,7 +39,13 @@ vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({ refreshSelection: resources.refreshSelection, }), })); -vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects })); +vi.mock("../../state/entities", () => ({ + useProjects: () => resources.projects, + readProject: (ref: { environmentId: EnvironmentId; projectId: ProjectId }) => + resources.projects.find( + (project) => project.environmentId === ref.environmentId && project.id === ref.projectId, + ) ?? null, +})); vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) })); function setup() { @@ -102,6 +108,7 @@ function setup() { enabled: true, }, connection: { phase: "connected", error: null, traceId: null }, + refusedRouteIds: [], serverConfig: null, }, ]), @@ -314,3 +321,35 @@ it("keeps the selected models when automatic routing picks another machine", asy await expect.element(screen.getByText(b)).toBeInTheDocument(); await expect.element(screen.getByText("gpt-6.1-sol, gpt-6.1-luna")).toBeInTheDocument(); }); + +it.each([ + { name: "takes the destination default", explicit: false, remoteDefault: true, model: "luna" }, + { name: "keeps a model the user picked", explicit: true, remoteDefault: true, model: "sol" }, + { + name: "keeps the last-used model without a default", + explicit: false, + remoteDefault: false, + model: "sol", + }, +])("$name when the draft switches machine by hand", async ({ explicit, remoteDefault, model }) => { + const { b, draftId, input, store } = fanoutSetup(); + const codex = ProviderInstanceId.make("codex"); + resources.projects = resources.projects.map((project) => + project.environmentId === b && remoteDefault + ? { ...project, defaultModelSelection: createModelSelection(codex, "luna") } + : project, + ); + store.setStickyModelSelection(createModelSelection(codex, "sol")); + store.setModelSelection(draftId, createModelSelection(codex, "sol"), { explicit }); + await using screen = await render( + , + ); + await screen.getByRole("button", { name: `Switch to ${b}` }).click(); + await expect.element(screen.getByText(b)).toBeInTheDocument(); + const draft = store.getComposerDraft(draftId); + expect(draft?.activeProvider).toBe(codex); + expect(draft?.modelSelectionByProvider[codex]?.model).toBe(model); + expect(draft?.modelSelectionExplicit === true).toBe(explicit); +}); diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts index 977f5cb31c7f1..86664b567a658 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts @@ -35,6 +35,7 @@ import { useAtomCommand } from "../../state/use-atom-command"; import type { DraftSessionState } from "../../composerDraftStore"; import { loadBalancingSendWarning } from "./composerSend.logic"; import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { seedDraftModelSelection } from "../../lib/seedDraftModelSelection"; import { draftFanoutSelectionsAtom } from "./chatViewSend"; interface DraftEnvironmentRoutingInput { @@ -337,6 +338,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput) loadBalancedEnvironmentId: null, }); } + seedDraftModelSelection(draftId, projectRef); }; const finish = () => { if (environmentChangeRef.current === request) environmentChangeRef.current = null; diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index 74260c4979c51..cf460e48e4bbf 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -33,12 +33,15 @@ import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attach interface RunStatus { readonly id: RunId; readonly status: string; + readonly activeAttemptId?: string; } const mocks = await vi.hoisted(async () => { const { Atom } = await import("effect/reactivity"); return { editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(), + promoteQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(), + promoteCommand: {}, // The projection's runs per thread, written by each test to stand in for the server. threadRuns: Atom.family((_key: string) => Atom.make | null>(null).pipe(Atom.keepAlive), @@ -47,7 +50,8 @@ const mocks = await vi.hoisted(async () => { }); vi.mock("../../state/use-atom-command", () => ({ - useAtomCommand: () => mocks.editQueuedRun, + useAtomCommand: (command: unknown) => + command === mocks.promoteCommand ? mocks.promoteQueuedRun : mocks.editQueuedRun, })); vi.mock("../../hooks/useSettings", () => ({ @@ -63,13 +67,35 @@ vi.mock("../../state/threads", async () => { threadEnvironment: { snapshotAtom: () => Atom.make(null), editQueuedRun: {}, + promoteQueuedRun: mocks.promoteCommand, }, environmentThreadDetails: { statusAtom: () => Atom.make("ready"), quietThreadAtom: (ref: ScopedThreadRef) => Atom.make((get) => { const runs = get(mocks.threadRuns(key(ref))); - return runs === null ? null : { projection: { runs } }; + if (runs === null) return null; + // A Claude-like session whose running turn takes steering. + return { + projection: { + thread: { id: ref.threadId, activeProviderThreadId: null }, + runs, + messages: [], + providerThreads: [], + providerSessions: [ + { + id: "session", + status: "running", + capabilities: { turns: { supportsActiveSteering: true } }, + }, + ], + providerTurns: runs.flatMap((run) => + run.activeAttemptId + ? [{ runAttemptId: run.activeAttemptId, status: "running" }] + : [], + ), + }, + }; }), }, environmentThreadShells: { @@ -154,6 +180,7 @@ function view( function setup() { mocks.editQueuedRun.mockReset(); + mocks.promoteQueuedRun.mockReset(); useAttachmentUploadStore.setState({ uploadsByImageId: {} }); useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); setRuns(THREAD_A, "queued"); @@ -250,6 +277,42 @@ describe("useQueuedRunEdit", () => { }, ); + it.each([ + // Cmd+Enter or Cmd-click with Queue as the default: save, then steer. + { dispatchMode: "steer", submissionIntent: "alternate", steers: true }, + // Enter or the Update button with Steer as the default: save in place only. + { dispatchMode: "steer", submissionIntent: "foreground", steers: false }, + // Cmd+Enter with Steer as the default queues, so the message stays queued. + { dispatchMode: "queue", submissionIntent: "alternate", steers: false }, + ] as const)( + "a saved edit sent as $submissionIntent/$dispatchMode steers: $steers", + async (submission) => { + const { hook } = setup(); + mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); + mocks.promoteQueuedRun.mockResolvedValue({ _tag: "Success" }); + const activeRun = RunId.make("run-active"); + appAtomRegistry.set(mocks.threadRuns(runsKey(THREAD_A)), [ + { id: activeRun, status: "running", activeAttemptId: "attempt-1" }, + { id: RUN, status: "queued" }, + ]); + await using _screen = await render(view(THREAD_A, "queued", hook)); + await beginChangedEdit(hook); + await act(() => requireHook(hook).saveEdit(savedContent("changed"), () => {}, submission)); + expect(mocks.editQueuedRun).toHaveBeenCalledOnce(); + if (!submission.steers) { + expect(mocks.promoteQueuedRun).not.toHaveBeenCalled(); + return; + } + expect(mocks.promoteQueuedRun).toHaveBeenCalledExactlyOnceWith({ + environmentId: ENV, + input: { threadId: THREAD_A.threadId, queuedRunId: RUN, targetRunId: activeRun }, + }); + expect(mocks.editQueuedRun.mock.invocationCallOrder[0]).toBeLessThan( + mocks.promoteQueuedRun.mock.invocationCallOrder[0]!, + ); + }, + ); + it("saves an effort-only prompt without claiming removed attachments remain", async () => { const { hook } = setup(); mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index bdc7fbbba61ae..09cd1e36673a3 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -3,7 +3,9 @@ import { makeQueuedRunEditStore, makeQueuedRunsAtom, } from "@t3tools/client-runtime/queued-run-edit"; +import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ChatAttachment, @@ -50,6 +52,7 @@ import { } from "../../lib/composerContextReferences"; import { readFileAsDataUrl } from "../../lib/imageCompression"; import type { TerminalContextDraft } from "../../lib/terminalContext"; +import type { ComposerSubmissionIntent } from "../../composer-logic"; import type { ReviewCommentContext } from "../../reviewCommentContext"; import { appAtomRegistry } from "../../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../../state/server"; @@ -221,6 +224,7 @@ export function useQueuedRunEdit(input: { composerRef, } = input; const editQueuedRunCommand = useEditQueuedRunCommand(); + const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun); const editKey = scopedThreadKey(routeThreadRef); const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null; const editing = activeThreadId === null ? null : storedEdit; @@ -347,9 +351,39 @@ export function useQueuedRunEdit(input: { })); }); + // The same move as the queued row's "Send now" while a turn runs. + const steerSavedRun = async (edited: EditingQueuedRun) => { + const projection = appAtomRegistry.get( + environmentThreadDetails.quietThreadAtom({ environmentId, threadId: edited.threadId }), + )?.projection; + if (!projection) return; + const workflow = deriveThreadQueueWorkflowState(projection); + const queued = workflow.queuedRuns.find(({ run }) => run.id === edited.runId); + if ( + queued === undefined || + workflow.activeRun === null || + !workflow.canPromoteToSteer || + (queued.run.freshContext === true && !workflow.promoteSkipsCompaction) + ) { + return; + } + await promoteQueuedRun({ + environmentId, + input: { + threadId: edited.threadId, + queuedRunId: edited.runId, + targetRunId: workflow.activeRun.id, + }, + }); + }; + const saveEdit = async ( content: QueuedRunEditContent, setThreadError: (threadId: ThreadId, error: string | null) => void, + submission?: { + readonly dispatchMode: ComposerDispatchMode; + readonly submissionIntent: ComposerSubmissionIntent; + }, ) => { if (editing === null || isSaving) return; const newAttachments = [...content.images, ...content.files]; @@ -424,6 +458,11 @@ export function useQueuedRunEdit(input: { clearEditDraft(editing.runId); composerRef.current?.resetCursorState(); focusComposerSoon(); + // A plain submit means "Update queued message"; only the opposite-action shortcut or + // modifier-click asks to steer, as it does for a new follow-up. + if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") { + await steerSavedRun(editing); + } }; return { diff --git a/apps/web/src/components/chat/useThreadFind.ts b/apps/web/src/components/chat/useThreadFind.ts index b88951e3b6ac3..ada7955e1c2ad 100644 --- a/apps/web/src/components/chat/useThreadFind.ts +++ b/apps/web/src/components/chat/useThreadFind.ts @@ -214,6 +214,9 @@ export function useThreadFind({ counting, activeIndex, status, + navigationId: state.navigationId, + settled: + status === "error" || (status === null && !counting && navigationId === state.navigationId), focusRequestId: state.focusRequestId, onRetry: remote.refresh, onQueryChange: (query: string) => { diff --git a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx index cc3640fc2a166..40c84cc69fde6 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx @@ -1,11 +1,15 @@ -import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; +import { + FILE_PREVIEW_SCROLL_SCRIPT, + injectHtmlRenderBootstrap, + readFilePreviewScroll, +} from "@t3tools/shared/htmlRender"; import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; -import { HtmlRenderDocument } from "./BrowserDocumentFrame"; +import { BrowserDocumentFrame, HtmlRenderDocument } from "./BrowserDocumentFrame"; const sizeChanged = (height: number) => ({ jsonrpc: "2.0", @@ -219,3 +223,98 @@ it("keeps the first and last selected card rings inside the fitted renderer fram expect(bounds.scrollWidth).toBeLessThanOrEqual(bounds.viewportWidth); } }); + +describe("BrowserDocumentFrame", () => { + it("keeps a page on screen until its next revision has loaded", async () => { + using pages = (() => { + const urls = ["first", "second", "third"].map((name) => + URL.createObjectURL(new Blob([`

${name}

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