diff --git a/.github/actions/drop-checkout-credentials/action.yml b/.github/actions/drop-checkout-credentials/action.yml new file mode 100644 index 0000000000000..f9a60340e1fe5 --- /dev/null +++ b/.github/actions/drop-checkout-credentials/action.yml @@ -0,0 +1,38 @@ +name: Drop checkout credentials +description: Removes the token actions/checkout leaves behind, so later steps can run dependency and build scripts. + +# checkout keeps the token in a file under RUNNER_TEMP that .git/config includes, so +# both go. `persist-credentials: false` fails in this repo: its cleanup runs `git +# submodule foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules). +runs: + using: composite + steps: + - name: Drop checkout credentials + shell: bash + run: | + # Status 1 means no match; any other failure stops the step. + lookup() { + local status=0 + git -C "$dir" config --local "$@" || status=$? + if [ "$status" -gt 1 ]; then exit "$status"; fi + } + for dir in . .trusted; do + [ -e "$dir/.git" ] || continue + lookup --get-regexp '^includeif\..*\.path$' | while read -r key file; do + rm -f "$file" + git -C "$dir" config --local --unset-all "$key" + done + lookup --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do + git -C "$dir" config --local --unset-all "$key" + done + remaining="$(lookup --get-regexp 'extraheader|includeif')" + if [ -n "$remaining" ]; then + echo "::error::checkout credentials are still configured in $dir" + exit 1 + fi + done + rm -f "$RUNNER_TEMP"/git-credentials-*.config + if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then + echo "::error::a checkout credential file is still present" + exit 1 + fi diff --git a/.github/actions/eas-local-build/action.yml b/.github/actions/eas-local-build/action.yml new file mode 100644 index 0000000000000..847c8e0117492 --- /dev/null +++ b/.github/actions/eas-local-build/action.yml @@ -0,0 +1,188 @@ +name: EAS local build +description: Installs the toolchain and mobile dependencies, then runs `eas build --local` on this runner. + +inputs: + platform: + description: android or ios + required: true + profile: + description: eas.json build profile + required: true + environment: + description: EAS environment to pull, preview or production + required: true + expo-token: + description: Expo token for that environment + required: true + output: + description: Path the build artifact is written to + required: true + cache: + description: "false for untrusted code: no sticky disk and no EAS cache, so nothing it writes reaches trusted builds" + default: "true" + sourcemaps-r2: + description: R2 credentials for the eas-build-on-success source map upload; EAS secrets don't reach local builds + default: "" + +runs: + using: composite + steps: + - name: Prepare Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + env: + CACHE_NAME: ${{ inputs.environment == 'production' && 'store' || 'preview' }} + run: | + cache="$HOME/.cache/t3-android-$CACHE_NAME" + { + echo "GRADLE_USER_HOME=$cache/gradle" + echo "CCACHE_DIR=$cache/ccache" + echo "CCACHE_MAXSIZE=5G" + # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. + echo "CCACHE_COMPILERCHECK=%compiler% -v" + echo "pnpm_config_store_dir=$cache/pnpm-store" + # eas build --local copies the project here. A fixed path keeps + # ccache keys stable, and the same disk as the store lets pnpm hardlink. + echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" + echo "CCACHE_BASEDIR=$cache/eas-build" + # CMake (3.17+) reads these, and AGP passes Gradle's environment through. + echo "CMAKE_C_COMPILER_LAUNCHER=ccache" + echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" + } >> "$GITHUB_ENV" + + - name: Mount Android build cache + if: inputs.platform == 'android' && inputs.cache == 'true' + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 + with: + key: ${{ github.repository }}-android-${{ inputs.environment == 'production' && 'store' || 'preview' }}-build + path: ~/.cache/t3-android-${{ inputs.environment == 'production' && 'store' || 'preview' }} + + - name: Configure Gradle and ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" + rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" + # No daemon: nothing should hold the sticky disk open when it is committed. + printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" + sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources + sudo apt-get update -qq && sudo apt-get install -y -qq ccache + ccache --zero-stats + + # Matches the EAS build image in eas.json. + - name: Select Xcode 27.1 + if: inputs.platform == 'ios' + shell: bash + run: | + xcode=/Applications/Xcode_27.1.app + if [ ! -d "$xcode" ]; then + ls -d /Applications/Xcode*.app + echo "::error::Xcode 27.1 is not on this runner." + exit 1 + fi + sudo xcode-select -s "$xcode/Contents/Developer" + xcodebuild -version + echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" + + # EAS's credentials step fails to import the distribution certificate without it. + - name: Install Apple WWDR G3 intermediate + if: inputs.platform == 'ios' + shell: bash + run: | + curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer + sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true + security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep labl + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - name: Enable corepack + shell: bash + run: | + npm install --global corepack@latest + corepack enable + pnpm --version + + # EAS commands load app.config.ts, whose plugins must resolve. Keep install + # scripts: some download native assets that the build's fingerprint check hashes. + - name: Install mobile dependencies + shell: bash + run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... + + - name: Setup Java + if: inputs.platform == 'android' + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + with: + distribution: temurin + java-version: 17 + + - name: Setup EAS + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + with: + eas-version: latest + eas-cache: ${{ inputs.cache }} + token: ${{ inputs.expo-token }} + # npm, not pnpm: this only installs eas-cli into the action's own + # tool dir, and pnpm 11 hard-fails that install on dtrace-provider's + # ignored build script (no allowBuilds config outside the repo). + packager: npm + + - name: Build tools + if: inputs.platform == 'ios' + shell: bash + run: | + command -v pod || sudo gem install cocoapods --no-document + command -v fastlane || brew install fastlane + pod --version + fastlane --version | tail -1 + + # EAS commands skip dotenv, and the Android fingerprint hashes this file. + - name: Pull ${{ inputs.environment }} environment variables + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + ENVIRONMENT: ${{ inputs.environment }} + PLATFORM: ${{ inputs.platform }} + run: | + eas env:pull "$ENVIRONMENT" --non-interactive + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from "node:fs"; + import { parseEnv } from "node:util"; + const env = parseEnv(readFileSync(".env.local", "utf8")); + const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; + if (!googleServicesFile && process.env.PLATFORM === "android") { + throw new Error(`T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the ${process.env.ENVIRONMENT} environment`); + } + if (googleServicesFile) { + appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); + } + NODE + + - name: Build + shell: bash + working-directory: apps/mobile + env: + EXPO_TOKEN: ${{ inputs.expo-token }} + MOBILE_SOURCEMAPS_R2: ${{ inputs.sourcemaps-r2 }} + PLATFORM: ${{ inputs.platform }} + PROFILE: ${{ inputs.profile }} + OUTPUT: ${{ inputs.output }} + run: | + if [ "$PLATFORM" = "ios" ]; then + # A real path: /var -> /private/var symlinks break the expo-widgets bundle step. + export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" + fi + eas build --local --platform "$PLATFORM" --profile "$PROFILE" --non-interactive --output "$OUTPUT" + + - name: Report ccache + if: inputs.platform == 'android' && inputs.cache == 'true' + shell: bash + run: | + { + echo '```' + ccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml new file mode 100644 index 0000000000000..2086d004b295c --- /dev/null +++ b/.github/actions/record-build-tag/action.yml @@ -0,0 +1,57 @@ +name: Record build tag +description: Pushes the tag that tells later runs a build for this fingerprint exists. + +inputs: + tag: + description: Tag name, without refs/tags/ + required: true + message: + description: Annotated tag message; empty makes a lightweight tag + default: "" + replace: + description: "true replaces an existing tag; otherwise an existing tag counts as recorded" + default: "false" + token: + description: Token with contents write + required: true + +runs: + using: composite + steps: + - name: Record build tag + shell: bash + env: + TAG: ${{ inputs.tag }} + MESSAGE: ${{ inputs.message }} + REPLACE: ${{ inputs.replace }} + GH_TOKEN: ${{ inputs.token }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). + for attempt in 1 2 3; do + if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then + old="$(printf '%s\n' "$refs" | while read -r sha ref; do + if [ "$ref" = "refs/tags/$TAG" ]; then echo "$sha"; fi + done)" + if [ -n "$old" ] && [ "$REPLACE" != "true" ]; then + echo "$TAG exists." + exit 0 + fi + if [ -n "$MESSAGE" ]; then + git tag -f -a "$TAG" -m "$MESSAGE" + else + git tag -f "$TAG" + fi + # An empty lease means the tag must not exist yet. + if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then + exit 0 + fi + fi + if [ "$attempt" = 3 ]; then + echo "::error::Could not push $TAG." + exit 1 + fi + sleep $((attempt * 15)) + done diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 05b652842e8a2..9b531b1a55d64 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -90,40 +90,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. @@ -271,91 +251,37 @@ 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 - - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - run: | - npm install --global corepack@latest - corepack enable - pnpm --version + uses: ./.trusted/.github/actions/drop-checkout-credentials - - name: Install mobile dependencies - run: pnpm install --frozen-lockfile --filter=@t3tools/mobile... - - - name: Setup Java - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + # Cold: no sticky disk or EAS cache that trusted builds would restore. + - name: Build + uses: ./.trusted/.github/actions/eas-local-build with: - distribution: temurin - java-version: 17 - - - name: Setup EAS - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 - with: - eas-version: latest - eas-cache: false - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm - - - name: 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 + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk + 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" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then @@ -387,112 +313,37 @@ 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 - - - name: Select Xcode 27.1 - run: | - xcode=/Applications/Xcode_27.1.app - if [ ! -d "$xcode" ]; then - ls -d /Applications/Xcode*.app - echo "::error::Xcode 27.1 is not on this runner." - exit 1 - fi - sudo xcode-select -s "$xcode/Contents/Developer" - xcodebuild -version - echo "- Xcode: \`$(basename "$xcode")\`" >> "$GITHUB_STEP_SUMMARY" - - # EAS's credentials step fails to import the distribution certificate without it. - - name: Install Apple WWDR G3 intermediate - run: | - curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer - sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true - security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep -m1 labl - - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - name: Install mobile dependencies - run: pnpm install --frozen-lockfile --filter=@t3tools/mobile... + uses: ./.trusted/.github/actions/drop-checkout-credentials - - name: Setup EAS - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + # Cold: no sticky disk or EAS cache that trusted builds would restore. + - name: Build + uses: ./.trusted/.github/actions/eas-local-build with: - eas-version: latest - eas-cache: false - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm - - - name: Build tools - run: | - command -v pod || sudo gem install cocoapods --no-document - command -v fastlane || brew install fastlane - pod --version - fastlane --version | tail -1 - - - name: Pull preview environment variables - working-directory: apps/mobile - env: - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - run: | - eas env:pull preview --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (googleServicesFile) { - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - } - NODE + 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: | - export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" - eas build --local --platform ios --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.ipa" eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 4eb069e39eb7f..711c4a9ba567b 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -50,32 +50,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' @@ -194,32 +172,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' @@ -333,124 +289,27 @@ jobs: echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" fi - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # The steps below run dependency and build scripts; they get no token. - name: Drop checkout credentials - run: | - for dir in . .trusted; do - [ -e "$dir/.git" ] || continue - git -C "$dir" config --local --get-regexp '^includeif\..*\.path$' | while read -r key file; do - rm -f "$file" - git -C "$dir" config --local --unset-all "$key" - done - git -C "$dir" config --local --name-only --get-regexp '^http\..*\.extraheader$' | while read -r key; do - git -C "$dir" config --local --unset-all "$key" - done - if git -C "$dir" config --local --get-regexp 'extraheader|includeif'; then - echo "::error::checkout credentials are still configured in $dir" - exit 1 - fi - done - rm -f "$RUNNER_TEMP"/git-credentials-*.config - if ls "$RUNNER_TEMP"/git-credentials-*.config 2>/dev/null; then - echo "::error::a checkout credential file is still present" - exit 1 - fi + uses: ./.github/actions/drop-checkout-credentials - - name: Prepare build directories - if: steps.record.outputs.built != 'true' - run: | - cache="$HOME/.cache/t3-android-preview" - { - echo "GRADLE_USER_HOME=$cache/gradle" - echo "CCACHE_DIR=$cache/ccache" - echo "CCACHE_MAXSIZE=5G" - # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. - echo "CCACHE_COMPILERCHECK=%compiler% -v" - echo "pnpm_config_store_dir=$cache/pnpm-store" - # eas build --local copies the project here. A fixed path keeps - # ccache keys stable, and the same disk as the store lets pnpm hardlink. - echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" - echo "CCACHE_BASEDIR=$cache/eas-build" - echo "CMAKE_C_COMPILER_LAUNCHER=ccache" - echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" - } >> "$GITHUB_ENV" - - - name: Mount build cache + - name: Build if: steps.record.outputs.built != 'true' - uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 + uses: ./.github/actions/eas-local-build with: - key: ${{ github.repository }}-android-preview-build - path: ~/.cache/t3-android-preview - - - name: Configure Gradle and ccache - if: steps.record.outputs.built != 'true' - run: | - mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" - rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" - # No daemon: nothing should hold the sticky disk open when it is committed. - printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" - sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources - sudo apt-get update -qq && sudo apt-get install -y -qq ccache - ccache --zero-stats - - - name: Setup Node - if: steps.record.outputs.built != 'true' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - 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 - if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 - with: - eas-version: latest - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm - - - name: 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: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk # `eas upload` hosts the APK on EAS and returns the page testers install from. - 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" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then @@ -458,25 +317,16 @@ jobs: exit 1 fi echo "link=$link" >> "$GITHUB_OUTPUT" - { - echo "### Android preview client for \`$FINGERPRINT\`: $link" - echo '```' - ccache --show-stats - echo '```' - } >> "$GITHUB_STEP_SUMMARY" + echo "### Android 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 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" + 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 @@ -523,104 +373,27 @@ jobs: fi fi - # The steps below run the PR's dependency and build scripts; they get no token. - # checkout keeps it in a file under RUNNER_TEMP that .git/config includes, so both - # go. Asking checkout not to persist it fails here: that cleanup runs `git submodule - # foreach`, which stops at the vendored gitlinks under .repos (no .gitmodules entry). + # 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 - - - 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" + uses: ./.github/actions/drop-checkout-credentials - # EAS's credentials step fails to import the distribution certificate without it. - - name: Install Apple WWDR G3 intermediate + - name: Build if: steps.record.outputs.built != 'true' - run: | - curl -fsSL -o "$RUNNER_TEMP/AppleWWDRCAG3.cer" https://www.apple.com/certificateauthority/AppleWWDRCAG3.cer - sudo security add-certificates -k /Library/Keychains/System.keychain "$RUNNER_TEMP/AppleWWDRCAG3.cer" || true - security find-certificate -c "Apple Worldwide Developer Relations" /Library/Keychains/System.keychain | grep -m1 labl - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... - - - name: Setup EAS - if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + uses: ./.github/actions/eas-local-build with: - eas-version: latest - token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - packager: npm - - - name: Build tools - if: steps.record.outputs.built != 'true' - run: | - command -v pod || sudo gem install cocoapods --no-document - command -v fastlane || brew install fastlane - pod --version - fastlane --version | tail -1 - - - name: Pull preview environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: | - eas env:pull preview --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (googleServicesFile) { - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - } - NODE + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa # 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: | - export EAS_LOCAL_BUILD_WORKINGDIR="$RUNNER_TEMP/eas-build" - eas build --local --platform ios --profile preview:dev --non-interactive --output "$RUNNER_TEMP/t3code-preview.ipa" eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" if [ -z "$link" ]; then @@ -628,28 +401,30 @@ jobs: exit 1 fi echo "link=$link" >> "$GITHUB_OUTPUT" - { - echo "### iOS preview client for \`$FINGERPRINT\`: $link" - } >> "$GITHUB_STEP_SUMMARY" + echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" # The tag stores the install link and provisioning-profile expiry. - - name: Record build + - 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" - profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | awk '/^Payload\/[^/]+\.app\/embedded.mobileprovision$/')" - test -n "$profile_path" + 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")" - old_tag="$(git rev-parse -q --verify "refs/tags/$BUILD_TAG" || true)" - git tag -f -a "$BUILD_TAG" -m "$record" - # Only this step has the token; the checkout's copy was removed before the build. - git push --force-with-lease="refs/tags/$BUILD_TAG:$old_tag" "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "refs/tags/$BUILD_TAG" + 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 diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index f9eb460eea19e..2efa4edbbe880 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -7,10 +7,8 @@ name: Mobile EAS Production # runner, with corepack pinning pnpm 10.24 in eas.json, local == build. # # Every merge reconciles native fingerprints and publishes matching OTAs. -# Android store builds run here with `eas build --local` on Blacksmith (the -# android job). iOS builds run on EAS unless the MOBILE_IOS_LOCAL_BUILDS -# repository variable is `true`, which moves them to the ios job the same way. -# Local builds never appear in `eas build:list`, so each finished local build +# Store builds run here with `eas build --local` on Blacksmith (the android and +# ios jobs). Local builds never appear in `eas build:list`, so each finished build # pushes a mobile-android-build// or # mobile-ios-build/// tag that the reconcile reads. # iOS prereleases use the testflight profile (3.0.0); App Store binaries use @@ -256,17 +254,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 }} @@ -354,7 +344,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))" @@ -377,19 +366,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 @@ -444,23 +430,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" @@ -479,9 +456,9 @@ jobs: fi done - # `eas build --local` on Blacksmith, ARM-only, without release lint (see the - # production profile in eas.json), with Gradle, ccache, and pnpm state on a - # sticky disk. Its own concurrency group keeps later OTAs from waiting on it. + # ARM-only, without release lint (see the production profile in eas.json), + # with Gradle, ccache, and pnpm state on a sticky disk. Its own concurrency + # group keeps later OTAs from waiting on it. android: name: Android store build needs: production @@ -506,20 +483,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 @@ -532,111 +498,22 @@ jobs: echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" fi - - name: Prepare build directories - if: steps.record.outputs.built != 'true' - run: | - cache="$HOME/.cache/t3-android-store" - { - echo "GRADLE_USER_HOME=$cache/gradle" - echo "CCACHE_DIR=$cache/ccache" - echo "CCACHE_MAXSIZE=5G" - # Gradle installs the NDK fresh each run, so key on the compiler's version, not its mtime. - echo "CCACHE_COMPILERCHECK=%compiler% -v" - echo "pnpm_config_store_dir=$cache/pnpm-store" - # eas build --local copies the project here. A fixed path keeps - # ccache keys stable, and the same disk as the store lets pnpm hardlink. - echo "EAS_LOCAL_BUILD_WORKINGDIR=$cache/eas-build" - echo "CCACHE_BASEDIR=$cache/eas-build" - # CMake (3.17+) reads these, and AGP passes Gradle's environment through. - echo "CMAKE_C_COMPILER_LAUNCHER=ccache" - echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" - } >> "$GITHUB_ENV" - - - name: Mount build cache - if: steps.record.outputs.built != 'true' - uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 - with: - key: ${{ github.repository }}-android-store-build - path: ~/.cache/t3-android-store - - - name: Configure Gradle and ccache - if: steps.record.outputs.built != 'true' - run: | - mkdir -p "$GRADLE_USER_HOME" "$CCACHE_DIR" - rm -rf "$EAS_LOCAL_BUILD_WORKINGDIR" - # No daemon: nothing should hold the sticky disk open when it is committed. - printf 'org.gradle.caching=true\norg.gradle.daemon=false\n' > "$GRADLE_USER_HOME/gradle.properties" - sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources - sudo apt-get update -qq && sudo apt-get install -y -qq ccache - ccache --zero-stats - - - name: Setup Node - if: steps.record.outputs.built != 'true' - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - name: Enable corepack - if: steps.record.outputs.built != 'true' - run: | - npm install --global corepack@latest - corepack enable - pnpm --version - - # EAS commands load app.config.ts, whose plugins must resolve. Keep install - # scripts: some download native assets that the build's fingerprint check hashes. - - name: Install mobile dependencies - if: steps.record.outputs.built != 'true' - run: pnpm install --frozen-lockfile --prefer-offline --filter=@t3tools/mobile... - - - name: Setup Java - if: steps.record.outputs.built != 'true' - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 17 - - - name: Setup EAS + - name: Build if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 + uses: ./.github/actions/eas-local-build with: - eas-version: latest - token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - packager: npm - - - name: Pull production environment variables - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: | - eas env:pull production --non-interactive - node --input-type=module <<'NODE' - import { appendFileSync, readFileSync } from "node:fs"; - import { parseEnv } from "node:util"; - const env = parseEnv(readFileSync(".env.local", "utf8")); - const googleServicesFile = env.T3CODE_ANDROID_GOOGLE_SERVICES_FILE; - if (!googleServicesFile) { - throw new Error("T3CODE_ANDROID_GOOGLE_SERVICES_FILE is missing from the production environment"); - } - appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); - NODE - - - name: Build + platform: android + profile: production + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.aab + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - name: Check ABIs if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - env: - # EAS secret variables don't reach local builds; the eas-build-on-success - # hook needs these to upload the bundle's source map. - MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} run: | - eas build --local --platform android --profile production --non-interactive --output "$RUNNER_TEMP/t3code.aab" abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" - { - echo "### Android $BUILD_TAG" - echo "- ABIs: \`$abis\`" - echo '```' - ccache --show-stats - echo '```' - } >> "$GITHUB_STEP_SUMMARY" + echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then echo "::error::Expected only ARM native libraries in the AAB, found $abis" exit 1 @@ -661,30 +538,16 @@ jobs: # pushed, the next merge rebuilds with a new build number; nothing is lost. - name: Record build if: steps.record.outputs.built != 'true' - env: - GH_TOKEN: ${{ github.token }} + uses: ./.github/actions/record-build-tag + with: + tag: ${{ env.BUILD_TAG }} + token: ${{ github.token }} + + - name: Summarize + if: steps.record.outputs.built != 'true' run: | - sha="$(git rev-parse HEAD)" - # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). - for attempt in 1 2 3; do - if gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$BUILD_TAG" >/dev/null 2>&1; then - echo "$BUILD_TAG exists." - break - fi - if gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$BUILD_TAG" -f sha="$sha" >/dev/null; then - break - fi - if [ "$attempt" = 3 ]; then - echo "::error::Submitted, but could not create $BUILD_TAG; the next merge will rebuild." - exit 1 - fi - sleep $((attempt * 15)) - done echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" - # Off unless the MOBILE_IOS_LOCAL_BUILDS repository variable is `true`; the - # production job only sets ios_build then. Xcode 27.1 matches the EAS build - # image in eas.json. # No sticky disk: it mounts ext4 and only works on Linux runners. ios: name: iOS store build @@ -711,20 +574,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 @@ -737,78 +589,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' @@ -819,23 +609,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/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index aca3b4fc7fe66..9cc3a187e83f3 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -54,6 +55,7 @@ import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts"; import * as BrowserImport from "../preview/BrowserImport/BrowserImport.ts"; import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfiguration.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts"; import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts"; import * as DesktopIpc from "../ipc/DesktopIpc.ts"; @@ -72,6 +74,179 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as PreviewManager from "../preview/Manager.ts"; +interface StubbedDesktop { + readonly localEnvironmentEnabled: boolean; + readonly environment: Partial; + readonly fileSystem: Layer.Layer; + readonly record: (event: string) => Effect.Effect; + readonly windowStarted: Deferred.Deferred; + readonly registerLinuxUrlHandler: Effect.Effect; + readonly backends?: ReadonlyArray<{ readonly stop: () => Effect.Effect }>; + readonly flushRendererHistory?: Effect.Effect; + readonly tokenRequested?: Deferred.Deferred; +} + +const runStubbedDesktop = (stub: StubbedDesktop) => + Effect.gen(function* () { + const quitting = yield* Ref.make(false); + const runApp = DesktopApp.program + .pipe( + Effect.provide(NodeCrypto.layer), + Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { + resolveUserDataPath: Effect.succeed("/isolated/userdata"), + configure: stub.record("identity"), + } as DesktopAppIdentity.DesktopAppIdentity["Service"]), + Effect.provideService(ElectronApp.ElectronApp, { + setPath: () => Effect.void, + whenReady: stub.record("ready"), + } as unknown as ElectronApp.ElectronApp["Service"]), + Effect.provideService(ElectronDialog.ElectronDialog, { + showErrorBox: () => Effect.die("unexpected fatal startup error"), + } as unknown as ElectronDialog.ElectronDialog["Service"]), + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + platform: "linux", + isDevelopment: false, + isPackaged: true, + stateDir: "/isolated/userdata", + configuredBackendPort: Option.some(3773), + defaultDesktopSettings: { serverExposureMode: "local-only" }, + ...stub.environment, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { + linux: null, + linuxPasswordStoreCommandLine: "basic", + }), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), + updates: Stream.empty, + }), + Effect.provideService(DesktopAppSettings.DesktopAppSettings, { + load: Effect.void, + get: Effect.succeed({ + localEnvironmentEnabled: stub.localEnvironmentEnabled, + serverExposureMode: "local-only", + }), + } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), + Effect.provideService(DesktopLifecycle.DesktopLifecycle, { + register: Effect.void, + relaunch: () => Effect.void, + }), + Effect.provideService(DesktopClerk.DesktopClerk, { + configure: Effect.void, + } as DesktopClerk.DesktopClerk["Service"]), + Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { + selectedStorageBackend: Effect.succeedNone, + } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), + Effect.provideService(PreviewPasskeys.PreviewPasskeys, { + configure: Effect.void, + } as PreviewPasskeys.PreviewPasskeys["Service"]), + Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { + configure: stub.record("menu"), + }), + Effect.provideService(DesktopUpdates.DesktopUpdates, { + configure: Effect.void, + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { + register: stub.registerLinuxUrlHandler, + }), + ) + .pipe( + Effect.provideService(ElectronProtocol.ElectronProtocol, { + registerDesktopProtocol: () => Effect.void, + } as unknown as ElectronProtocol.ElectronProtocol["Service"]), + Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { + load: () => Effect.void, + } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), + Effect.provideService(DesktopSnapShot.DesktopSnapShot, { + initialize: Effect.void, + } as DesktopSnapShot.DesktopSnapShot["Service"]), + Effect.provideService(DesktopState.DesktopState, { + quitting, + } as DesktopState.DesktopState["Service"]), + Effect.provideService(DesktopWindow.DesktopWindow, { + ensureMain: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + createMainIfBackendReady: stub + .record("window") + .pipe(Effect.andThen(Deferred.succeed(stub.windowStarted, undefined))), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + Effect.provideService(DesktopBackendPool.DesktopBackendPool, { + primary: Effect.succeed({ + start: stub.record("backend"), + currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), + }), + list: Effect.succeed(stub.backends ?? []), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), + Effect.provideService(DesktopServerExposure.DesktopServerExposure, { + configureFromSettings: () => Effect.succeed({ mode: "local-only" }), + backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), + } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), + Effect.provideService(DesktopWslBackend.DesktopWslBackend, { + reconcile: Effect.void, + } as DesktopWslBackend.DesktopWslBackend["Service"]), + Effect.provideService(DesktopAppActivation.DesktopAppActivation, { + start: Effect.void, + } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), + Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { + shutdown: stub.flushRendererHistory ?? Effect.void, + } as DesktopRendererHistory.DesktopRendererHistory["Service"]), + ); + return yield* runApp.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), + Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), + Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), + Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), + Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), + Layer.mock(DesktopIpc.DesktopIpc, {}), + Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { + getBearerToken: stub + .record("token") + .pipe( + Effect.andThen( + stub.tokenRequested + ? Deferred.succeed(stub.tokenRequested, undefined) + : Effect.void, + ), + Effect.as("token"), + ), + }), + Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), + Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), + Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), + Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), + Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), + Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), + Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), + Layer.mock(ElectronMenu.ElectronMenu, {}), + Layer.mock(ElectronShell.ElectronShell, {}), + Layer.mock(ElectronTheme.ElectronTheme, {}), + Layer.mock(ElectronWindow.ElectronWindow, {}), + Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(PreviewManager.PreviewManager, { + isBrowserPartition: () => { + throw new Error("unexpected browser partition lookup"); + }, + }), + stub.fileSystem, + Layer.mock(NetService.NetService, {}), + Path.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected HTTP request")), + ), + ), + ), + Effect.forkScoped, + ); + }); + it.effect.each([false, true])( "stops backends together before flushing history and cancels Linux registration, stop defect=%s", (stopDefect) => @@ -85,178 +260,42 @@ it.effect.each([false, true])( const releaseStops = yield* Deferred.make(); const historyStarted = yield* Deferred.make(); const releaseHistory = yield* Deferred.make(); - const quitting = yield* Ref.make(false); const tokenRequested = yield* Deferred.make(); const events: string[] = []; - const record = (event: string) => - Effect.sync(() => { - events.push(event); - }); - const runApp = DesktopApp.program - .pipe( - Effect.provide(NodeCrypto.layer), - Effect.provideService(DesktopAppIdentity.DesktopAppIdentity, { - resolveUserDataPath: Effect.succeed("/isolated/userdata"), - configure: record("identity"), - } as DesktopAppIdentity.DesktopAppIdentity["Service"]), - Effect.provideService(ElectronApp.ElectronApp, { - setPath: () => Effect.void, - whenReady: record("ready"), - } as unknown as ElectronApp.ElectronApp["Service"]), - Effect.provideService(ElectronDialog.ElectronDialog, { - showErrorBox: () => Effect.die("unexpected fatal startup error"), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - Effect.provideService(DesktopEnvironment.DesktopEnvironment, { - platform: "linux", - isDevelopment: false, - isPackaged: true, - stateDir: "/isolated/userdata", - configuredBackendPort: Option.some(3773), - defaultDesktopSettings: { serverExposureMode: "local-only" }, - } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), - Effect.provideService(DesktopPreReadyPlatform.DesktopPreReadyElectronOptions, { - linux: null, - linuxPasswordStoreCommandLine: "basic", - }), - Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { - installIntoProcess: Effect.succeed(true), - awaitDiscovery: Effect.succeed(true), - awaitUserShellDiscovery: Effect.succeed(true), - updates: Stream.empty, + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: true, + environment: {}, + fileSystem: FileSystem.layerNoop({}), + record: (event) => + Effect.sync(() => { + events.push(event); }), - Effect.provideService(DesktopAppSettings.DesktopAppSettings, { - load: Effect.void, - get: Effect.succeed({ - localEnvironmentEnabled: true, - serverExposureMode: "local-only", - }), - } as unknown as DesktopAppSettings.DesktopAppSettings["Service"]), - Effect.provideService(DesktopLifecycle.DesktopLifecycle, { - register: Effect.void, - relaunch: () => Effect.void, - }), - Effect.provideService(DesktopClerk.DesktopClerk, { - configure: Effect.void, - } as DesktopClerk.DesktopClerk["Service"]), - Effect.provideService(ElectronSafeStorage.ElectronSafeStorage, { - selectedStorageBackend: Effect.succeedNone, - } as unknown as ElectronSafeStorage.ElectronSafeStorage["Service"]), - Effect.provideService(PreviewPasskeys.PreviewPasskeys, { - configure: Effect.void, - } as PreviewPasskeys.PreviewPasskeys["Service"]), - Effect.provideService(DesktopApplicationMenu.DesktopApplicationMenu, { - configure: record("menu"), - }), - Effect.provideService(DesktopUpdates.DesktopUpdates, { - configure: Effect.void, - } as unknown as DesktopUpdates.DesktopUpdates["Service"]), - Effect.provideService(DesktopLinuxUrlHandler.DesktopLinuxUrlHandler, { - register: Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), - ), - }), - ) - .pipe( - Effect.provideService(ElectronProtocol.ElectronProtocol, { - registerDesktopProtocol: () => Effect.void, - } as unknown as ElectronProtocol.ElectronProtocol["Service"]), - Effect.provideService(DesktopLegacyLocalStorage.DesktopLegacyLocalStorage, { - load: () => Effect.void, - } as unknown as DesktopLegacyLocalStorage.DesktopLegacyLocalStorage["Service"]), - Effect.provideService(DesktopSnapShot.DesktopSnapShot, { - initialize: Effect.void, - } as DesktopSnapShot.DesktopSnapShot["Service"]), - Effect.provideService(DesktopState.DesktopState, { - quitting, - } as DesktopState.DesktopState["Service"]), - Effect.provideService(DesktopWindow.DesktopWindow, { - ensureMain: record("window").pipe( - Effect.andThen(Deferred.succeed(windowStarted, undefined)), - ), - } as unknown as DesktopWindow.DesktopWindow["Service"]), - Effect.provideService(DesktopBackendPool.DesktopBackendPool, { - primary: Effect.succeed({ - start: record("backend"), - currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), - }), - list: Effect.succeed([ - { - stop: () => - Deferred.succeed(firstStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), - ), - }, - { - stop: () => - Deferred.succeed(secondStopStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseStops)), - ), - }, - ]), - } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), - Effect.provideService(DesktopServerExposure.DesktopServerExposure, { - configureFromSettings: () => Effect.succeed({ mode: "local-only" }), - backendConfig: Effect.succeed({ httpBaseUrl: new URL("http://127.0.0.1:3773") }), - } as unknown as DesktopServerExposure.DesktopServerExposure["Service"]), - Effect.provideService(DesktopWslBackend.DesktopWslBackend, { - reconcile: Effect.void, - } as DesktopWslBackend.DesktopWslBackend["Service"]), - Effect.provideService(DesktopAppActivation.DesktopAppActivation, { - start: Effect.void, - } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), - Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { - shutdown: Deferred.succeed(historyStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseHistory)), - Effect.asVoid, - ), - } as DesktopRendererHistory.DesktopRendererHistory["Service"]), - ); - const app = yield* runApp.pipe( - Effect.provide( - Layer.mergeAll( - Layer.mock(BrowserImport.BrowserImport, {}), - Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), - Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), - Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), - Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), - Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}), - Layer.mock(DesktopIpc.DesktopIpc, {}), - Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, { - getBearerToken: record("token").pipe( - Effect.andThen(Deferred.succeed(tokenRequested, undefined)), - Effect.as("token"), + windowStarted, + tokenRequested, + registerLinuxUrlHandler: Deferred.succeed(registrationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseRegistration)), + Effect.ensuring(Deferred.succeed(registrationStopped, undefined)), + ), + backends: [ + { + stop: () => + Deferred.succeed(firstStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), ), - }), - Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}), - Layer.succeed(DesktopPrimaryPaste.DesktopPrimaryPaste, { enabled: true }), - Layer.mock(DesktopSshEnvironment.DesktopSshEnvironment, {}), - Layer.mock(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, {}), - Layer.mock(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {}), - Layer.mock(DesktopWebLinks.DesktopWebLinks, {}), - Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {}), - Layer.mock(ElectronMenu.ElectronMenu, {}), - Layer.mock(ElectronShell.ElectronShell, {}), - Layer.mock(ElectronTheme.ElectronTheme, {}), - Layer.mock(ElectronWindow.ElectronWindow, {}), - Layer.mock(MacPermissions.MacPermissions, {}), - Layer.mock(PreviewManager.PreviewManager, { - isBrowserPartition: () => { - throw new Error("unexpected browser partition lookup"); - }, - }), - FileSystem.layerNoop({}), - Layer.mock(NetService.NetService, {}), - Path.layer, - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), - ), - ), + }, + { + stop: () => + Deferred.succeed(secondStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + ), + }, + ], + flushRendererHistory: Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseHistory)), + Effect.asVoid, ), - Effect.forkScoped, - ); + }); yield* Deferred.await(registrationStarted); yield* Deferred.await(windowStarted); yield* Deferred.await(tokenRequested); @@ -283,3 +322,53 @@ it.effect.each([false, true])( assert.isTrue(yield* Deferred.isDone(registrationStopped)); }).pipe(Effect.provide(DesktopShutdown.layer)), ); + +it.effect("points a stale t3 launcher at the updated AppImage with Local environment off", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-desktop-app-" }); + const launcher = DesktopCliShim.launcherPath({ + path, + baseDir, + platform: "linux", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const removedAppImage = path.join(baseDir, "T3-Code-0.1.6-x86_64.AppImage"); + const updatedAppImage = path.join(baseDir, "T3-Code-0.1.7-x86_64.AppImage"); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString( + launcher, + DesktopCliShim.renderCliShim({ + target: { kind: "appimage", appImage: removedAppImage, executableName: "t3code" }, + shimPath: launcher, + t3Home: baseDir, + }), + ); + yield* fs.writeFileString(updatedAppImage, "", { mode: 0o755 }); + const windowStarted = yield* Deferred.make(); + + const app = yield* runStubbedDesktop({ + localEnvironmentEnabled: false, + environment: { + path, + baseDir, + serverRoot: path.join(baseDir, "resources", "app.asar"), + appImagePath: Option.some(updatedAppImage), + }, + fileSystem: Layer.succeed(FileSystem.FileSystem, fs), + record: () => Effect.void, + windowStarted, + registerLinuxUrlHandler: Effect.void, + }); + yield* Deferred.await(windowStarted); + yield* (yield* DesktopShutdown.DesktopShutdown).request; + yield* Fiber.join(app); + + const content = yield* fs.readFileString(launcher); + assert.include( + content, + `app='${updatedAppImage}'`, + "startup left the t3 launcher pointing at the removed AppImage", + ); + }).pipe(Effect.provide(Layer.mergeAll(DesktopShutdown.layer, NodeServices.layer))), +); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index f69bf965d0058..56fe979cf8c67 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -15,6 +15,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopCliCommand from "./DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; @@ -301,6 +302,8 @@ const bootstrap = Effect.fn("desktop.bootstrap")(function* (backendStarted: bool ); if (!settings.localEnvironmentEnabled) { + // The backend config refreshes the launcher when the local environment runs; an update may move the app. + yield* DesktopCliShim.install; if (!(yield* Ref.get(state.quitting))) { yield* desktopWindow.createMainIfBackendReady; } diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index ab57d5db32372..565a50f193e0f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -29,6 +29,7 @@ const layerShellEnvironment = (prepared = true) => installIntoProcess: Effect.succeed(prepared), awaitDiscovery: Effect.succeed(prepared), awaitUserShellDiscovery: Effect.succeed(prepared), + discoveryFinished: Effect.succeed(true), updates: Stream.empty, }); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 60b72deb293a5..fe65edd0ee1e9 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -1,3 +1,4 @@ +import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; @@ -110,6 +111,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); + yield* ipc.handle(startFileDrag); yield* ipc.handle(restartAudioService); yield* ipc.handle(getClientSettings); yield* ipc.handle(setClientSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 9e5c7296a3a03..d8652bd199713 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -142,3 +142,5 @@ export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-stor export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage"; export const RESTART_AUDIO_SERVICE_CHANNEL = "desktop:restart-audio-service"; + +export const START_FILE_DRAG_CHANNEL = "desktop:start-file-drag"; diff --git a/apps/desktop/src/ipc/methods/fileDrag.test.ts b/apps/desktop/src/ipc/methods/fileDrag.test.ts new file mode 100644 index 0000000000000..04b75c9be98a1 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.test.ts @@ -0,0 +1,51 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import { vi } from "vite-plus/test"; + +const { startDrag, getFileIcon } = vi.hoisted(() => ({ + startDrag: vi.fn(), + getFileIcon: vi.fn(async () => "file-icon"), +})); +vi.mock("electron", () => ({ app: { getFileIcon } })); + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import { startFileDrag } from "./fileDrag.ts"; + +it.effect("only drags existing absolute paths from the Mac host environment and app window", () => + Effect.gen(function* () { + startDrag.mockClear(); + getFileIcon.mockClear(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const filePath = path.join(stateDir, "file with spaces.txt"); + yield* fs.writeFileString(filePath, "file"); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), "host\n"); + const run = (environmentId: string, target: string, platform = "darwin", sender = 1) => + startFileDrag.handler({ environmentId, path: target }, { sender: { id: sender } }).pipe( + Effect.provideService(DesktopEnvironment.DesktopEnvironment, { + path, + stateDir, + platform, + } as DesktopEnvironment.DesktopEnvironment["Service"]), + Effect.provideService(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents: { id: 1, startDrag } }), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ); + assert.isFalse(yield* run("remote", filePath)); + assert.isFalse(yield* run("host", "relative.txt")); + assert.isFalse(yield* run("host", `${filePath}:12`)); + assert.isFalse(yield* run("host", filePath, "linux")); + assert.isFalse(yield* run("host", filePath, "darwin", 2)); + assert.strictEqual(startDrag.mock.calls.length, 0); + assert.isTrue(yield* run("host", filePath)); + assert.deepEqual(startDrag.mock.calls, [[{ file: filePath, icon: "file-icon" }]]); + yield* fs.remove(path.join(stateDir, "environment-id")); + assert.isFalse(yield* run("host", filePath)); + assert.strictEqual(startDrag.mock.calls.length, 1); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/desktop/src/ipc/methods/fileDrag.ts b/apps/desktop/src/ipc/methods/fileDrag.ts new file mode 100644 index 0000000000000..9701dfafcda32 --- /dev/null +++ b/apps/desktop/src/ipc/methods/fileDrag.ts @@ -0,0 +1,36 @@ +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Electron from "electron"; + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronWindow from "../../electron/ElectronWindow.ts"; +import * as IpcChannels from "../channels.ts"; +import { makeIpcMethod } from "../DesktopIpc.ts"; +import { getHostEnvironmentId } from "./localEnvironment.ts"; + +export const startFileDrag = makeIpcMethod({ + channel: IpcChannels.START_FILE_DRAG_CHANNEL, + payload: Schema.Struct({ environmentId: Schema.String, path: Schema.String }), + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.fileDrag.start")(function* (input, event) { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + if (environment.platform !== "darwin" || !environment.path.isAbsolute(input.path)) return false; + const hostEnvironmentId = yield* getHostEnvironmentId.handler(undefined); + if (hostEnvironmentId === null || input.environmentId !== hostEnvironmentId) return false; + const window = yield* (yield* ElectronWindow.ElectronWindow).main; + if (Option.isNone(window) || event?.sender.id !== window.value.webContents.id) return false; + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(input.path))) return false; + return yield* Effect.promise(async () => { + try { + const icon = await Electron.app.getFileIcon(input.path, { size: "normal" }); + window.value.webContents.startDrag({ file: input.path, icon }); + return true; + } catch { + return false; + } + }); + }), +}); diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index de202529c4113..b256025eff844 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -10,6 +10,7 @@ import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -26,6 +27,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; @@ -235,6 +237,7 @@ describe("installRelayTelemetryEnabled", () => { const relayTelemetryEnabled = ( env: NodeJS.ProcessEnv, policy?: Parameters[0], + loginShellEnv: NodeJS.ProcessEnv = {}, ) => Effect.gen(function* () { const listeners = new Map(); @@ -244,21 +247,47 @@ describe("installRelayTelemetryEnabled", () => { removeAllListeners: (channel) => void listeners.delete(channel), on: (channel, listener) => void listeners.set(channel, listener), }; + let discoveryFinished = false; + const ask = () => { + const event = { returnValue: undefined as unknown }; + listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); + return event.returnValue; + }; yield* installRelayTelemetryEnabled().pipe( Effect.provideService(HostProcess.Environment, env), + Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.sync(() => discoveryFinished), + updates: Stream.empty, + }), Effect.provide( Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)), ), ); - const event = { returnValue: undefined as unknown }; - listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never); - return event.returnValue; + const beforeDiscovery = ask(); + // The login shell's values land in the process env after startup has installed handlers. + Object.assign(env, loginShellEnv); + discoveryFinished = true; + return { beforeDiscovery, afterDiscovery: ask() }; }).pipe(Effect.scoped); it.effect("reads the desktop host opt-out before returning the renderer policy", () => Effect.gen(function* () { - assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" })); - assert.isTrue(yield* relayTelemetryEnabled({})); + assert.deepEqual(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }), { + beforeDiscovery: false, + afterDiscovery: false, + }); + // Undecided until the login shell is read, so the renderer asks again instead of opting out. + assert.deepEqual(yield* relayTelemetryEnabled({}), { + beforeDiscovery: null, + afterDiscovery: true, + }); + assert.deepEqual( + yield* relayTelemetryEnabled({}, undefined, { T3CODE_TELEMETRY_ENABLED: "false" }), + { beforeDiscovery: null, afterDiscovery: false }, + ); }), ); @@ -269,14 +298,14 @@ describe("installRelayTelemetryEnabled", () => { organization: "Example Corp", limits, }); - assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false }))); - assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false }))); + const after = function* (...args: Parameters) { + return (yield* relayTelemetryEnabled(...args)).afterDiscovery; + }; + assert.isFalse(yield* after({}, policy({ telemetry: false }))); + assert.isTrue(yield* after({}, policy({ webhookTasks: false }))); // A policy that cannot be read fails closed. assert.isFalse( - yield* relayTelemetryEnabled( - {}, - new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }), - ), + yield* after({}, new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })), ); }), ); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 38887ec71d906..2545cb9dc5390 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -34,6 +34,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; +import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; import * as ElectronApp from "../../electron/ElectronApp.ts"; @@ -82,22 +83,28 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ /** * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read, - * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. + * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. Until the login + * shell's environment (which may opt out) is known, answer null so the renderer asks again. */ export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")( function* () { const ipc = yield* DesktopIpc.DesktopIpc; - const enabled = - isRelayTracingEnabled(yield* HostProcess.Environment) && - (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( - Effect.map((found) => found?.document.limits?.telemetry !== false), - Effect.orElseSucceed(() => false), - )); + const env = yield* HostProcess.Environment; + const policyAllows = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( + Effect.map((found) => found?.document.limits?.telemetry !== false), + Effect.orElseSucceed(() => false), + ); + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; yield* ipc.handleSync( DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL, - result: Schema.Boolean, - handler: () => Effect.succeed(enabled), + result: Schema.NullOr(Schema.Boolean), + handler: () => + shellEnvironment.discoveryFinished.pipe( + Effect.map((known) => + !policyAllows || !isRelayTracingEnabled(env) ? false : known ? true : null, + ), + ), }), ); }, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ba9c17aae2695..b4b15f6a7a4eb 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -111,8 +111,10 @@ contextBridge.exposeInMainWorld("desktopBridge", { } return result as ReturnType; }, - getRelayTelemetryEnabled: () => - ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true, + getRelayTelemetryEnabled: () => { + const enabled = ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL); + return enabled === null ? null : enabled === true; + }, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), @@ -255,6 +257,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL, url), cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), + startFileDrag: (input) => ipcRenderer.invoke(IpcChannels.START_FILE_DRAG_CHANNEL, input), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), checkSystemPermission: (pane: string) => diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 7808682dfd82b..f082020a5dec1 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -355,6 +355,7 @@ describe("DesktopShellEnvironment", () => { NODE_EXTRA_CA_CERTS: "/cached/ca.pem", SSL_CERT_FILE: "/cached/cert.pem", SSL_CERT_DIR: "/cached/certs", + T3CODE_TELEMETRY_ENABLED: "false", SSH_AUTH_SOCK: "/stale.sock", NODE_OPTIONS: "--bad", }, @@ -394,6 +395,7 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); assert.equal(env.SSL_CERT_FILE, ""); assert.equal(env.SSL_CERT_DIR, "/cached/certs"); + assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false"); assert.equal(env.SSH_AUTH_SOCK, "/current.sock"); assert.isUndefined(env.NODE_OPTIONS); assert.equal(yield* fs.readFileString(cachePath), contents); @@ -711,6 +713,8 @@ describe("DesktopShellEnvironment", () => { Effect.gen(function* () { assert.isTrue(yield* service.awaitDiscovery); assert.equal(env.PATH, "/usr/bin"); + // The user's shell may still opt out of telemetry, so discovery has not settled. + assert.isFalse(yield* service.discoveryFinished); // The Linux probe checks the D-Bus socket on the real filesystem, which the clock does not await. const published = yield* service.updates.pipe( Stream.filter((snapshot) => snapshot.environment.PATH === "/fish/bin:/usr/bin"), diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index f2a92069f066b..1bd3386a1a2e6 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -93,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") {} @@ -651,6 +653,7 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", + "T3CODE_TELEMETRY_ENABLED", ] as const; /** @public */ @@ -672,6 +675,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, @@ -741,6 +745,7 @@ export const make = Effect.gen(function* () { ), ), ), + Effect.onExit(() => Deferred.succeed(settledDiscovery, undefined)), ); const installIntoProcess = yield* Effect.cached( Effect.gen(function* () { @@ -796,6 +801,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/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index e2bfabe32762c..3b0582e8131b7 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -93,6 +93,7 @@ describe("DesktopTelemetryPublisher", () => { installIntoProcess: Effect.succeed(true), awaitDiscovery: Effect.succeed(true), awaitUserShellDiscovery: Effect.succeed(true), + discoveryFinished: Effect.succeed(true), updates: Stream.make({ version: 1, type: "shellEnvironment", diff --git a/apps/mobile/src/components/ui/AppSymbol.android.tsx b/apps/mobile/src/components/ui/AppSymbol.android.tsx index 4a5a16298b956..a98e9d4ba8ea1 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"; @@ -189,6 +190,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, 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..c76c79896d103 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(); }; diff --git a/apps/mobile/src/features/pull-requests/PullRequestLabelsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestLabelsScreen.tsx index 24fd3533ce358..95cf64d02e848 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestLabelsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestLabelsScreen.tsx @@ -1,15 +1,23 @@ import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { LegendList } from "@legendapp/list/react-native"; import { useAtomValue } from "@effect/atom-react"; -import type { StaticScreenProps } from "@react-navigation/native"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + emptySelection, + isSelected, + changeBatches, + selectionChanges, + toggleSelection, +} from "@t3tools/client-runtime/pull-request-selection"; import type { PullRequestLabelCandidate } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; -import { useRef, useState } from "react"; +import { useEffect, useState } 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 * as Dialog from "../../components/ui/Dialog"; import { EmptyState } from "../../components/ui/EmptyState"; import { SelectionRow } from "../../components/ui/SelectionRow"; import { composerPullRequests } from "../../state/pull-requests"; @@ -22,6 +30,7 @@ import { usePullRequestConnected } from "./usePullRequestConnected"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; export function PullRequestLabelsScreen({ route }: StaticScreenProps) { + const navigation = useNavigation(); const target = pullRequestTarget(route.params); const pr = useEnvironmentQuery(composerPullRequests.detail(target)).data; const canWrite = useAtomValue( @@ -47,30 +56,46 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps(); - const [error, setError] = useState(null); - const inFlight = useRef(false); + const [draft, setDraft] = useState(emptySelection); const needle = query.trim().toLowerCase(); // Host order, not applied-first: re-sorting on toggle would move the row out from under a tap. const candidates = (result.data?.candidates ?? []).filter((candidate) => `${candidate.name} ${candidate.description ?? ""}`.toLowerCase().includes(needle), ); - const toggle = async (candidate: PullRequestLabelCandidate) => { - if (!allowed || inFlight.current) return; - inFlight.current = true; - setPending({ name: candidate.name, applied: !candidate.isApplied }); - setError(null); - const response = await setLabels({ - ...target, - input: { ...target.input, labels: [candidate.name], applied: !candidate.isApplied }, - }); - inFlight.current = false; - setPending(undefined); - if (AsyncResult.isFailure(response)) { - const cause = squashAtomCommandFailure(response); - setError(cause instanceof Error ? cause.message : "Couldn't update this label. Try again."); - } - }; + const latest = result.data?.candidates; + // 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", () => { + const { add, remove } = selectionChanges( + draft, + (name, label) => + latest?.find((entry) => entry.name === name)?.isApplied ?? label.isApplied, + ); + const sendBatch = async ( + labels: ReadonlyArray, + applied: boolean, + ) => { + const names = labels.map((label) => label.name); + const response = await setLabels({ + ...target, + input: { ...target.input, labels: names, applied }, + }); + if (!AsyncResult.isFailure(response)) return; + const cause = squashAtomCommandFailure(response); + Dialog.alert( + applied ? `Couldn't add ${names.join(", ")}` : `Couldn't remove ${names.join(", ")}`, + cause instanceof Error ? cause.message : "The provider refused the change.", + ); + }; + const send = async (labels: ReadonlyArray, applied: boolean) => { + for (const batch of changeBatches(labels)) await sendBatch(batch, applied); + }; + // Adding first keeps the Labels row from showing empty between the two writes. + void send(add, true).then(() => send(remove, false)); + }), + [navigation, draft, latest, setLabels, target], + ); return ( candidate.name} - extraData={{ pending, allowed, count: candidates.length }} + extraData={{ draft, allowed, count: candidates.length }} estimatedItemSize={72} recycleItems className="flex-1" @@ -96,16 +121,9 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps - {readOnlyReason ? ( - {readOnlyReason} - ) : null} - {error ? ( - - {error} - - ) : null} + readOnlyReason ? ( + + {readOnlyReason} ) : undefined } @@ -114,13 +132,15 @@ export function PullRequestLabelsScreen({ route }: StaticScreenProps} - onPress={() => void toggle(item)} + onPress={() => + setDraft((current) => toggleSelection(current, item.name, item, item.isApplied)) + } /> )} ListEmptyComponent={ diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx index 2daad20250a59..2a74bad7cc478 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx @@ -12,14 +12,22 @@ import { reviewerCandidateView, type ReviewerTruncation, } from "@t3tools/client-runtime/pull-request-reviewers"; +import { + emptySelection, + isSelected, + changeBatches, + selectionChanges, + toggleSelection, +} from "@t3tools/client-runtime/pull-request-selection"; import type { PullRequestReviewerCandidate } from "@t3tools/contracts"; -import { useRef, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { Pressable, ScrollView, View } from "react-native"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { useContentTopInset, useSearchToolbarInset } from "../../components/ui/useBarInset"; import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; import { EmptyState } from "../../components/ui/EmptyState"; import { Button } from "../../components/ui/Button"; +import * as Dialog from "../../components/ui/Dialog"; import { SymbolView } from "../../components/ui/AppSymbol"; import { composerPullRequests } from "../../state/pull-requests"; import { useEnvironmentQuery } from "../../state/query"; @@ -68,6 +76,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps(null); const [error, setError] = useState(null); const inFlight = useRef(false); + const [draft, setDraft] = useState(emptySelection); const debouncedQuery = useDebouncedValue(query.trim(), 250); const searchInput = { loaded: result.data, @@ -100,6 +109,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps, ) => { @@ -124,13 +134,60 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps + navigation.addListener("beforeRemove", () => { + const { add, remove } = selectionChanges( + draft, + (key, person) => + latest.find((entry) => `${entry.kind}:${entry.id}` === key)?.isRequested ?? + person.isRequested, + ); + const sendBatch = async ( + people: ReadonlyArray, + requested: boolean, + ) => { + const response = await request({ + ...target, + input: { + ...target.input, + reviewers: people.map(({ id, kind }) => ({ id, kind })), + requested, + }, + }); + if (!AsyncResult.isFailure(response)) return; + const cause = squashAtomCommandFailure(response); + const logins = people.map((person) => person.login).join(", "); + Dialog.alert( + requested + ? `Couldn't request a review from ${logins}` + : `Couldn't remove the review request from ${logins}`, + cause instanceof Error ? cause.message : "The provider refused the change.", + ); + }; + const send = async ( + people: ReadonlyArray, + requested: boolean, + ) => { + for (const batch of changeBatches(people)) await sendBatch(batch, requested); + }; + // A search result is keyed by what was typed, so the writes do not reach it on their own. + const refreshSearch = + hostQuery !== null && add.length + remove.length > 0 ? searchResult.refresh : null; + // Removing first lets a host that keeps one reviewer take the new one. + void send(remove, false) + .then(() => send(add, true)) + .then(() => refreshSearch?.()); + }), + [navigation, draft, latest, request, target, hostQuery, searchResult.refresh], + ); const reviewerSearch: AppBarSearch | undefined = listCandidates ? { mode: "inline", @@ -155,7 +212,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps `${candidate.kind}:${candidate.id}`} - extraData={{ allowed, pending }} + extraData={{ allowed, draft }} estimatedItemSize={64} recycleItems renderScrollComponent={NativeScrollView} @@ -168,28 +225,27 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps Tap someone to request a review. Tap a requested reviewer to remove the request. + Changes are sent when you close this sheet. {!allowed ? ( Requesting reviews requires write access and an open {singular}. ) : null} - {error ? ( - - {error} - - ) : null} } renderItem={({ item }) => { const id = `${item.kind}:${item.id}`; + const requested = isSelected(draft, id, item.isRequested); return ( void update(item)} + accessibilityLabel={`${requested ? "Remove review request from" : "Request review from"} ${item.login}${item.kind === "team" ? " team" : ""}`} + accessibilityState={{ disabled: !allowed }} + disabled={!allowed} + onPress={() => + setDraft((current) => toggleSelection(current, id, item, item.isRequested)) + } className="min-h-16 flex-row items-center gap-3 border-b border-border-subtle px-4 py-3 active:opacity-70" > @@ -202,9 +258,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps - {pending === id ? ( - - ) : item.isRequested ? ( + {requested ? ( Requested diff --git a/apps/mobile/src/features/pull-requests/usePullRequestStack.ts b/apps/mobile/src/features/pull-requests/usePullRequestStack.ts index 74a19737ac85d..6efe6143856c5 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestStack.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestStack.ts @@ -1,6 +1,8 @@ import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; import type { PullRequestDetail } from "@t3tools/contracts"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/reactivity"; import { useMemo } from "react"; import { useEnvironmentServerConfig, useNavigationThreadShells } from "../../state/entities"; import { pullRequestStackAtom } from "../../state/pull-requests"; @@ -8,6 +10,8 @@ import { useEnvironmentQuery } from "../../state/query"; import { savedPullRequestStack } from "./pullRequestStack"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; +const NOT_ANSWERED = Atom.make(false); + export function usePullRequestStack(params: PullRequestParams, pr: PullRequestDetail | null) { const target = pullRequestTarget(params); const config = useEnvironmentServerConfig(target.environmentId); @@ -37,11 +41,14 @@ export function usePullRequestStack(params: PullRequestParams, pr: PullRequestDe const query = useEnvironmentQuery( supported ? pullRequestStackAtom({ ...target, input: reference }) : null, ); + const answered = useAtomValue( + supported ? pullRequestStackAtom.answered({ ...target, input: reference }) : NOT_ANSWERED, + ); const stack = query.isSuccess ? query.data : (query.data ?? saved); return { ...query, stack, - isFresh: supported && query.isSuccess && !query.isPending, + isFresh: supported && query.isSuccess && !query.isPending && answered, supportsStackActions: supported && pr?.capabilities.stackActions === true, }; } diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index 201204a8a57bf..ef279152d2581 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -431,15 +431,16 @@ export function NewTaskDraftScreen(props: { if (appliedInitialProjectKeyRef.current === directProjectKey) { return; } + // setProject creates the draft, so it also runs when the fallback already shows this project. + const showsDirectProject = + flow.draftKey !== null && + selectedProject?.environmentId === directProject.environmentId && + selectedProject.id === directProject.id; if (props.initialProjectRef?.branch) { - if ( - selectedProject?.environmentId !== directProject.environmentId || - selectedProject.id !== directProject.id - ) { + if (!showsDirectProject || !flow.draftKey) { setProject(directProject); return; } - if (!flow.draftKey) return; // Checkout completed before mount; local mode reuses it while worktree mode would create another. updateComposerDraftSettings(flow.draftKey, { workspaceSelection: { @@ -451,12 +452,7 @@ export function NewTaskDraftScreen(props: { }); } appliedInitialProjectKeyRef.current = directProjectKey; - if ( - selectedProject?.environmentId === directProject.environmentId && - selectedProject.id === directProject.id - ) { - return; - } + if (showsDirectProject) return; setProject(directProject); return; } diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 425a5cecac599..4ee5478648aaa 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -168,7 +168,6 @@ import { appAtomRegistry } from "../../state/atom-registry"; import { threadStreamHaptics } from "./threadStreamHaptics"; import { useAtomCommand } from "../../state/use-atom-command"; import { orchestrationEnvironment } from "../../state/orchestration"; -import { useDelayedStatus } from "../../lib/useDelayedStatus"; import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; import type { @@ -191,6 +190,7 @@ import { FloatingWorkingControl, } from "./floating-working-control"; import { connectionFloatingStatus, type FloatingWorkingStatus } from "./floating-working-status"; +import type { ThreadStatusLineModel } from "./thread-context-divider"; import { derivePendingUserInputMaxHeight, ESTIMATED_KEYBOARD_HEIGHT, @@ -231,7 +231,6 @@ export interface ThreadDetailScreenProps { readonly interactionLocked: boolean; }; readonly worktreeSetup?: WorktreeSetupCardProps | null; - readonly setupWorkingStartedAt?: string | null; readonly canOperateThread: boolean; readonly selectedThread: EnvironmentThreadShell; /** Use this for detail reads; it stays null until queued creation reaches the server. */ @@ -268,7 +267,6 @@ export interface ThreadDetailScreenProps { readonly activePendingUserInputAnswers: Record> | null; readonly respondingUserInputId: RuntimeRequestId | null; readonly connectionStateLabel: EnvironmentConnectionPhase; - readonly connectionAwaitingApproval?: boolean; readonly historyControls?: ThreadFeedHistoryControls; readonly activeThreadBusy: boolean; readonly canStopThread: boolean; @@ -342,6 +340,7 @@ function ColumnWidth(props: { readonly width: number | null; readonly children: ); } const USAGE_LIMITS_PANEL_GAP = 12; +const FEED_END_GAP = 12; const USAGE_LIMITS_PANEL_MIN_HEIGHT = 44; const USER_INPUT_TOGGLE_TIMING = { @@ -383,9 +382,6 @@ const NO_RUN_STOP_ATOM = Atom.make(null).pipe( Atom.withLabel("mobile-thread-run-stop:empty"), ); -// Connection failures survive retries and app suspension. -const RECONNECT_ERROR_DELAY_MS = 5_000; - // Anchors, the submitted message, follow state and pending scrolls belong to // one thread, so the body remounts when the thread changes. export function ThreadDetailScreen(props: ThreadDetailScreenProps) { @@ -569,14 +565,6 @@ function ThreadDetailBody( ); const composerKeyboardOffset = composerBottomInset; const contentPresentationKind = props.contentPresentation.kind; - const connectionRetrying = - props.connectionStateLabel === "connecting" || props.connectionStateLabel === "reconnecting"; - const retryError = connectionRetrying ? props.connectionError : null; - const retryConnectionError = useDelayedStatus( - `${props.environmentId}:${retryError !== null}`, - retryError, - RECONNECT_ERROR_DELAY_MS, - ); const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, { reportFailure: false, }); @@ -750,11 +738,67 @@ function ThreadDetailBody( Dialog.alert("Pi", props.extensionStatuses?.map((status) => status.text).join("\n\n")), } : null; + const backgroundLine = ((): ThreadStatusLineModel | null => { + if (pendingBackgroundWork === null || contentPresentationKind !== "ready") return null; + return { + key: "background", + icon: pendingBackgroundWork.waiting ? "person.2" : "terminal", + label: pendingBackgroundWork.title, + accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items + .map((item) => item.label) + .join(", ")}`, + onOpen: () => { + Keyboard.dismiss(); + navigation.navigate("ThreadBackgroundWork", { + environmentId: props.environmentId, + threadId: props.selectedThread.id, + }); + }, + action: { + label: statusPending ? "Stopping..." : "Stop", + accessibilityLabel: "Stop background work", + disabled: !props.canOperateThread || statusPending, + onPress: () => void runStatusAction("stop"), + }, + }; + })(); + const lifecycleLine = ((): ThreadStatusLineModel | null => { + if (contentPresentationKind !== "ready" || !(lifecycleSnoozed || settled || woke)) return null; + const actionLabel = lifecycleSnoozed ? "Wake now" : settled ? "Un-settle" : "Dismiss"; + const wake = + lifecycleSnoozed && snoozedUntil !== null + ? snoozeWakeLabel(snoozedUntil, { now: lifecycleNow }) + : "now"; + return { + key: "lifecycle", + icon: settled && !lifecycleSnoozed ? "checkmark.circle" : "alarm", + label: lifecycleSnoozed + ? wake === "now" + ? "Snoozed" + : `Snoozed, ${wake} left` + : settled + ? "Settled" + : "Woke from snooze", + action: { + label: statusPending + ? lifecycleSnoozed + ? "Waking..." + : settled + ? "Un-settling..." + : "Dismissing..." + : actionLabel, + accessibilityLabel: actionLabel, + disabled: !props.canOperateThread || statusPending, + onPress: () => + void runStatusAction(lifecycleSnoozed ? "wake" : settled ? "unsettle" : "dismiss"), + }, + }; + })(); + const statusLines = [backgroundLine, lifecycleLine].filter((line) => line !== null); const floatingStatus = ((): FloatingWorkingStatus | null => { const connectionStatus = connectionFloatingStatus({ - connectionError: connectionRetrying ? retryConnectionError : props.connectionError, + connectionError: props.connectionError, connectionState: props.connectionStateLabel, - connectionAwaitingApproval: props.connectionAwaitingApproval === true, environmentLabel: props.environmentLabel, onReconnect: props.onReconnectEnvironment, }); @@ -810,67 +854,6 @@ function ThreadDetailBody( }, }; } - if (props.isCompacting && contentPresentationKind === "ready") { - return { kind: "compacting" }; - } - if (props.activeWorkStartedAt !== null && contentPresentationKind === "ready") { - return { - kind: "working", - environmentId: props.environmentId, - startedAt: props.activeWorkStartedAt, - }; - } - if (pendingBackgroundWork !== null && contentPresentationKind === "ready") { - return { - kind: "background", - label: pendingBackgroundWork.title, - accessibilityLabel: `${pendingBackgroundWork.title}: ${pendingBackgroundWork.items - .map((item) => item.label) - .join(", ")}`, - waiting: pendingBackgroundWork.waiting, - onPress: () => { - Keyboard.dismiss(); - navigation.navigate("ThreadBackgroundWork", { - environmentId: props.environmentId, - threadId: props.selectedThread.id, - }); - }, - action: { - label: statusPending ? "Stopping..." : "Stop", - accessibilityLabel: "Stop background work", - disabled: !props.canOperateThread || statusPending, - onPress: () => void runStatusAction("stop"), - }, - }; - } - if (contentPresentationKind === "ready" && (lifecycleSnoozed || settled || woke)) { - const state = lifecycleSnoozed ? "snoozed" : settled ? "settled" : "woke"; - const label = - lifecycleSnoozed && snoozedUntil !== null - ? `Snoozed, wakes in ${snoozeWakeLabel(snoozedUntil, { now: lifecycleNow })}` - : settled - ? "Settled" - : "Woke from snooze"; - const actionLabel = lifecycleSnoozed ? "Wake now" : settled ? "Un-settle" : "Dismiss"; - return { - kind: "lifecycle", - state, - label, - action: { - label: statusPending - ? lifecycleSnoozed - ? "Waking..." - : settled - ? "Un-settling..." - : "Dismissing..." - : actionLabel, - accessibilityLabel: actionLabel, - disabled: !props.canOperateThread || statusPending, - onPress: () => - void runStatusAction(lifecycleSnoozed ? "wake" : settled ? "unsettle" : "dismiss"), - }, - }; - } if (props.selectedThread.goal !== null && contentPresentationKind === "ready") { const goal = presentProviderGoal(props.selectedThread.goal, false); return { @@ -885,23 +868,12 @@ function ThreadDetailBody( return null; })(); const showWorkingControl = floatingStatus !== null; - // A pending message holds the pill's row for its Starting/Working pill. Worktree setup reports - // progress in the feed instead, so holding the row there only leaves a gap that later closes. - const worktreeSetupInFeed = - props.worktreeSetup?.snapshot.phase === "running" || - (props.creationState?.kind === "preparing" && props.creationState.preparingWorktree); const showFloatingStatus = showWorkingControl || queuedCount > 0 || agentsSegment !== null || devicePreviews.length > 0 || - browserTabs.tabs.length > 0 || - props.connectionStateLabel !== "connected" || - (!worktreeSetupInFeed && - (props.queuedMessages.length > 0 || - props.selectedThreadFeed.some( - (entry) => "acknowledged" in entry && entry.acknowledged === true, - ))); + browserTabs.tabs.length > 0; const selectedThreadFeed = props.selectedThreadFeed; // A palette message result opens the thread at that message: earlier // history loads until the message is in the feed, which then scrolls to it. @@ -1150,7 +1122,8 @@ function ThreadDetailBody( questionInFlow ? 0 : contentInsetEndAdjustment.value + - floatingControlCoverage.value + + // The feed's last row keeps a gap above the composer; the status row grows from it. + Math.max(FEED_END_GAP, floatingControlCoverage.value) + (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0), @@ -1479,8 +1452,8 @@ function ThreadDetailBody( workspaceRoot={props.threadCwd} feed={props.selectedThreadFeed} pendingHandoff={props.pendingHandoff} + statusLines={statusLines} worktreeSetup={props.worktreeSetup} - setupWorkingStartedAt={props.setupWorkingStartedAt} preparingWorktree={ props.creationState?.kind === "preparing" && props.creationState.preparingWorktree && @@ -1513,7 +1486,7 @@ function ThreadDetailBody( questionInFlow ? 0 : estimatedOverlayHeight + - (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0) + (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : FEED_END_GAP) } contentMaxWidth={contentMaxWidth} historyControls={props.historyControls} @@ -1605,12 +1578,7 @@ function ThreadDetailBody( colorScheme={isDarkMode ? "dark" : "light"} status={floatingStatus} extensionStatus={ - floatingStatus !== null && - (floatingStatus.kind === "working" || - floatingStatus.kind === "compacting" || - floatingStatus.kind === "background" || - floatingStatus.kind === "goal" || - floatingStatus.kind === "lifecycle") + floatingStatus !== null && floatingStatus.kind === "goal" ? extensionStatus : null } diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 3e1ee80f2831f..ab2f5357aefa1 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1,7 +1,10 @@ +import { toServerClock } from "@t3tools/client-runtime/clock"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width"; +import { useVisibleSecondClock } from "./use-visible-second-clock"; import { ThreadMarkdownVideo, ThreadMediaRetainContext, @@ -18,7 +21,11 @@ import { enrichedSkillReference, } from "../../lib/enrichedLinkPresentation"; import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; -import { ThreadContextDivider } from "./thread-context-divider"; +import { + ThreadContextDivider, + ThreadStatusLine, + type ThreadStatusLineModel, +} from "./thread-context-divider"; import { ThreadHandoffDivider, ThreadHandoffRow, @@ -31,8 +38,10 @@ import { SecretRequestCard } from "./SecretRequestCard"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { WorktreePreparingHeader, - WorktreeWorkingHeader, WorktreeSetupCard, + WorktreeSetupDetails, + WorktreeSetupFoldChip, + worktreeSetupHandedOff, type WorktreeSetupCardProps, } from "./worktree-setup-card"; import * as Haptics from "expo-haptics"; @@ -158,7 +167,7 @@ import { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./mar import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; import { inlineFilePreviewKind, isPdfFile } from "../../lib/filePreview"; import { ThreadInlineFilePreview } from "./ThreadInlineFilePreview"; -import { flattenThemeColor } from "../../lib/mobileTheme"; +import { flattenThemeColor, themeColorWithContrast } from "../../lib/mobileTheme"; import { PresentationSource } from "../../components/ui/NativePresentation"; import { NativeScrollViewMarker } from "../../native/NativeScrollViewMarker"; import Animated, { FadeIn, FadeInDown, type SharedValue } from "react-native-reanimated"; @@ -243,6 +252,7 @@ import { import { appendGuestPendingMessages, appendPendingThreadMessages, + createPendingTurnAppender, createThreadFeedGrouping, isCompactionCommandFeedEntry, type GroupedThreadFeedRow, @@ -341,7 +351,6 @@ export interface ThreadFeedHistoryControls { export interface ThreadFeedProps { readonly toolCallVisibility?: ToolCallVisibility; readonly worktreeSetup?: WorktreeSetupCardProps | null; - readonly setupWorkingStartedAt?: string | null; readonly preparingWorktree?: boolean; readonly queuedMessages: ReadonlyArray; readonly dispatchingMessageId: MessageId | null; @@ -354,6 +363,8 @@ export interface ThreadFeedProps { readonly workspaceRoot?: string | null; readonly feed: ReadonlyArray; readonly pendingHandoff?: HandoffEndpoints | null; + /** Thread states that close the feed: background work, then snooze or settle. */ + readonly statusLines?: ReadonlyArray; readonly contentPresentation: ThreadContentPresentation; readonly latestRun: ThreadFeedLatestRun | null; readonly activeWorkStartedAt: string | null; @@ -1445,7 +1456,7 @@ function useMarkdownStyles(): MarkdownStyleSets { color: markdownUserBodyColor, strongColor: markdownUserBodyColor, mutedColor: markdownUserBodyColor, - linkColor: markdownUserBodyColor, + linkColor: themeColorWithContrast(markdownLinkColor, theme["--color-user-bubble"]), inlineCodeColor: markdownUserInlineCodeText, codeColor: markdownUserCodeText, codeBackgroundColor: markdownUserCodeBg, @@ -1595,7 +1606,7 @@ function ThreadAutomationMessageRow(props: { const summary = taskTitle ?? props.text.trim().split(/\r?\n/, 1)[0] ?? ""; return ( - + ; +}) { + const nowMs = toServerClock(props.environmentId, useVisibleSecondClock(true)); + const seconds = Math.floor((nowMs - Date.parse(props.startedAt)) / 1_000); + return ( + + + Working for {seconds > 0 ? formatDuration(seconds * 1_000) : "0s"} + + + ); } function RunFoldButton({ @@ -1784,7 +1821,13 @@ function renderFeedEntry( | "onEditPendingMessage" | "threadId" | "workspaceRoot" + | "worktreeSetup" > & { + /** The fold row of the turn the worktree setup handed off to. */ + readonly setupFoldRowId: string | null; + readonly setupDetailsOpen: boolean; + readonly onOpenSetupDetails: () => void; + readonly pendingFoldMessageId: string | null; readonly formatMessageTime: (input: string) => string; readonly copiedRowId: string | null; readonly expandedWorkRows: Record; @@ -1844,18 +1887,54 @@ function renderFeedEntry( ); } + if (entry.type === "pending-fold") { + return ( + + + + Pending + + + + ); + } + if (entry.type === "run-fold") { return ( - + {entry.workingSince ? ( + + ) : ( + + )} + {props.worktreeSetup && entry.id === props.setupFoldRowId ? ( + + ) : null} {entry.checkpointSummary ? ( 0); return ( {presentation.attribution === "t3code" ? ( @@ -2366,7 +2446,11 @@ function renderFeedEntry( ) : null} - {entry.pendingMessage && !entry.acknowledged ? "Pending" : timestampLabel} + {entry.pendingMessage && + !entry.acknowledged && + entry.id !== props.pendingFoldMessageId + ? "Pending" + : timestampLabel} {props.onEditPendingMessage !== null && entry.pendingMessage && @@ -3479,12 +3563,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // LegendList does not invalidate visible rows when only the renderItem closure changes. // Include turn completion so unchanged message rows reveal their footer and spacing // even when the final message update arrives before the turn settles. + // One sheet for the setup's card, chip, and summary row, so it stays open as setup moves between them. + const [setupDetailsThreadId, setSetupDetailsThreadId] = useState(null); + const setupDetailsOpen = setupDetailsThreadId === props.threadId && !!props.worktreeSetup; + const openSetupDetails = () => setSetupDetailsThreadId(props.threadId); const listAppearanceData = { + setupDetailsOpen, disclosureLayout, reduceMotion, formatMessageTime, worktreeSetup: props.worktreeSetup, - setupWorkingStartedAt: props.setupWorkingStartedAt, preparingWorktree: props.preparingWorktree, dispatchingMessageId: props.dispatchingMessageId, unsettledTurnId, @@ -3572,10 +3660,16 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (jumpReady && revealedMessageId !== jumpToMessageId) { setInteractionState((current) => ({ ...current, revealedMessageId: jumpToMessageId })); } + const [appendPendingTurn] = useState(createPendingTurnAppender); const presentedFeed = appendGuestPendingMessages( - useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups, revealedMessageId), + appendPendingTurn( + useThreadFeedPresentation(props, expandedTurnIds, expandedWorkGroups, revealedMessageId), + { zen: props.toolCallVisibility === "zen" }, + ), guestShare, ); + const pendingFoldMessageId = + presentedFeed.findLast((entry) => entry.type === "pending-fold")?.messageId ?? null; const jumpRunId = jumpReady && !presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId) @@ -3590,13 +3684,22 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const setupAnchorIndex = presentedFeed.findIndex( (entry) => entry.type === "message" && entry.message.role === "user", ); + // As on web, setup still running after the agent took the turn rides on the live Working row. + const setupFoldRowId = + props.worktreeSetup && + worktreeSetupHandedOff(props.worktreeSetup) && + props.worktreeSetup.snapshot.phase === "running" + ? (presentedFeed.find( + (entry, index) => + index > setupAnchorIndex && + entry.type === "run-fold" && + entry.workingSince !== undefined, + )?.id ?? null) + : null; const [groupFeed] = useState(createThreadFeedGrouping); const groupedFeed = groupFeed(presentedFeed, { workflowOpeningMessageId: workflowOpening?.messageId, - setupAnchorIndex: - props.worktreeSetup || props.setupWorkingStartedAt || props.preparingWorktree - ? setupAnchorIndex - : undefined, + setupAnchorIndex: props.worktreeSetup || props.preparingWorktree ? setupAnchorIndex : undefined, }); const { contentInsetEndAdjustment } = props; const attachList = (list: LegendListRef | null) => { @@ -3834,6 +3937,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // corrects each row's height as it mounts — the feed visibly jumps. const getFixedItemSize = (entry: ThreadFeedRow) => { if (entry.type === "guest-pending") return undefined; + if (entry.type === "pending-fold") { + return workRowSizing.fixedRowHeight === undefined + ? undefined + : resolveThreadFeedFixedItemSize("run-fold"); + } if (entry.type === "html-render") { return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth)); } @@ -3924,6 +4032,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { formatMessageTime, environmentId: props.environmentId, dispatchingMessageId: props.dispatchingMessageId, + pendingFoldMessageId, + setupFoldRowId, + worktreeSetup: props.worktreeSetup, + setupDetailsOpen, + onOpenSetupDetails: openSetupDetails, onEditPendingMessage: props.onEditPendingMessage, onUseArtifactTemplate: props.onUseArtifactTemplate, threadId: props.threadId, @@ -3964,9 +4077,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { workflowOpening, })} {props.worktreeSetup && info.index === setupAnchorIndex ? ( - - ) : props.setupWorkingStartedAt && info.index === setupAnchorIndex ? ( - + ) : props.preparingWorktree && info.index === setupAnchorIndex ? ( ) : null} @@ -4023,6 +4139,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { viewabilityConfig={THREAD_MEDIA_VIEWABILITY_CONFIG} keyExtractor={(entry) => entry.id} getItemType={(entry) => { + // Same container as the live fold that replaces it. + if (entry.type === "pending-fold") return "run-fold"; if (entry.type !== "message") return entry.type; if (isCompactionCommandFeedEntry(entry)) return "message:compaction"; if ( @@ -4067,7 +4185,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { <> {usesNativeAutomaticInsets ? null : } {setupAnchorIndex < 0 && props.worktreeSetup ? ( - + ) : setupAnchorIndex < 0 && props.preparingWorktree ? ( ) : null} @@ -4077,14 +4200,21 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } ListFooterComponent={ - props.pendingHandoff ? ( - + props.pendingHandoff || props.statusLines?.length ? ( + <> + {props.pendingHandoff ? ( + + ) : null} + {props.statusLines?.map((line) => ( + + ))} + ) : null } contentContainerStyle={{ @@ -4113,6 +4243,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ) : null} + {setupDetailsOpen && props.worktreeSetup ? ( + setSetupDetailsThreadId(null)} + /> + ) : null} diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 4d814d3a8a4f7..735e169a72dda 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -52,6 +52,7 @@ import { EmptyState } from "../../components/ui/EmptyState"; import { LoadingScreen } from "../../components/LoadingScreen"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { useDelayedStatus } from "../../lib/useDelayedStatus"; +import { connectionRetryLabel } from "./floating-working-status"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { useThreadShell } from "../../state/entities"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; @@ -136,6 +137,8 @@ function firstRouteParam(value: string | string[] | undefined): string | null { return first === undefined || first.trim().length === 0 ? null : first; } +const RECONNECT_ERROR_DELAY_MS = 5_000; + // The inspector pane's bar belongs to ThreadInspectorHeader; the fallback must not draw its own. const InspectorHeaderShownContext = createContext(false); @@ -857,7 +860,7 @@ function ThreadRouteContent( ); }; const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null; - const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({ + const { visible: worktreeSetup } = useWorktreeSetup({ environmentId: selectedThread?.environmentId ?? null, threadId: selectedThread?.id ?? null, preparing: @@ -961,18 +964,33 @@ function ThreadRouteContent( detailDeleted: selectedThreadDetailState.status === "deleted", connectionState: routeConnectionState, }); - // Shown in the header subtitle so the composer's status slot doesn't jump while history syncs. - const threadSyncLabel = useDelayedStatus( - selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id), - // A thread this client is creating has nothing older to sync. + const connectionRetrying = + routeConnectionState === "connecting" || routeConnectionState === "reconnecting"; + // Connection failures survive retries and app suspension. + const retryConnectionError = useDelayedStatus( + `${environmentId}:${connectionRetrying && routeConnectionError !== null}`, + connectionRetrying ? routeConnectionError : null, + RECONNECT_ERROR_DELAY_MS, + ); + const connectionStatusLabel = connectionRetryLabel({ + connectionError: retryConnectionError, + connectionState: routeConnectionState, + connectionAwaitingApproval: routeEnvironmentRuntime?.connectionAwaitingApproval === true, + }); + // A thread this client is creating has nothing older to sync. + const threadSyncLabel = creationState === null ? threadSyncStatusLabel(selectedThreadDetailState.status, contentPresentation.kind) - : null, + : null; + // Transient states go in the header subtitle so the composer's status slot doesn't jump. + const threadStatusLabel = useDelayedStatus( + selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id), + connectionStatusLabel !== null ? connectionStatusLabel : threadSyncLabel, ); const inspectorHeader = props.inspectorPresentation ? ( ) : null; @@ -1000,7 +1018,7 @@ function ThreadRouteContent( props.inspectorPresentation ? null : ( entry.type === "message" && entry.message.role === "user", - ).length <= 1 - ? composer.activeWorkStartedAt - : null - } worktreeSetup={ worktreeSetup ? { snapshot: worktreeSetup, - turnStartedAt: setupTurnStartedAt, - working: composer.activeWorkStartedAt !== null, turnStarted: setupTurnStartedAt !== null, onCancel: handleCancelWorktreeSetup, onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null, @@ -1065,7 +1072,6 @@ function ThreadRouteContent( activePendingUserInputAnswers={requests.activePendingUserInputAnswers} respondingUserInputId={requests.respondingUserInputId} connectionStateLabel={routeConnectionState} - connectionAwaitingApproval={routeEnvironmentRuntime?.connectionAwaitingApproval === true} historyControls={historyControls} activeThreadBusy={composer.activeThreadBusy} canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null} diff --git a/apps/mobile/src/features/threads/floating-working-control.tsx b/apps/mobile/src/features/threads/floating-working-control.tsx index 0f83743f99d31..f1143e9e5040f 100644 --- a/apps/mobile/src/features/threads/floating-working-control.tsx +++ b/apps/mobile/src/features/threads/floating-working-control.tsx @@ -1,16 +1,7 @@ -import { toServerClock } from "@t3tools/client-runtime/clock"; import type { SubagentPillSegment } from "@t3tools/client-runtime/state/thread-subagents"; -import type { EnvironmentId } from "@t3tools/contracts"; -import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import { GlassContainer, GlassView } from "expo-glass-effect"; import { type ReactNode, useEffect, useRef, useState } from "react"; -import { - type LayoutChangeEvent, - Pressable, - Text as SystemText, - useWindowDimensions, - View, -} from "react-native"; +import { type LayoutChangeEvent, Pressable, useWindowDimensions, View } from "react-native"; import Animated, { Easing, FadeIn, @@ -33,7 +24,6 @@ import { BrowserPreviewButton } from "../browser/browser-preview-button"; import { DevicePreviewButton } from "../devices/device-preview-button"; import type { FloatingWorkingStatus } from "./floating-working-status"; import { ShimmeringWorkContent } from "./thread-work-log"; -import { useVisibleSecondClock } from "./use-visible-second-clock"; const CONTROL_HEIGHT = 38.5; const CONTROL_GAP = 8; @@ -91,12 +81,7 @@ export function FloatingWorkingControl(props: { const extensionStatus = props.extensionStatus ?? null; const extensionOnly = props.status?.kind === "extension"; const useGlass = NATIVE_LIQUID_GLASS_SUPPORTED && !extensionOnly; - const action = - props.status?.kind === "background" || - props.status?.kind === "lifecycle" || - props.status?.kind === "stop" - ? props.status.action - : null; + const action = props.status?.kind === "stop" ? props.status.action : null; const [agentsWidth, setAgentsWidth] = useState(0); const hasQueue = props.queuedCount > 0; const hasPreview = props.devicePreview !== null || props.browserPreview !== null; @@ -176,8 +161,7 @@ export function FloatingWorkingControl(props: { const statusInteractive = props.status?.kind === "connection" || props.status?.kind === "extension" || - props.status?.kind === "child-input" || - props.status?.kind === "background"; + props.status?.kind === "child-input"; const capsuleInteractive = statusInteractive || extensionStatus !== null || @@ -199,8 +183,6 @@ export function FloatingWorkingControl(props: { > void }) { - return ( - - - Compacting… - - ); -} - function FloatingStatusLabel(props: { readonly status: FloatingWorkingStatus; readonly onLayout: (event: LayoutChangeEvent) => void; @@ -427,9 +395,6 @@ function FloatingStatusLabel(props: { ); } - if (props.status.kind === "compacting") { - return ; - } if (props.status.kind === "child-input") { return ( - {props.status.tone === "reconnecting" ? ( - - ) : ( - - )} + ); } - if (props.status.kind === "lifecycle") { - return ( - - - - {props.status.label} - - - ); - } - if (props.status.kind === "background") { - return ( - - - - {props.status.label} - - - ); - } if (props.status.kind === "stop") { return ( ); } - if (props.status.kind === "preparing") { - return ( - - - - - ); - } return ( - + > + + + ); } @@ -629,53 +538,6 @@ function StatusLabelRow(props: { ); } -function WorkingDuration(props: { - readonly environmentId: EnvironmentId; - readonly startedAt: string; - readonly onLayout: (event: LayoutChangeEvent) => void; -}) { - return ( - - - - ); -} - -function WorkingTimer(props: { - readonly environmentId: EnvironmentId; - readonly startedAt: string; -}) { - const nowMs = useVisibleSecondClock(true); - return ( - - Working {formatWorkingDuration(props.startedAt, toServerClock(props.environmentId, nowMs))} - - ); -} - -function formatWorkingDuration(startedAt: string, nowMs: number): string { - const startedAtMs = Date.parse(startedAt); - if (!Number.isFinite(startedAtMs) || nowMs <= startedAtMs) { - return "0s"; - } - - const totalSeconds = Math.floor((nowMs - startedAtMs) / 1_000); - if (totalSeconds < 60) { - return `${totalSeconds}s`; - } - if (totalSeconds >= 3_600) { - return formatDuration(totalSeconds * 1_000); - } - - const minutes = Math.floor(totalSeconds / 60); - const seconds = String(totalSeconds % 60).padStart(2, "0"); - return `${minutes}m ${seconds}s`; -} - function ScrollToEndButton(props: { readonly disabled?: boolean; readonly onPress: () => void }) { return ( void; } - | { - readonly kind: "background"; - readonly label: string; - readonly accessibilityLabel: string; - readonly waiting: boolean; - readonly onPress: () => void; - readonly action: FloatingStatusAction; - } - | { - readonly kind: "lifecycle"; - readonly state: "snoozed" | "settled" | "woke"; - readonly label: string; - readonly action: FloatingStatusAction; - } | { readonly kind: "stop"; readonly label: string; @@ -42,46 +25,39 @@ export type FloatingWorkingStatus = | { readonly kind: "preparing"; readonly label: string } | { readonly kind: "connection"; - readonly tone: "reconnecting" | "unavailable"; readonly label: string; readonly onPress: () => void; }; -export function connectionFloatingStatus(input: { +/** A connection still retrying on its own; short enough for the thread header subtitle. */ +export function connectionRetryLabel(input: { readonly connectionError: string | null; readonly connectionState: EnvironmentConnectionPhase; readonly connectionAwaitingApproval?: boolean; +}): string | null { + if (input.connectionState === "reconnecting" && input.connectionAwaitingApproval) { + return "Awaiting device approval"; + } + if (input.connectionState !== "connecting" && input.connectionState !== "reconnecting") { + return null; + } + return input.connectionError === null ? "Reconnecting…" : "Retrying connection…"; +} + +export function connectionFloatingStatus(input: { + readonly connectionError: string | null; + readonly connectionState: EnvironmentConnectionPhase; readonly environmentLabel: string | null; readonly onReconnect: () => void; }): FloatingWorkingStatus | null { const environmentLabel = input.environmentLabel ?? "Environment"; const unavailable = (label: string): FloatingWorkingStatus => ({ kind: "connection", - tone: "unavailable", label, onPress: input.onReconnect, }); - if (input.connectionState === "reconnecting" && input.connectionAwaitingApproval) { - return { - kind: "connection", - tone: "reconnecting", - label: `Waiting for ${environmentLabel} to approve this device`, - onPress: input.onReconnect, - }; - } switch (input.connectionState) { - case "connecting": - case "reconnecting": - return { - kind: "connection", - tone: "reconnecting", - label: - input.connectionError === null - ? `Reconnecting to ${environmentLabel}...` - : `Failed to connect. Retrying ${environmentLabel}...`, - onPress: input.onReconnect, - }; case "offline": return unavailable("You are offline"); case "unsupported": @@ -94,6 +70,8 @@ export function connectionFloatingStatus(input: { ); case "available": return unavailable(`${environmentLabel} is not connected`); + case "connecting": + case "reconnecting": case "connected": return null; } diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx index 05ccf29b2ae70..0972d937696e1 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.test.tsx @@ -14,7 +14,7 @@ import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; -import { act, useLayoutEffect } from "react"; +import { act, useEffect, useLayoutEffect } from "react"; import { createRoot } from "react-dom/client"; import { expect, it, vi } from "vite-plus/test"; import type { ComposerDraft } from "../../state/use-composer-drafts"; @@ -213,11 +213,16 @@ function setup() { mocks.writeSettings.mockImplementation(write); mocks.writeText.mockImplementation((key, text) => write(key, { text })); let current: ReturnType; - function Probe() { + function Probe(props: { readonly pickOnMount?: EnvironmentProject }) { const value = useNewTaskFlow(); useLayoutEffect(() => { current = value; }); + // Mirrors the draft screen applying its route project on mount, before the provider's effects run. + useEffect(() => { + if (props.pickOnMount) value.setProject(props.pickOnMount); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- picks once on mount; setProject changes every render + }, []); return null; } const root = createRoot(document.createElement("div")); @@ -245,16 +250,20 @@ function setup() { get current() { return current; }, - async render(active: boolean) { + async render(active: boolean, pickOnMount?: EnvironmentProject) { await act(async () => root.render( - + , ), ); + // The draft screen applies a project whenever it shows without a draft. + if (active && current.draftKey === null) { + await act(async () => current.setProject(projects[0]!)); + } }, async emit(cwd: string, branch: string, isRepo = true) { await act(async () => emitters.get(cwd)!(branch, isRepo)); @@ -270,6 +279,16 @@ function setup() { }; } +it("keeps the draft on a project the screen picks as it mounts", async () => { + using screen = setup(); + await screen.render(true, screen.projects[2]); + expect(screen.current.selectedProject).toEqual(screen.projects[2]); + expect(screen.snapshot(screen.current.draftKey).project).toEqual({ + environmentId: "two", + projectId: "b", + }); +}); + it("owns a status stream only while the draft is active, retaining draft choices on reopen", async () => { using screen = setup(); await screen.render(false); diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index 5852206095a8f..83d87d6eba882 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -2,7 +2,7 @@ import { ActiveNewTaskContext } from "../../state/active-new-task"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; import { useNowMinuteMs } from "../../lib/clock"; import * as Dialog from "../../components/ui/Dialog"; -import React, { useEffect, useRef, useState } from "react"; +import React, { useRef, useState } from "react"; import type { EnvironmentId, @@ -304,11 +304,23 @@ export function NewTaskFlowProvider( // binding outlives the draft's project stamp (submit clears it). const updateFlow = (patch: Partial) => updateNewTaskFlowState(flowKey, { ...readFlow(), ...patch }); + // A draft's project stamp is the selection: picking a project writes it, and uploads and + // the send read it, so the screen cannot show one project while the draft holds another. + const draftStamp = useComposerDraft(activeDraftKey).project; + const stampedProject = + draftStamp === undefined + ? undefined + : projects.find( + (project) => + project.environmentId === draftStamp.environmentId && + project.id === draftStamp.projectId, + ); const selectedEnvironmentId = - selectedEnvironmentIdOverride !== null && + stampedProject?.environmentId ?? + (selectedEnvironmentIdOverride !== null && projects.some((project) => project.environmentId === selectedEnvironmentIdOverride) ? selectedEnvironmentIdOverride - : (projects[0]?.environmentId ?? null); + : (projects[0]?.environmentId ?? null)); const projectsForEnvironment = pipe( projects, Arr.filter((project) => project.environmentId === selectedEnvironmentId), @@ -319,7 +331,8 @@ export function NewTaskFlowProvider( const selectedProject = routeDraftResolution.kind === "pending" ? null - : (projectsForEnvironment.find( + : (stampedProject ?? + projectsForEnvironment.find( (project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey, ) ?? projectsForEnvironment[0] ?? @@ -333,25 +346,6 @@ export function NewTaskFlowProvider( const serverConfigs = useServerConfigs(); const { connectedEnvironments } = useRemoteConnectionStatus(); const selectedProjectDraftKey = selectedProject ? activeDraftKey : null; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates the persistent draft in the new-task flow store once a project is selected, before the composer mounts - useEffect(() => { - // A route that names a draft binds that draft, or returns to the picker. - if ( - props.active === false || - props.routeDraftId !== undefined || - activeDraftKey !== null || - selectedProject === null - ) { - return; - } - // Creates the persistent draft once the project selection is ready; the key must exist before the composer mounts. - updateNewTaskFlowState(flowKey, { - draftKey: createNewTaskDraft({ - environmentId: selectedProject.environmentId, - projectId: selectedProject.id, - }), - }); - }, [activeDraftKey, flowKey, selectedProject, props.active, props.routeDraftId]); const activePendingKey = props.active === false ? null diff --git a/apps/mobile/src/features/threads/pending-thread-feed.test.ts b/apps/mobile/src/features/threads/pending-thread-feed.test.ts index 99cabea0d5443..f7c237d4aa9f1 100644 --- a/apps/mobile/src/features/threads/pending-thread-feed.test.ts +++ b/apps/mobile/src/features/threads/pending-thread-feed.test.ts @@ -11,6 +11,7 @@ import type { QueuedThreadMessage } from "../../state/thread-outbox-model"; import { appendAcceptedThreadMessages, appendPendingThreadMessages, + createPendingTurnAppender, createThreadFeedGrouping, isCompactionCommandFeedEntry, selectPendingAcknowledgedMessages, @@ -229,4 +230,30 @@ describe("pending timeline messages", () => { "waiting", ]); }); + + it("holds the run's rows after a sent message until the run shows", () => { + const appendTurn = createPendingTurnAppender(); + const sent = appendPendingThreadMessages([], [], [pending("sent")]); + const held = appendTurn(sent, { zen: false }); + expect(held.map((entry) => [entry.id, "label" in entry ? entry.label : null])).toEqual([ + ["sent", null], + ["pending-fold:sent", null], + ["live-activity-row", "Sending…"], + ]); + expect(appendTurn(sent, { zen: false })[1]).toBe(held[1]); + const delivered = sent.map((entry) => ({ ...entry, acknowledged: true })); + expect(appendTurn(delivered, { zen: true }).map((entry) => entry.id)).toEqual([ + "sent", + "live-activity-row", + ]); + // A working run already shows its own rows. + const thinking = { + type: "thinking", + runId: null, + id: "thinking", + createdAt: "2026-09-06T11:00:00.000Z", + } as const; + const working = appendPendingThreadMessages([thinking], [], [pending("queued")]); + expect(appendTurn(working, { zen: false })).toBe(working); + }); }); diff --git a/apps/mobile/src/features/threads/pending-thread-feed.ts b/apps/mobile/src/features/threads/pending-thread-feed.ts index 940ec12db8604..af39959f2ebe7 100644 --- a/apps/mobile/src/features/threads/pending-thread-feed.ts +++ b/apps/mobile/src/features/threads/pending-thread-feed.ts @@ -3,7 +3,7 @@ import { type ThreadGuestMessage, type ThreadGuestShare, } from "@t3tools/contracts"; -import type { ThreadFeedEntry } from "../../lib/threadActivity"; +import { LIVE_ACTIVITY_ROW_ID, type ThreadFeedEntry } from "../../lib/threadActivity"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { threadHasCaughtUpTo } from "@t3tools/client-runtime/state/threads"; import { resolveUserMessageGrouping } from "@t3tools/client-runtime/user-message"; @@ -51,8 +51,19 @@ export function selectPendingAcknowledgedMessages( ); } +/** + * Holds the turn's fold slot while a sent message waits for its run, so the live "Working for" + * row replaces it in place instead of being inserted. + */ +export interface PendingFoldFeedEntry { + readonly type: "pending-fold"; + readonly id: string; + readonly createdAt: string; + readonly messageId: string; +} + /** A row of the thread feed's list. */ -export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry; +export type ThreadFeedRow = PendingThreadFeedEntry | GuestPendingFeedEntry | PendingFoldFeedEntry; export type GroupedThreadFeedRow = ThreadFeedRow & { readonly userMessageGrouping: ReturnType; @@ -100,7 +111,7 @@ export function createThreadFeedGrouping() { /** Waiting guest messages go after the transcript, oldest first. */ export function appendGuestPendingMessages( - presentedFeed: ReadonlyArray, + presentedFeed: ReadonlyArray, share: ThreadGuestShare | null, ): ReadonlyArray { const pending = share?.messages.filter((message) => message.status === "pending") ?? []; @@ -175,6 +186,56 @@ export function appendAcceptedThreadMessages( ); } +/** + * Ends the feed with the rows a starting run will fill, while its last row is a sent message no + * run has picked up: the fold slot and the live activity row, under the activity row's own key. + * The run's rows then replace them in place instead of being inserted. + */ +export function createPendingTurnAppender() { + let fold: PendingFoldFeedEntry | null = null; + let activity: Extract | null = null; + return ( + feed: ReadonlyArray, + options: { readonly zen: boolean }, + ): ReadonlyArray => { + const last = feed.at(-1); + if ( + last?.type !== "message" || + last.message.role !== "user" || + last.pendingMessage === undefined || + last.pendingMessage.creation !== undefined || + isCompactionCommandMessage(last.message) || + feed.some( + (entry) => + (entry.type === "run-fold" && entry.workingSince !== undefined) || + entry.type === "thinking", + ) + ) { + return feed; + } + const label = last.acknowledged ? "Starting…" : "Sending…"; + if (activity?.createdAt !== last.createdAt || activity.label !== label) { + activity = { + type: "thinking", + id: LIVE_ACTIVITY_ROW_ID, + createdAt: last.createdAt, + runId: null, + label, + }; + } + if (options.zen) return [...feed, activity]; + if (fold?.messageId !== last.id) { + fold = { + type: "pending-fold", + id: `pending-fold:${last.id}`, + createdAt: last.createdAt, + messageId: last.id, + }; + } + return [...feed, fold, activity]; + }; +} + export function isCompactionCommandFeedEntry(entry: PendingThreadFeedEntry): boolean { return ( entry.type === "message" && diff --git a/apps/mobile/src/features/threads/thread-context-divider.tsx b/apps/mobile/src/features/threads/thread-context-divider.tsx index 19c99f6e63e45..ccaa1b1d8aa9d 100644 --- a/apps/mobile/src/features/threads/thread-context-divider.tsx +++ b/apps/mobile/src/features/threads/thread-context-divider.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from "react"; -import { View, type ColorValue } from "react-native"; +import { Pressable, View, type ColorValue } from "react-native"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; import { ShimmeringWorkContent } from "./thread-work-log"; @@ -14,35 +14,105 @@ export function ThreadContextDivider(props: { }) { return ( - + - {props.icon ? ( - - ) : null} - {props.active ? ( - - ) : ( - - {props.label} - - )} + {/* One row, so a long label wraps beside its icon instead of under it. */} + + {props.icon ? ( + + ) : null} + {props.active ? ( + + ) : ( + + {props.label} + + )} + {props.children} - + + + ); +} + +export interface ThreadStatusLineModel { + readonly key: string; + readonly icon: AppSymbolName; + readonly label: string; + readonly accessibilityLabel?: string; + /** Tapping the label opens the state's detail. */ + readonly onOpen?: () => void; + readonly action: { + readonly label: string; + readonly accessibilityLabel: string; + readonly disabled: boolean; + readonly onPress: () => void; + }; +} + +/** A thread state that closes the feed with its one action, left-aligned as on web. */ +export function ThreadStatusLine(props: { + readonly line: ThreadStatusLineModel; + readonly iconColor: ColorValue; +}) { + const { line } = props; + const { action } = line; + const body = ( + <> + + + {line.label} + + + ); + return ( + + {line.onOpen ? ( + + {body} + + ) : ( + + {body} + + )} + · + + {action.label} + ); } diff --git a/apps/mobile/src/features/threads/thread-feed-scroll-position.test.ts b/apps/mobile/src/features/threads/thread-feed-scroll-position.test.ts index 89816db6467ed..ef8158cb5b90d 100644 --- a/apps/mobile/src/features/threads/thread-feed-scroll-position.test.ts +++ b/apps/mobile/src/features/threads/thread-feed-scroll-position.test.ts @@ -65,16 +65,19 @@ describe("resolveThreadFeedSubmissionAnchor", () => { ).toBe("first-message"); }); - it("does not anchor a follow-up after a user message appears", () => { + it("keeps the first message's anchor, not the follow-up's, after a user message appears", () => { + const followUp = { + submittedMessageId: "second-message", + hasStartedTurn: true, + hasUserMessage: true, + deliveryDeferred: false, + queuedMessageCount: 0, + }; expect( - resolveThreadFeedSubmissionAnchor({ - currentAnchorMessageId: "first-message", - submittedMessageId: "second-message", - hasStartedTurn: false, - hasUserMessage: true, - deliveryDeferred: false, - queuedMessageCount: 0, - }), + resolveThreadFeedSubmissionAnchor({ ...followUp, currentAnchorMessageId: "first-message" }), + ).toBe("first-message"); + expect( + resolveThreadFeedSubmissionAnchor({ ...followUp, currentAnchorMessageId: null }), ).toBeNull(); }); diff --git a/apps/mobile/src/features/threads/thread-feed-scroll-position.ts b/apps/mobile/src/features/threads/thread-feed-scroll-position.ts index 58e9ed34248a6..470ecde1623d9 100644 --- a/apps/mobile/src/features/threads/thread-feed-scroll-position.ts +++ b/apps/mobile/src/features/threads/thread-feed-scroll-position.ts @@ -20,13 +20,14 @@ export function resolveThreadFeedSubmissionAnchor(input: { readonly queuedMessageCount: number; readonly deliveryDeferred: boolean; }): AnchorId | null { - if (input.deliveryDeferred || input.hasStartedTurn || input.hasUserMessage) { - return null; - } - + // Keeping the first message's anchor holds a short thread in place; a follow-up never anchors. if (input.currentAnchorMessageId !== null) { return input.currentAnchorMessageId; } + if (input.deliveryDeferred || input.hasStartedTurn || input.hasUserMessage) { + return null; + } + return input.queuedMessageCount > 0 ? null : input.submittedMessageId; } diff --git a/apps/mobile/src/features/threads/worktree-setup-card.tsx b/apps/mobile/src/features/threads/worktree-setup-card.tsx index 66b14afbc47fc..84ae2d70e8451 100644 --- a/apps/mobile/src/features/threads/worktree-setup-card.tsx +++ b/apps/mobile/src/features/threads/worktree-setup-card.tsx @@ -7,7 +7,6 @@ import { } from "@t3tools/contracts"; import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; -import { useState } from "react"; import { Platform, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; @@ -20,8 +19,6 @@ import { useVisibleSecondClock } from "./use-visible-second-clock"; export interface WorktreeSetupCardProps { snapshot: WorktreeSetupSnapshot; turnStarted: boolean; - turnStartedAt: string | null; - working: boolean; onCancel: () => void; onWorkLocally: (() => void) | null; } @@ -40,76 +37,56 @@ const icons: Record = { warning: "exclamationmark.triangle", }; -export function WorktreeSetupCard(props: WorktreeSetupCardProps) { - const { snapshot, turnStarted, turnStartedAt, working } = props; - const handedOff = turnStarted && worktreeSetupAgentStarted(snapshot); +/** The feed owns whether the details sheet is open, so it survives the card turning into a chip or summary. */ +interface SetupDetailsControl { + readonly detailsOpen: boolean; + readonly onOpenDetails: () => void; +} + +export function WorktreeSetupCard(props: WorktreeSetupCardProps & SetupDetailsControl) { + // Once the agent has the turn, running setup is a chip on the live Working row. + if (worktreeSetupHandedOff(props)) { + // As on web, only a setup that went wrong stays in view. + return setupWentWrong(props.snapshot) ? : null; + } + return ; +} + +function WorktreeSetupHeaderCard(props: WorktreeSetupCardProps & SetupDetailsControl) { + const { snapshot, detailsOpen } = props; const running = snapshot.phase === "running"; - const backgroundSetup = handedOff && running; - const scriptName = snapshot.setupScript?.name ?? "Setup script"; - const [detailsOpen, setDetailsOpen] = useState(false); - const now = useVisibleSecondClock(running || working); + const now = useVisibleSecondClock(running); const failed = snapshot.phase === "failed" || snapshot.stages.some((stage) => stage.status === "failed"); - const label = - handedOff && working - ? `Working for ${elapsed(turnStartedAt, null, now) ?? "0s"}` - : running - ? handedOff - ? "Setup continues…" - : "Setting up worktree…" - : snapshot.phase === "cancelled" - ? "Worktree setup cancelled" - : snapshot.phase === "failed" - ? "Worktree setup failed" - : failed - ? "Setup script failed" - : "Worktree ready"; + const label = running + ? "Setting up worktree…" + : snapshot.phase === "cancelled" + ? "Worktree setup cancelled" + : snapshot.phase === "failed" + ? "Worktree setup failed" + : failed + ? "Setup script failed" + : "Worktree ready"; return ( - - {!handedOff ? ( - - {elapsed(snapshot.startedAt, snapshot.endedAt, now)} - - ) : null} + + + {elapsed(snapshot.startedAt, snapshot.endedAt, now)} + setDetailsOpen(true)} + onPress={props.onOpenDetails} className="min-h-11 max-w-[55%] justify-center px-2" > - - {backgroundSetup ? ( - - ) : failed ? ( + + {failed ? ( ) : null} - {backgroundSetup ? "Background setup" : "Details"} + Details - {!backgroundSetup ? ( - - ) : null} + - {!handedOff ? ( - - {snapshot.stages - .filter((stage) => stage.id !== "agent") - .map((stage) => ( - - ))} - - ) : null} - {detailsOpen ? ( - setDetailsOpen(false)} /> - ) : null} + + {snapshot.stages + .filter((stage) => stage.id !== "agent") + .map((stage) => ( + + ))} + ); } +/** True once the agent has the turn; the turn's fold row then carries the setup instead of the card. */ +export function worktreeSetupHandedOff(props: WorktreeSetupCardProps): boolean { + return props.turnStarted && worktreeSetupAgentStarted(props.snapshot); +} + +/** The card's state on the turn's fold row: setup still running, or a failure to look at. */ +export function WorktreeSetupFoldChip(props: WorktreeSetupCardProps & SetupDetailsControl) { + const scriptName = props.snapshot.setupScript?.name ?? "Setup script"; + return ( + + + + Background setup + + + ); +} + +/** + * Setup that ended after the agent took the turn, as one row under the prompt, like web's + * collapsed summary. Tapping it opens the details. + */ +function setupWentWrong(snapshot: WorktreeSetupSnapshot): boolean { + return ( + snapshot.phase === "failed" || + snapshot.phase === "cancelled" || + (snapshot.phase === "done" && + snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed")) + ); +} + +function WorktreeSetupSummaryRow(props: WorktreeSetupCardProps & SetupDetailsControl) { + const { snapshot } = props; + const now = useVisibleSecondClock(false); + const label = + snapshot.phase === "failed" + ? "Worktree setup failed" + : snapshot.phase === "cancelled" + ? "Worktree setup cancelled" + : "Worktree ready, setup script failed"; + return ( + + + + + + {label} + + + {elapsed(snapshot.startedAt, snapshot.endedAt, now)} + + + + ); +} + +/** The one setup details sheet, opened from the card, the chip, or the summary row. */ +export function WorktreeSetupDetails( + props: WorktreeSetupCardProps & { readonly onClose: () => void }, +) { + const now = useVisibleSecondClock(props.snapshot.phase === "running"); + return ; +} + /** Holds the card's place until the server publishes the first setup snapshot. */ // Same rows the first snapshot brings, so the card keeps its height when that snapshot lands. const PREPARING_STAGES: ReadonlyArray = WORKTREE_SETUP_STAGE_ORDER.filter( @@ -177,17 +234,6 @@ export function WorktreePreparingHeader() { ); } -export function WorktreeWorkingHeader({ startedAt }: { startedAt: string }) { - const now = useVisibleSecondClock(true); - return ( - - - - - - ); -} - function HeaderLabel({ label, active, diff --git a/apps/mobile/src/lib/attachmentUpload.test.ts b/apps/mobile/src/lib/attachmentUpload.test.ts index 0097ab7ed77c0..9c58c9a3b05f6 100644 --- a/apps/mobile/src/lib/attachmentUpload.test.ts +++ b/apps/mobile/src/lib/attachmentUpload.test.ts @@ -1,6 +1,7 @@ import { EnvironmentId, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; import * as Option from "effect/Option"; -import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it } from "@effect/vitest"; +import { beforeEach, vi } from "vite-plus/test"; const mocks = vi.hoisted(() => ({ canOperate: true, @@ -89,11 +90,34 @@ vi.mock("expo-file-system", () => ({ UploadType: { BINARY_CONTENT: 0 }, })); +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import { - prepareTurnAttachments, + prepareTurnAttachments as prepareWithUploads, releasePendingAttachmentUploads, + uploadComposerAttachment, withUploadedMobileAttachmentReferences, } from "./attachmentUpload"; + +/** Uploads each attachment directly, as the shared registry does for one holder. */ +function prepare( + input: Omit[0], "uploadAttachment"> & { + readonly onUploadProgress?: (attachmentId: string, progress: number) => void; + }, +) { + return prepareWithUploads({ + ...input, + uploadAttachment: (attachment) => + uploadComposerAttachment( + input.environmentId, + attachment, + input.onUploadProgress + ? (progress) => input.onUploadProgress?.(attachment.id, progress) + : undefined, + ), + }); +} import type { DraftComposerAttachment } from "./composerImages"; const environmentId = EnvironmentId.make("environment-1"); @@ -176,68 +200,80 @@ describe("prepareTurnAttachments", () => { mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} }); }); - it("does not mint or transfer attachments without task operation access", async () => { - mocks.canOperate = false; - await expect( - prepareTurnAttachments({ - environmentId, - attachments: [fileBackedImage], - supportsImageUploads: true, - }), - ).rejects.toThrow("cannot upload attachments"); - expect(mocks.runAtomCommand).not.toHaveBeenCalled(); - expect(mocks.upload).not.toHaveBeenCalled(); - }); - - it("rechecks access after a signed URL is minted before sending any bytes", async () => { - mocks.runAtomCommand.mockImplementationOnce(async () => { + it.effect("does not mint or transfer attachments without task operation access", () => + Effect.gen(function* () { mocks.canOperate = false; - return { - _tag: "Success", - value: { - attachmentId: MINTED_ID, - relativeUrl: "/api/attachments/upload/signed", - expiresAt: 1, - }, - }; - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); - try { - await expect( - prepareTurnAttachments({ - environmentId, - attachments: [fileBackedImage], - supportsImageUploads: true, - }), - ).rejects.toThrow("cannot upload attachments"); + expect( + (yield* Effect.flip( + prepare({ + environmentId, + attachments: [fileBackedImage], + supportsImageUploads: true, + }), + )).message, + ).toContain("cannot upload attachments"); + expect(mocks.runAtomCommand).not.toHaveBeenCalled(); expect(mocks.upload).not.toHaveBeenCalled(); - expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1); - } finally { - warning.mockRestore(); - } - }); + }), + ); - it("does not replace an expired upload when access was revoked during verification", async () => { - mocks.executeAtomQuery.mockImplementationOnce(async () => { - mocks.canOperate = false; - return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } }; - }); - await expect( - prepareTurnAttachments({ - environmentId, - attachments: [ - { - ...fileBackedImage, - uploadedAttachmentId: MINTED_ID, - uploadEnvironmentId: environmentId, + it.effect("rechecks access after a signed URL is minted before sending any bytes", () => + Effect.gen(function* () { + mocks.runAtomCommand.mockImplementationOnce(async () => { + mocks.canOperate = false; + return { + _tag: "Success", + value: { + attachmentId: MINTED_ID, + relativeUrl: "/api/attachments/upload/signed", + expiresAt: 1, }, - ], - supportsImageUploads: true, - }), - ).rejects.toThrow("cannot upload attachments"); - expect(mocks.runAtomCommand).not.toHaveBeenCalled(); - expect(mocks.upload).not.toHaveBeenCalled(); - }); + }; + }); + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + expect( + (yield* Effect.flip( + prepare({ + environmentId, + attachments: [fileBackedImage], + supportsImageUploads: true, + }), + )).message, + ).toContain("cannot upload attachments"); + expect(mocks.upload).not.toHaveBeenCalled(); + expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1); + } finally { + warning.mockRestore(); + } + }), + ); + + it.effect("does not replace an expired upload when access was revoked during verification", () => + Effect.gen(function* () { + mocks.executeAtomQuery.mockImplementationOnce(async () => { + mocks.canOperate = false; + return { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } }; + }); + expect( + (yield* Effect.flip( + prepare({ + environmentId, + attachments: [ + { + ...fileBackedImage, + uploadedAttachmentId: MINTED_ID, + uploadEnvironmentId: environmentId, + }, + ], + supportsImageUploads: true, + }), + )).message, + ).toContain("cannot upload attachments"); + expect(mocks.runAtomCommand).not.toHaveBeenCalled(); + expect(mocks.upload).not.toHaveBeenCalled(); + }), + ); it("rechecks deletion permission before retrying a failed cleanup", async () => { mocks.runAtomCommand.mockImplementationOnce(async () => { @@ -250,256 +286,272 @@ describe("prepareTurnAttachments", () => { expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1); }); - it("inlines a file-backed image lazily when the server lacks image uploads", async () => { - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [fileBackedImage], - }); + it.effect("inlines a file-backed image lazily when the server lacks image uploads", () => + Effect.gen(function* () { + const prepared = yield* prepare({ + environmentId, + attachments: [fileBackedImage], + }); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments).toEqual([ - { - type: "image", - name: "photo.png", - mimeType: "image/png", - sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - }, - ]); - expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri); - expect(mocks.upload).not.toHaveBeenCalled(); - }); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments).toEqual([ + { + type: "image", + name: "photo.png", + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + }, + ]); + expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith(fileBackedImage.fileUri); + expect(mocks.upload).not.toHaveBeenCalled(); + }), + ); // regression: #9713 read file-backed image drafts before enabling them - it("reads restored images from the current iOS document container for legacy sends", async () => { - const fileName = "33333333-3333-4333-8333-333333333333-photo.png"; - mocks.documentUri = - "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents"; - const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`; - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }], - }); - expect(prepared.status).toBe("ready"); - expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith( - `${mocks.documentUri}/t3-composer-attachments/${fileName}`, - ); - }); + it.effect("reads restored images from the current iOS document container for legacy sends", () => + Effect.gen(function* () { + const fileName = "33333333-3333-4333-8333-333333333333-photo.png"; + mocks.documentUri = + "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents"; + const oldUri = `file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`; + const prepared = yield* prepare({ + environmentId, + attachments: [{ ...fileBackedImage, fileUri: oldUri, previewUri: oldUri }], + }); + expect(prepared.status).toBe("ready"); + expect(mocks.readBase64).toHaveBeenCalledExactlyOnceWith( + `${mocks.documentUri}/t3-composer-attachments/${fileName}`, + ); + }), + ); // regression: #9713 read file-backed image drafts before enabling them - it("rejects a legacy image without inline bytes or a file", async () => { - const { fileUri: _, ...missingImage } = fileBackedImage; - await expect( - prepareTurnAttachments({ environmentId, attachments: [missingImage] }), - ).rejects.toThrow("'photo.png' is no longer available. Attach the image again."); - }); + it.effect("rejects a legacy image without inline bytes or a file", () => + Effect.gen(function* () { + const { fileUri: _, ...missingImage } = fileBackedImage; + expect( + (yield* Effect.flip(prepare({ environmentId, attachments: [missingImage] }))).message, + ).toContain("'photo.png' is no longer available. Attach the image again."); + }), + ); - it.each(["resolve", "reject"] as const)( + it.effect.each(["resolve", "reject"] as const)( "abandons a canceled legacy image read that later %ss", - async (outcome) => { - const readStarted = Promise.withResolvers(); - const read = Promise.withResolvers(); - const controller = new AbortController(); - mocks.readBase64.mockImplementation(() => { - readStarted.resolve(); - return read.promise; - }); - const preparing = prepareTurnAttachments({ + (outcome) => + Effect.gen(function* () { + const readStarted = Promise.withResolvers(); + const read = Promise.withResolvers(); + mocks.readBase64.mockImplementation(() => { + readStarted.resolve(); + return read.promise; + }); + const preparing = yield* Effect.forkChild( + prepare({ environmentId, attachments: [fileBackedImage] }), + ); + yield* Effect.promise(() => readStarted.promise); + yield* Fiber.interrupt(preparing); + if (outcome === "resolve") read.resolve("YWJj"); + else read.reject(new Error("Native read failed after cancellation")); + + expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true); + }), + ); + + // regression: #9713 read file-backed image drafts before enabling them + it.effect("uploads a file-backed image from its owned copy without staging base64", () => + Effect.gen(function* () { + mocks.upload.mockImplementation( + async ( + _uri: string, + _url: string, + options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void }, + ) => { + // expo-modules-jsi delivers native Int64 progress counts as BigInt. + options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) }); + return { status: 204, body: "", headers: {} }; + }, + ); + const progress: Array = []; + const prepared = yield* prepare({ environmentId, attachments: [fileBackedImage], - signal: controller.signal, + supportsImageUploads: true, + onUploadProgress: (_, value) => progress.push(value), }); - await readStarted.promise; - controller.abort(); - if (outcome === "resolve") read.resolve("YWJj"); - else read.reject(new Error("Native read failed after cancellation")); - await expect(preparing).resolves.toEqual({ status: "abandoned" }); - }, + expect(progress).toEqual([0.25]); + + expect(mocks.upload).toHaveBeenCalledWith( + fileBackedImage.fileUri, + "https://environment.example/api/attachments/upload/signed", + expect.objectContaining({ headers: { "Content-Type": "image/png" } }), + ); + expect(mocks.readBase64).not.toHaveBeenCalled(); + expect(mocks.writeFile).not.toHaveBeenCalled(); + expect(mocks.deleteFile).not.toHaveBeenCalled(); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments).toEqual([ + { + type: "image", + id: MINTED_ID, + name: "photo.png", + mimeType: "image/png", + sizeBytes: 3, + }, + ]); + }), ); - // regression: #9713 read file-backed image drafts before enabling them - it("uploads a file-backed image from its owned copy without staging base64", async () => { - mocks.upload.mockImplementation( - async ( - _uri: string, - _url: string, - options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void }, - ) => { - // expo-modules-jsi delivers native Int64 progress counts as BigInt. - options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) }); - return { status: 204, body: "", headers: {} }; - }, - ); - const progress: Array = []; - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [fileBackedImage], - supportsImageUploads: true, - onUploadProgress: (_, value) => progress.push(value), - }); - - expect(progress).toEqual([0.25]); + it.effect("sends a document-picked picture with the mime it was uploaded under", () => + Effect.gen(function* () { + const prepared = yield* prepare({ + environmentId, + attachments: [documentPickedImage], + }); - expect(mocks.upload).toHaveBeenCalledWith( - fileBackedImage.fileUri, - "https://environment.example/api/attachments/upload/signed", - expect.objectContaining({ headers: { "Content-Type": "image/png" } }), - ); - expect(mocks.readBase64).not.toHaveBeenCalled(); - expect(mocks.writeFile).not.toHaveBeenCalled(); - expect(mocks.deleteFile).not.toHaveBeenCalled(); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments).toEqual([ - { + expect(mocks.upload).toHaveBeenCalledWith( + "file:///documents/photo.png", + "https://environment.example/api/attachments/upload/signed", + expect.objectContaining({ headers: { "Content-Type": "image/png" } }), + ); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments[0]).toEqual({ type: "image", id: MINTED_ID, name: "photo.png", mimeType: "image/png", sizeBytes: 3, - }, - ]); - }); - - it("sends a document-picked picture with the mime it was uploaded under", async () => { - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [documentPickedImage], - }); + }); + }), + ); - expect(mocks.upload).toHaveBeenCalledWith( - "file:///documents/photo.png", - "https://environment.example/api/attachments/upload/signed", - expect.objectContaining({ headers: { "Content-Type": "image/png" } }), - ); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments[0]).toEqual({ - type: "image", - id: MINTED_ID, - name: "photo.png", - mimeType: "image/png", - sizeBytes: 3, - }); - }); + it.effect("uploads an oversized document-picked image as a file", () => + Effect.gen(function* () { + const largeImage = { + ...documentPickedImage, + mimeType: "image/png", + sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, + }; + const prepared = yield* prepare({ environmentId, attachments: [largeImage] }); - it("uploads an oversized document-picked image as a file", async () => { - const largeImage = { - ...documentPickedImage, - mimeType: "image/png", - sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, - }; - const prepared = await prepareTurnAttachments({ environmentId, attachments: [largeImage] }); - - expect(mocks.runAtomCommand).toHaveBeenCalledWith( - expect.anything(), - mocks.createUploadUrl, - expect.objectContaining({ - input: { + expect(mocks.runAtomCommand).toHaveBeenCalledWith( + expect.anything(), + mocks.createUploadUrl, + expect.objectContaining({ + input: { + type: "file", + name: largeImage.name, + mimeType: "image/png", + sizeBytes: largeImage.sizeBytes, + }, + }), + expect.anything(), + ); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments).toEqual([ + { type: "file", + id: MINTED_ID, name: largeImage.name, mimeType: "image/png", sizeBytes: largeImage.sizeBytes, }, - }), - expect.anything(), - ); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments).toEqual([ - { - type: "file", - id: MINTED_ID, - name: largeImage.name, - mimeType: "image/png", - sizeBytes: largeImage.sizeBytes, - }, - ]); - expect(mocks.readBase64).not.toHaveBeenCalled(); - }); + ]); + expect(mocks.readBase64).not.toHaveBeenCalled(); + }), + ); - it("uploads generic file bytes directly and keeps mixed attachment order", async () => { - const pastedFile = { - ...file, - source: { _tag: "pasted-text" as const }, - }; - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [pastedFile, image], - }); + it.effect("uploads generic file bytes directly and keeps mixed attachment order", () => + Effect.gen(function* () { + const pastedFile = { + ...file, + source: { _tag: "pasted-text" as const }, + }; + const prepared = yield* prepare({ + environmentId, + attachments: [pastedFile, image], + }); - expect(mocks.upload).toHaveBeenCalledWith( - "file:///documents/report.pdf", - "https://environment.example/api/attachments/upload/signed", - expect.objectContaining({ - httpMethod: "POST", - uploadType: 0, - headers: { "Content-Type": "application/pdf" }, - }), - ); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments[0]).toEqual({ - type: "file", - id: MINTED_ID, - name: "report.pdf", - mimeType: "application/pdf", - sizeBytes: 42, - source: { _tag: "pasted-text" }, - }); - expect(prepared.attachments[1]?.type).toBe("image"); - expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]); - expect(prepared.draftAttachments[0]).toEqual({ - ...pastedFile, - uploadedAttachmentId: MINTED_ID, - uploadEnvironmentId: environmentId, - }); - }); + expect(mocks.upload).toHaveBeenCalledWith( + "file:///documents/report.pdf", + "https://environment.example/api/attachments/upload/signed", + expect.objectContaining({ + httpMethod: "POST", + uploadType: 0, + headers: { "Content-Type": "application/pdf" }, + }), + ); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments[0]).toEqual({ + type: "file", + id: MINTED_ID, + name: "report.pdf", + mimeType: "application/pdf", + sizeBytes: 42, + source: { _tag: "pasted-text" }, + }); + expect(prepared.attachments[1]?.type).toBe("image"); + expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]); + expect(prepared.draftAttachments[0]).toEqual({ + ...pastedFile, + uploadedAttachmentId: MINTED_ID, + uploadEnvironmentId: environmentId, + }); + }), + ); - it("uses the current connection when an environment reconnects during URL creation", async () => { - mocks.readAtom - .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" })) - .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" })); + it.effect("uses the current connection when an environment reconnects during URL creation", () => + Effect.gen(function* () { + mocks.readAtom + .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" })) + .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" })); - await prepareTurnAttachments({ environmentId, attachments: [file] }); + yield* prepare({ environmentId, attachments: [file] }); - expect(mocks.upload).toHaveBeenCalledWith( - file.fileUri, - "https://new-environment.example/api/attachments/upload/signed", - expect.anything(), - ); - }); + expect(mocks.upload).toHaveBeenCalledWith( + file.fileUri, + "https://new-environment.example/api/attachments/upload/signed", + expect.anything(), + ); + }), + ); - it("uploads a restored draft file from the current iOS document container", async () => { - const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf"; - const restoredFile = { - ...file, - fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`, - }; - mocks.documentUri = - "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents"; - const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`; - mocks.upload.mockImplementation(async (uri: string) => { - if (uri !== currentUri) { - throw new Error("File does not exist in the previous application container."); - } - return { status: 204, body: "", headers: {} }; - }); + it.effect("uploads a restored draft file from the current iOS document container", () => + Effect.gen(function* () { + const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf"; + const restoredFile = { + ...file, + fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`, + }; + mocks.documentUri = + "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents"; + const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`; + mocks.upload.mockImplementation(async (uri: string) => { + if (uri !== currentUri) { + throw new Error("File does not exist in the previous application container."); + } + return { status: 204, body: "", headers: {} }; + }); - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [restoredFile], - }); + const prepared = yield* prepare({ + environmentId, + attachments: [restoredFile], + }); - expect(prepared.status).toBe("ready"); - expect(mocks.upload).toHaveBeenCalledWith( - currentUri, - "https://environment.example/api/attachments/upload/signed", - expect.anything(), - ); - }); + expect(prepared.status).toBe("ready"); + expect(mocks.upload).toHaveBeenCalledWith( + currentUri, + "https://environment.example/api/attachments/upload/signed", + expect.anything(), + ); + }), + ); it("adds uploaded file references to durable drafts without changing images", () => { expect( @@ -533,215 +585,219 @@ describe("prepareTurnAttachments", () => { ]); }); - it("reuses a pending file upload from a previous outbox attempt", async () => { - const previouslyUploaded = { - ...file, - uploadedAttachmentId: "pending-existing-pdf", - uploadEnvironmentId: environmentId, - }; - - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [previouslyUploaded, image], - }); + it.effect("reuses a pending file upload from a previous outbox attempt", () => + Effect.gen(function* () { + const previouslyUploaded = { + ...file, + uploadedAttachmentId: "pending-existing-pdf", + uploadEnvironmentId: environmentId, + }; - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments).toEqual([ - { - type: "file", - id: "pending-existing-pdf", - name: "report.pdf", - mimeType: "application/pdf", - sizeBytes: 42, - }, - { - type: "image", - name: "screenshot.png", - mimeType: "image/png", - sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - }, - ]); - expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]); - expect(mocks.upload).not.toHaveBeenCalled(); - expect(mocks.runAtomCommand).not.toHaveBeenCalled(); - }); + const prepared = yield* prepare({ + environmentId, + attachments: [previouslyUploaded, image], + }); - it("uploads a file again when its saved pending upload has expired", async () => { - mocks.executeAtomQuery.mockResolvedValueOnce({ - _tag: "Failure", - error: { _tag: "AssetAttachmentNotFoundError" }, - }); - const previouslyUploaded = { - ...file, - uploadedAttachmentId: "pending-expired-pdf", - uploadEnvironmentId: environmentId, - }; - - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [previouslyUploaded], - }); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments).toEqual([ + { + type: "file", + id: "pending-existing-pdf", + name: "report.pdf", + mimeType: "application/pdf", + sizeBytes: 42, + }, + { + type: "image", + name: "screenshot.png", + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + }, + ]); + expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]); + expect(mocks.upload).not.toHaveBeenCalled(); + expect(mocks.runAtomCommand).not.toHaveBeenCalled(); + }), + ); - expect(mocks.upload).toHaveBeenCalledOnce(); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]); - }); + it.effect("uploads a file again when its saved pending upload has expired", () => + Effect.gen(function* () { + mocks.executeAtomQuery.mockResolvedValueOnce({ + _tag: "Failure", + error: { _tag: "AssetAttachmentNotFoundError" }, + }); + const previouslyUploaded = { + ...file, + uploadedAttachmentId: "pending-expired-pdf", + uploadEnvironmentId: environmentId, + }; - it("uploads image bytes over HTTP while retaining the durable offline image", async () => { - const persisted = vi.fn(async () => "persisted" as const); - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [image], - supportsImageUploads: true, - persistUploadedReferences: persisted, - }); - expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", { - encoding: "base64", - }); - expect(mocks.upload).toHaveBeenCalledWith( - "file:///cache/t3-upload-uuid", - "https://environment.example/api/attachments/upload/signed", - expect.objectContaining({ headers: { "Content-Type": "image/png" } }), - ); - expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid"); - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments).toEqual([ - { - type: "image", - id: MINTED_ID, - name: image.name, - mimeType: image.mimeType, - sizeBytes: image.sizeBytes, - }, - ]); - expect(prepared.draftAttachments).toEqual([ - { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId }, - ]); - expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments); - }); + const prepared = yield* prepare({ + environmentId, + attachments: [previouslyUploaded], + }); - it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => { - const saved = { - ...image, - uploadedAttachmentId: "saved-image", - uploadEnvironmentId: environmentId, - }; - const reused = await prepareTurnAttachments({ - environmentId, - attachments: [saved], - supportsImageUploads: true, - }); - expect(reused.status === "ready" && reused.attachments[0]).toEqual({ - type: "image", - id: "saved-image", - name: image.name, - mimeType: image.mimeType, - sizeBytes: image.sizeBytes, - }); - expect(mocks.upload).not.toHaveBeenCalled(); - mocks.executeAtomQuery.mockResolvedValueOnce({ - _tag: "Failure", - error: { _tag: "AssetAttachmentNotFoundError" }, - }); - const restored = await prepareTurnAttachments({ - environmentId, - attachments: [saved], - supportsImageUploads: true, - }); - expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({ - ...saved, - uploadedAttachmentId: MINTED_ID, - }); - expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", { - encoding: "base64", - }); - }); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]); + }), + ); - it("does not reuse an image upload from another environment", async () => { - const prepared = await prepareTurnAttachments({ - environmentId, - attachments: [ + it.effect("uploads image bytes over HTTP while retaining the durable offline image", () => + Effect.gen(function* () { + const persisted = vi.fn(() => Effect.succeed("persisted" as const)); + const prepared = yield* prepare({ + environmentId, + attachments: [image], + supportsImageUploads: true, + persistUploadedReferences: persisted, + }); + expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", { + encoding: "base64", + }); + expect(mocks.upload).toHaveBeenCalledWith( + "file:///cache/t3-upload-uuid", + "https://environment.example/api/attachments/upload/signed", + expect.objectContaining({ headers: { "Content-Type": "image/png" } }), + ); + expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid"); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments).toEqual([ { - ...image, - uploadedAttachmentId: "other-image", - uploadEnvironmentId: EnvironmentId.make("other"), + type: "image", + id: MINTED_ID, + name: image.name, + mimeType: image.mimeType, + sizeBytes: image.sizeBytes, }, - ], - supportsImageUploads: true, - }); - expect(mocks.executeAtomQuery).not.toHaveBeenCalled(); - expect(mocks.upload).toHaveBeenCalledOnce(); - expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe( - environmentId, - ); - }); + ]); + expect(prepared.draftAttachments).toEqual([ + { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId }, + ]); + expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments); + }), + ); - it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => { - const started = Promise.withResolvers(); - const controller = new AbortController(); - const persist = vi.fn(async () => "persisted" as const); - mocks.upload.mockImplementation( - (_uri: string, _url: string, options: { signal: AbortSignal }) => - new Promise((_, reject) => { - options.signal.addEventListener("abort", () => reject(new Error("cancelled")), { - once: true, - }); - started.resolve(); - }), - ); - const preparing = prepareTurnAttachments({ - environmentId, - attachments: [file], - signal: controller.signal, - persistUploadedReferences: persist, - }); - await started.promise; - controller.abort(); - expect(await preparing).toEqual({ status: "abandoned" }); - expect(persist).not.toHaveBeenCalled(); - expect(mocks.deleteFile).not.toHaveBeenCalled(); - expect(removeCallsFor(MINTED_ID)).toBe(1); - }); + it.effect("reuses an uploaded image and reuploads its local bytes after server expiry", () => + Effect.gen(function* () { + const saved = { + ...image, + uploadedAttachmentId: "saved-image", + uploadEnvironmentId: environmentId, + }; + const reused = yield* prepare({ + environmentId, + attachments: [saved], + supportsImageUploads: true, + }); + expect(reused.status === "ready" && reused.attachments[0]).toEqual({ + type: "image", + id: "saved-image", + name: image.name, + mimeType: image.mimeType, + sizeBytes: image.sizeBytes, + }); + expect(mocks.upload).not.toHaveBeenCalled(); + mocks.executeAtomQuery.mockResolvedValueOnce({ + _tag: "Failure", + error: { _tag: "AssetAttachmentNotFoundError" }, + }); + const restored = yield* prepare({ + environmentId, + attachments: [saved], + supportsImageUploads: true, + }); + expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({ + ...saved, + uploadedAttachmentId: MINTED_ID, + }); + expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", { + encoding: "base64", + }); + }), + ); - it("removes pending uploads when the native HTTP request fails", async () => { - mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} }); + it.effect("does not reuse an image upload from another environment", () => + Effect.gen(function* () { + const prepared = yield* prepare({ + environmentId, + attachments: [ + { + ...image, + uploadedAttachmentId: "other-image", + uploadEnvironmentId: EnvironmentId.make("other"), + }, + ], + supportsImageUploads: true, + }); + expect(mocks.executeAtomQuery).not.toHaveBeenCalled(); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe( + environmentId, + ); + }), + ); - await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow( - "Upload failed for 'report.pdf' (500).", - ); - expect(removeCallsFor(MINTED_ID)).toBe(1); - }); + it.effect( + "aborts an active transfer without dropping local bytes or stamping a partial upload", + () => + Effect.gen(function* () { + const started = Promise.withResolvers(); + const persist = vi.fn(() => Effect.succeed("persisted" as const)); + mocks.upload.mockImplementation( + (_uri: string, _url: string, options: { signal: AbortSignal }) => + new Promise((_, reject) => { + options.signal.addEventListener("abort", () => reject(new Error("cancelled")), { + once: true, + }); + started.resolve(); + }), + ); + const preparing = yield* Effect.forkChild( + prepare({ environmentId, attachments: [file], persistUploadedReferences: persist }), + ); + yield* Effect.promise(() => started.promise); + yield* Fiber.interrupt(preparing); + expect(Exit.hasInterrupts(yield* Fiber.await(preparing))).toBe(true); + expect(persist).not.toHaveBeenCalled(); + expect(mocks.deleteFile).not.toHaveBeenCalled(); + expect(removeCallsFor(MINTED_ID)).toBe(1); + }), + ); - it("keeps a previously persisted upload when a later attachment fails", async () => { - const previouslyUploaded = { - ...file, - id: "file-existing", - uploadedAttachmentId: "pending-existing-pdf", - uploadEnvironmentId: environmentId, - }; - mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} }); + it.effect("removes pending uploads when the native HTTP request fails", () => + Effect.gen(function* () { + mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} }); - await expect( - prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }), - ).rejects.toThrow("Upload failed for 'report.pdf' (500)."); + expect( + (yield* Effect.flip(prepare({ environmentId, attachments: [file] }))).message, + ).toContain("Upload failed for 'report.pdf' (500)."); + expect(removeCallsFor(MINTED_ID)).toBe(1); + }), + ); - expect(removeCallsFor("pending-existing-pdf")).toBe(0); - }); + it.effect("keeps a previously persisted upload when a later attachment fails", () => + Effect.gen(function* () { + const previouslyUploaded = { + ...file, + id: "file-existing", + uploadedAttachmentId: "pending-existing-pdf", + uploadEnvironmentId: environmentId, + }; + mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} }); - it("deletes the minted uploads when the owner abandons the send", async () => { - const result = await prepareTurnAttachments({ - environmentId, - attachments: [file], - persistUploadedReferences: async () => "abandon", - }); + expect( + (yield* Effect.flip(prepare({ environmentId, attachments: [previouslyUploaded, file] }))) + .message, + ).toContain("Upload failed for 'report.pdf' (500)."); - expect(result.status).toBe("abandoned"); - expect(removeCallsFor(MINTED_ID)).toBe(1); - }); + expect(removeCallsFor("pending-existing-pdf")).toBe(0); + }), + ); }); describe("releasePendingAttachmentUploads", () => { diff --git a/apps/mobile/src/lib/attachmentUpload.ts b/apps/mobile/src/lib/attachmentUpload.ts index 57699af22819e..ab102a059934e 100644 --- a/apps/mobile/src/lib/attachmentUpload.ts +++ b/apps/mobile/src/lib/attachmentUpload.ts @@ -15,6 +15,7 @@ import { AuthOrchestrationOperateScope, PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES, } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { appAtomRegistry } from "../state/atom-registry"; @@ -31,6 +32,10 @@ import { } from "./composerImages"; import { imageMimeType } from "@t3tools/shared/image"; import { uuidv4 } from "./uuid"; +import { + attachmentUploadError, + type AttachmentUploadError, +} from "@t3tools/client-runtime/state/attachment-uploads"; export type UploadedMobileAttachment = | UploadChatImageAttachment @@ -248,159 +253,164 @@ async function uploadFileBytes( } } -/** persistUploadedReferences runs only for new uploaded ids; save them to their owner so crash retries reuse bytes. */ -export async function prepareTurnAttachments(input: { +function requireUploadAccess(environmentId: EnvironmentId): void { + if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { + throw new Error("This connection cannot upload attachments."); + } +} + +/** + * Uploads one attachment and returns its uploaded id, reusing an earlier upload the server + * still has. Interrupting it aborts the native transfer and deletes the pending upload it minted; + * a failed transfer deletes it too. + */ +export const uploadComposerAttachment = Effect.fn("uploadComposerAttachment")(function* ( + environmentId: EnvironmentId, + attachment: DraftComposerAttachment, + onProgress?: (progress: number) => void, +) { + yield* Effect.try({ + try: () => requireUploadAccess(environmentId), + catch: attachmentUploadError, + }); + if ( + attachment.uploadEnvironmentId === environmentId && + attachment.uploadedAttachmentId !== undefined + ) { + const verification = yield* verifyPersistedAttachmentUpload({ + registry: appAtomRegistry, + createAssetUrl: assetEnvironment.createUrl, + environmentId, + attachmentId: attachment.uploadedAttachmentId, + }); + if (verification.status === "failed") { + return yield* attachmentUploadError(verification.error); + } + if (verification.status === "verified") return attachment.uploadedAttachmentId; + } + yield* Effect.try({ + try: () => requireUploadAccess(environmentId), + catch: attachmentUploadError, + }); + if ( + Option.isNone( + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)), + ) + ) { + return yield* attachmentUploadError(new Error("The environment is not connected.")); + } + const result = yield* runAttachmentUploadCycle({ + registry: appAtomRegistry, + createUploadUrl: attachmentEnvironment.createUploadUrl, + remove: attachmentEnvironment.remove, + environmentId, + upload: attachmentUploadInput(attachment), + // Resolve at transfer time; reconnects may change the base URL. + resolveUploadUrl: (relativeUrl) => { + if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return null; + const connection = appAtomRegistry.get( + environmentSession.preparedConnectionValueAtom(environmentId), + ); + return Option.isNone(connection) + ? null + : resolveAssetUrl(connection.value.httpBaseUrl, relativeUrl); + }, + transport: (url) => + Effect.tryPromise({ + try: (signal) => uploadFileBytes(environmentId, attachment, url, signal, onProgress), + catch: attachmentUploadError, + }), + }); + if (result.status === "uploaded") return result.attachmentId; + if (result.attachmentId !== null) { + yield* Effect.promise(() => + releaseCreatedUploadsQuietly(environmentId, [result.attachmentId!]), + ); + } + return yield* attachmentUploadError( + result.step === "resolve-url" && + !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) + ? new Error("This connection cannot upload attachments.") + : result.error instanceof Error + ? result.error + : new Error(`Upload failed for '${attachment.name}'.`), + ); +}); + +/** + * Turns a message's attachments into wire references. `uploadAttachment` is the shared upload + * registry, so a send joins an upload the composer already started; interrupting this stops + * waiting without cancelling that shared upload. persistUploadedReferences runs only for new + * uploaded ids; save them to their owner so crash retries reuse bytes. + */ +export const prepareTurnAttachments = Effect.fn("prepareTurnAttachments")(function* (input: { readonly environmentId: EnvironmentId; readonly attachments: ReadonlyArray; readonly supportsImageUploads?: boolean; - readonly signal?: AbortSignal; - readonly onUploadProgress?: (attachmentId: string, progress: number) => void; + readonly uploadAttachment: ( + attachment: DraftComposerAttachment, + ) => Effect.Effect; readonly persistUploadedReferences?: ( draftAttachments: ReadonlyArray, - ) => Promise<"persisted" | "abandon">; -}): Promise { + ) => Effect.Effect<"persisted" | "abandon">; +}) { const { environmentId } = input; - if (input.signal?.aborted) return { status: "abandoned" }; + const inlineImages = (attachments: ReadonlyArray) => + Effect.tryPromise({ + try: () => + toUploadChatImageAttachments( + attachments.filter( + (attachment): attachment is DraftComposerImageAttachment => attachment.type === "image", + ), + ), + catch: attachmentUploadError, + }); const files = input.attachments.filter((attachment) => attachment.type === "file"); - const ready = ( - attachments: ReadonlyArray, - pendingAttachmentIds: ReadonlyArray, - draftAttachments: ReadonlyArray, - ): PreparedTurnAttachments => ({ - status: "ready", - attachments, - draftAttachments, - pendingAttachmentIds, - }); - if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) { - try { - const imageAttachments = await toUploadChatImageAttachments( - input.attachments.filter((attachment) => attachment.type === "image"), - ); - if (input.signal?.aborted) return { status: "abandoned" }; - return ready(imageAttachments, [], input.attachments); - } catch (error) { - if (input.signal?.aborted) return { status: "abandoned" }; - throw error; - } - } - - const requireUploadAccess = () => { - if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { - throw new Error("This connection cannot upload attachments."); - } - }; - requireUploadAccess(); - - const connection = appAtomRegistry.get( - environmentSession.preparedConnectionValueAtom(environmentId), - ); - if (Option.isNone(connection)) { - throw new Error("The environment is not connected."); + const imageAttachments = yield* inlineImages(input.attachments); + return { + status: "ready", + attachments: imageAttachments, + draftAttachments: input.attachments, + pendingAttachmentIds: [], + } satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult; } + yield* Effect.try({ + try: () => requireUploadAccess(environmentId), + catch: attachmentUploadError, + }); const uploadedAttachments: UploadedMobileAttachment[] = []; const pendingAttachmentIds: string[] = []; - const createdAttachmentIds: string[] = []; - const controller = new AbortController(); - const abort = () => controller.abort(); - input.signal?.addEventListener("abort", abort, { once: true }); - try { - for (const attachment of input.attachments) { - if (controller.signal.aborted) throw new Error("Upload cancelled."); - requireUploadAccess(); - if (attachment.type === "image" && !input.supportsImageUploads) { - uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment]))); - continue; - } - - if ( - attachment.uploadEnvironmentId === environmentId && - attachment.uploadedAttachmentId !== undefined - ) { - const verification = await verifyPersistedAttachmentUpload({ - registry: appAtomRegistry, - createAssetUrl: assetEnvironment.createUrl, - environmentId, - attachmentId: attachment.uploadedAttachmentId, - }); - if (verification.status === "failed") { - throw verification.error; - } - if (verification.status === "verified") { - pendingAttachmentIds.push(attachment.uploadedAttachmentId); - uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId)); - continue; - } - } - - requireUploadAccess(); - const result = await runAttachmentUploadCycle({ - registry: appAtomRegistry, - createUploadUrl: attachmentEnvironment.createUploadUrl, - remove: attachmentEnvironment.remove, - environmentId, - upload: attachmentUploadInput(attachment), - // Resolve at transfer time; reconnects may change the base URL. - resolveUploadUrl: (relativeUrl) => { - requireUploadAccess(); - const currentConnection = appAtomRegistry.get( - environmentSession.preparedConnectionValueAtom(environmentId), - ); - return Option.isNone(currentConnection) - ? null - : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl); - }, - transport: (url) => ({ - done: uploadFileBytes( - environmentId, - attachment, - url, - controller.signal, - input.onUploadProgress - ? (progress) => input.onUploadProgress?.(attachment.id, progress) - : undefined, - ), - abort, - }), - onMinted: (attachmentId) => { - if (controller.signal.aborted) return "cancel"; - pendingAttachmentIds.push(attachmentId); - createdAttachmentIds.push(attachmentId); - return "continue"; - }, - }); - if (result.status !== "uploaded") { - throw result.status === "failed" && result.error !== undefined - ? result.error - : new Error(`Upload failed for '${attachment.name}'.`); - } - uploadedAttachments.push(uploadedReference(attachment, result.attachmentId)); + for (const attachment of input.attachments) { + if (attachment.type === "image" && !input.supportsImageUploads) { + uploadedAttachments.push(...(yield* inlineImages([attachment]))); + continue; } + const uploadedId = yield* input.uploadAttachment(attachment); + pendingAttachmentIds.push(uploadedId); + uploadedAttachments.push(uploadedReference(attachment, uploadedId)); + } - if (controller.signal.aborted) throw new Error("Upload cancelled."); - - const draftAttachments = withUploadedMobileAttachmentReferences({ - environmentId, - attachments: input.attachments, - uploadedAttachments, - }); - const referencesChanged = draftAttachments.some( - (attachment, index) => attachment !== input.attachments[index], - ); - if (referencesChanged && input.persistUploadedReferences) { - if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") { - await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds); - return { status: "abandoned" }; - } - } - return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments); - } catch (error) { - await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds); - if (controller.signal.aborted) return { status: "abandoned" }; - throw error; - } finally { - input.signal?.removeEventListener("abort", abort); + const draftAttachments = withUploadedMobileAttachmentReferences({ + environmentId, + attachments: input.attachments, + uploadedAttachments, + }); + const referencesChanged = draftAttachments.some( + (attachment, index) => attachment !== input.attachments[index], + ); + if ( + referencesChanged && + input.persistUploadedReferences && + (yield* input.persistUploadedReferences(draftAttachments)) === "abandon" + ) { + return { status: "abandoned" } as PrepareTurnAttachmentsResult; } -} + return { + status: "ready", + attachments: uploadedAttachments, + draftAttachments, + pendingAttachmentIds, + } satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult; +}); diff --git a/apps/mobile/src/lib/composerAttachmentUploadQueue.test.ts b/apps/mobile/src/lib/composerAttachmentUploadQueue.test.ts index 6de39c413d49e..cfff340939a65 100644 --- a/apps/mobile/src/lib/composerAttachmentUploadQueue.test.ts +++ b/apps/mobile/src/lib/composerAttachmentUploadQueue.test.ts @@ -1,5 +1,6 @@ import { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; import { questionAttachmentDraftKey, questionAttachmentDraftPrefix, @@ -11,9 +12,7 @@ import { composerAttachmentsStillUploading, composerAttachmentUploadKey, composerDraftEnvironmentId, - createComposerAttachmentUploadQueue, type ComposerAttachmentUploadRequest, - type ComposerAttachmentUploadState, } from "./composerAttachmentUploadQueue"; const environmentId = EnvironmentId.make("environment-1"); @@ -31,221 +30,6 @@ function request(id: string, environment = environmentId): ComposerAttachmentUpl }; } -describe("composer attachment upload queue", () => { - it("bounds concurrency, deduplicates updates, and drains all attachments", async () => { - const gates = new Map>>(); - const fourthStarted = Promise.withResolvers(); - const firstThreeStarted = Promise.withResolvers(); - let active = 0; - let maximum = 0; - const upload = vi.fn(async (input: ComposerAttachmentUploadRequest) => { - active += 1; - maximum = Math.max(maximum, active); - const gate = Promise.withResolvers(); - gates.set(input.attachment.id, gate); - if (gates.size === 3) firstThreeStarted.resolve(); - if (gates.size === 4) fourthStarted.resolve(); - try { - return await gate.promise; - } finally { - active -= 1; - } - }); - const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} }); - const requests = [request("one"), request("two"), request("three"), request("four")]; - queue.sync(requests); - queue.sync(requests); - await firstThreeStarted.promise; - expect(upload).toHaveBeenCalledTimes(3); - gates.get("one")!.resolve(true); - await fourthStarted.promise; - for (const gate of gates.values()) gate.resolve(true); - await queue.settled(); - queue.sync(requests); - await queue.settled(); - expect(maximum).toBe(3); - expect(upload).toHaveBeenCalledTimes(4); - queue.dispose(); - }); - - it("cancels on disconnect and resumes from the same local draft on reconnect", async () => { - const started = Promise.withResolvers(); - let states: Readonly> = {}; - let signal: AbortSignal | undefined; - const upload = vi.fn( - async (_request: ComposerAttachmentUploadRequest, currentSignal: AbortSignal) => { - signal = currentSignal; - started.resolve(); - return new Promise((resolve) => - currentSignal.addEventListener("abort", () => resolve(false), { once: true }), - ); - }, - ); - const queue = createComposerAttachmentUploadQueue({ - upload, - onChange: (next) => { - states = next; - }, - }); - const local = request("offline-draft"); - queue.sync([local]); - await started.promise; - queue.sync([]); - await queue.settled(); - expect(signal?.aborted).toBe(true); - expect(states).toEqual({}); - upload.mockResolvedValueOnce(true); - queue.sync([local]); - await queue.settled(); - expect(upload.mock.calls[1]?.[0]).toBe(local); - expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({ - status: "ready", - }); - expect(local.attachment).toMatchObject({ fileUri: "file:///documents/offline-draft.pdf" }); - queue.dispose(); - }); - - it("retries a failed attachment when the worker restores requests after reconnect", async () => { - let states: Readonly> = {}; - const upload = vi.fn().mockRejectedValueOnce(new Error("Disconnected")).mockResolvedValue(true); - const queue = createComposerAttachmentUploadQueue({ - upload, - onChange: (next) => { - states = next; - }, - }); - const local = request("failed-upload"); - const key = composerAttachmentUploadKey(environmentId, local.attachment.id); - queue.sync([local]); - await queue.settled(); - expect(states[key]?.status).toBe("failed"); - queue.sync([local]); - await queue.settled(); - expect(upload).toHaveBeenCalledTimes(1); - queue.sync([]); - queue.sync([local]); - await queue.settled(); - expect(upload).toHaveBeenCalledTimes(2); - expect(states[key]?.status).toBe("ready"); - queue.dispose(); - }); - - it("ignores a late completion after removal or environment switch", async () => { - const gate = Promise.withResolvers(); - const started = Promise.withResolvers(); - let states: Readonly> = {}; - const upload = vi.fn(async () => { - started.resolve(); - return gate.promise; - }); - const queue = createComposerAttachmentUploadQueue({ - upload, - onChange: (next) => { - states = next; - }, - }); - queue.sync([request("photo")]); - await started.promise; - upload.mockResolvedValueOnce(true); - const other = EnvironmentId.make("environment-2"); - queue.sync([request("photo", other)]); - gate.resolve(true); - await queue.settled(); - expect(states).toEqual({ [composerAttachmentUploadKey(other, "photo")]: { status: "ready" } }); - queue.sync([]); - expect(states).toEqual({}); - queue.dispose(); - }); - - it("restarts a re-added attachment after its aborted transfer finishes settling", async () => { - const firstStarted = Promise.withResolvers(); - const firstSettled = Promise.withResolvers(); - const secondStarted = Promise.withResolvers(); - const secondSettled = Promise.withResolvers(); - let states: Readonly> = {}; - let firstSignal: AbortSignal | undefined; - const upload = vi.fn(async (_request: ComposerAttachmentUploadRequest, signal: AbortSignal) => { - if (!firstSignal) { - firstSignal = signal; - firstStarted.resolve(); - return firstSettled.promise; - } - secondStarted.resolve(); - return secondSettled.promise; - }); - const queue = createComposerAttachmentUploadQueue({ - upload, - onChange: (next) => { - states = next; - }, - }); - const local = request("re-added"); - queue.sync([local]); - await firstStarted.promise; - queue.sync([]); - queue.sync([local]); - expect(firstSignal?.aborted).toBe(true); - expect(upload).toHaveBeenCalledOnce(); - firstSettled.resolve(false); - await secondStarted.promise; - expect(upload).toHaveBeenCalledTimes(2); - secondSettled.resolve(true); - await queue.settled(); - expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({ - status: "ready", - }); - queue.dispose(); - }); - - it("keeps failures stable until retry and reports bounded progress", async () => { - let states: Readonly> = {}; - const progress: number[] = []; - const upload = vi.fn( - async ( - _request: ComposerAttachmentUploadRequest, - _signal: AbortSignal, - report: (value: number) => void, - ): Promise => { - report(0.12); - report(0.13); - report(1.1); - throw new Error("Server unavailable"); - }, - ); - const queue = createComposerAttachmentUploadQueue({ - upload, - onChange: (next) => { - states = next; - const state = next[composerAttachmentUploadKey(environmentId, "file")]; - if (state?.status === "uploading") progress.push(state.progress); - }, - }); - queue.sync([request("file")]); - await queue.settled(); - queue.sync([request("file")]); - expect(upload).toHaveBeenCalledOnce(); - expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({ - status: "failed", - reason: "Server unavailable", - }); - expect(progress).toEqual([0, 0.1, 1]); - upload.mockImplementationOnce(async () => true); - queue.retry(environmentId, "file"); - await queue.settled(); - expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({ status: "ready" }); - queue.dispose(); - }); - - it("does not spin when an upload's draft was abandoned before persistence", async () => { - const upload = vi.fn(async () => false); - const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} }); - queue.sync([request("discarded")]); - await queue.settled(); - expect(upload).toHaveBeenCalledOnce(); - queue.dispose(); - }); -}); - describe("draft upload scope and offline submission", () => { it("uploads question drafts in their environment without matching other thread prefixes", () => { const requestId = ApprovalRequestId.make("request:1"); diff --git a/apps/mobile/src/lib/composerAttachmentUploadQueue.ts b/apps/mobile/src/lib/composerAttachmentUploadQueue.ts index 0a28fff2231d5..7c0e56dae08de 100644 --- a/apps/mobile/src/lib/composerAttachmentUploadQueue.ts +++ b/apps/mobile/src/lib/composerAttachmentUploadQueue.ts @@ -1,5 +1,6 @@ import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments"; +import type { AttachmentUploadStatus } from "@t3tools/client-runtime/state/attachment-uploads"; import { parseLegacyNewTaskDraftKey } from "../state/new-task-draft-key"; import type { DraftComposerAttachment } from "./composerImages"; @@ -9,10 +10,7 @@ export interface ComposerAttachmentUploadRequest { readonly attachment: DraftComposerAttachment; } -export type ComposerAttachmentUploadState = - | { readonly status: "uploading"; readonly progress: number } - | { readonly status: "ready" } - | { readonly status: "failed"; readonly reason: string }; +export type ComposerAttachmentUploadState = AttachmentUploadStatus; export function composerAttachmentUploadKey( environmentId: EnvironmentId, @@ -104,139 +102,3 @@ export function composerAttachmentsStillUploading(input: { return state?.status !== "ready" && state?.status !== "failed"; }); } - -/** Changes when an upload starts or settles, not on its progress ticks. */ -export function uploadingComposerAttachmentKeys( - states: Readonly>, -): string { - return Object.keys(states) - .filter((key) => states[key]?.status === "uploading") - .sort() - .join("\n"); -} - -/** A queued message waits for the worker's upload instead of starting a second one. */ -export function queuedAttachmentsStillUploading(input: { - readonly environmentId: EnvironmentId; - readonly attachments: ReadonlyArray; - readonly states: Readonly>; -}): boolean { - return input.attachments.some( - (attachment) => - attachment.uploadedAttachmentId === undefined && - input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)]?.status === - "uploading", - ); -} - -export function createComposerAttachmentUploadQueue(options: { - readonly upload: ( - request: ComposerAttachmentUploadRequest, - signal: AbortSignal, - onProgress: (progress: number) => void, - ) => Promise; - readonly onChange: (states: Readonly>) => void; -}) { - const jobs = new Map< - string, - { readonly controller: AbortController; readonly done: Promise } - >(); - let desired = new Map(); - let states: Readonly> = {}; - let disposed = false; - - function setState(key: string, state: ComposerAttachmentUploadState | undefined) { - const previous = states[key]; - if ( - previous === state || - (previous?.status === "uploading" && - state?.status === "uploading" && - previous.progress === state.progress) - ) - return; - const next = { ...states }; - if (state) next[key] = state; - else delete next[key]; - states = next; - options.onChange(states); - } - - function pump() { - if (disposed) return; - for (const [key, request] of desired) { - if (jobs.size >= 3) break; - if (jobs.has(key) || states[key]?.status === "ready" || states[key]?.status === "failed") - continue; - const controller = new AbortController(); - setState(key, { status: "uploading", progress: 0 }); - // Publish the job before starting async work, including synchronous test transports. - const done = Promise.resolve() - .then(() => - options.upload(request, controller.signal, (progress) => { - if (controller.signal.aborted) return; - setState(key, { - status: "uploading", - progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20, - }); - }), - ) - .then((persisted) => { - if (!controller.signal.aborted && desired.has(key)) { - if (!persisted) desired.delete(key); - setState(key, persisted ? { status: "ready" } : undefined); - } - }) - .catch((error: unknown) => { - if (!controller.signal.aborted && desired.has(key)) { - setState(key, { - status: "failed", - reason: error instanceof Error ? error.message : "Upload failed. Tap to retry.", - }); - } - }) - .finally(() => { - jobs.delete(key); - pump(); - }); - jobs.set(key, { controller, done }); - } - } - - return { - sync(requests: ReadonlyArray) { - if (disposed) return; - desired = new Map( - requests.map((request) => [ - composerAttachmentUploadKey(request.environmentId, request.attachment.id), - request, - ]), - ); - for (const [key, job] of jobs) { - if (!desired.has(key)) job.controller.abort(); - } - for (const key of Object.keys(states)) { - if (!desired.has(key)) setState(key, undefined); - } - for (const key of desired.keys()) { - if (!states[key]) setState(key, { status: "uploading", progress: 0 }); - } - pump(); - }, - retry(environmentId: EnvironmentId, attachmentId: string) { - const key = composerAttachmentUploadKey(environmentId, attachmentId); - if (states[key]?.status !== "failed") return; - setState(key, undefined); - pump(); - }, - async settled() { - while (jobs.size > 0) await Promise.all([...jobs.values()].map((job) => job.done)); - }, - dispose() { - disposed = true; - desired.clear(); - for (const job of jobs.values()) job.controller.abort(); - states = {}; - options.onChange(states); - }, - }; -} diff --git a/apps/mobile/src/lib/composerContextClipboard.test.ts b/apps/mobile/src/lib/composerContextClipboard.test.ts index 77305cce84439..41cdcf3078bce 100644 --- a/apps/mobile/src/lib/composerContextClipboard.test.ts +++ b/apps/mobile/src/lib/composerContextClipboard.test.ts @@ -73,6 +73,13 @@ const image = { mimeType: "image/png", sizeBytes: 7, attachmentId: "source-file", + source: { + kind: "snap-shot" as const, + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, }; const terminal = { version: 1 as const, @@ -146,7 +153,11 @@ describe("mobile context clipboard imports", () => { const signal = { aborted: false } as AbortSignal; const result = await importComposerContextClipboard(clipboard, 0, signal); expect(result?.failures).toEqual([]); - expect(result?.attachments[0]).toMatchObject({ fileUri: "file:///owned.png", sizeBytes: 42 }); + expect(result?.attachments[0]).toMatchObject({ + fileUri: "file:///owned.png", + sizeBytes: 42, + source: image.source, + }); expect(result?.context.records[0]).toMatchObject({ contextId: "import-1", attachmentId: result?.attachments[0]?.id, diff --git a/apps/mobile/src/lib/composerContextClipboard.ts b/apps/mobile/src/lib/composerContextClipboard.ts index 8c5a31cdb7e44..e744a2cbbf96a 100644 --- a/apps/mobile/src/lib/composerContextClipboard.ts +++ b/apps/mobile/src/lib/composerContextClipboard.ts @@ -253,6 +253,11 @@ async function persistImportedAttachment( sizeBytes: new File(fileUri).size, }; return record.kind === "image" - ? { ...common, type: "image", previewUri: fileUri } + ? { + ...common, + type: "image", + previewUri: fileUri, + ...(record.source ? { source: record.source } : {}), + } : { ...common, type: "file" }; } diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index ddeca4b2d2103..55e8c09394387 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -3,7 +3,11 @@ import { unified, type Processor } from "unified"; import remarkParse from "remark-parse"; import remarkGfm from "remark-gfm"; import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths"; -import { absoluteFilePathMatches, parseMarkdownFileLink } from "@t3tools/shared/markdownLinks"; +import { + absoluteFilePathMatches, + inlineCodeFilePathCandidate, + parseMarkdownFileLink, +} from "@t3tools/shared/markdownLinks"; import { isWindowsAbsolutePath } from "@t3tools/shared/path"; const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths); @@ -322,6 +326,11 @@ export function withReferenceDefinitions( // Start only at the beginning of a backtick run to avoid retrying every suffix. const INLINE_CODE_SPAN = /(?]/.test(node.value) ) { diff --git a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts index 3de6590dc7a4b..465afe21f34a2 100644 --- a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts +++ b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts @@ -99,13 +99,16 @@ describe("inline code that names a file", () => { "數學.ts:2", "src/數學.ts:2-4", "docker/Dockerfile", + "/Users/me/Path Test/notes with spaces.md", + "~/Library/Mobile Documents/notes.md", ]) { expect(rewrite(`See \`${path}\`.`), path).toBe(`See [${path}](<${path}>).`); } }); it("keeps commands, identifiers and URLs as code", () => { - const markdown = "Run `vp test run`, call `useMemo`, open `https://example.com/a.ts`."; + const markdown = + "Run `vp test run`, `/usr/bin/python3 -m venv .venv`, call `useMemo`, open `https://example.com/a.ts`."; expect(rewrite(markdown)).toBe(markdown); }); diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index cfc228a982339..175ef5b4bab3c 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1328,24 +1328,24 @@ describe("buildThreadFeed", () => { "assistant:resume-answer", ]); - expect( - shape( - deriveThreadFeedPresentation( - feed(true), - null, - new Set(), - new Set(), - "2026-06-20T00:01:12.000Z", - true, - ), - ), - ).toEqual([ + const working = deriveThreadFeedPresentation( + feed(true), + null, + new Set(), + new Set(), + "2026-06-20T00:01:12.000Z", + true, + ); + expect(shape(working)).toEqual([ "user:launch", "fold:Worked for 8s", "assistant:launch-answer", "user:resume", + "fold:Working", "activity-group", ]); + // The live timer row becomes the settled fold in place. + expect(working[4]?.id).toBe(settled[4]?.id); }); it("keeps imported V1 turns folded once the thread's first V2 run starts", () => { @@ -1443,8 +1443,8 @@ describe("buildThreadFeed", () => { new Set(), new Set(), startedAt, - ), - ).toEqual([]); + ).map((row) => row.type), + ).toEqual(["run-fold"]); }); it("hides tool calls or everything but the final answer", () => { const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`; @@ -1794,8 +1794,9 @@ describe("subagent continued by a later turn", () => { ]; it("keeps each turn's fold between its own prompt and answer", () => { + const feed = buildThreadFeed(items.map((entry, index) => projected(entry, index))); const presented = deriveThreadFeedPresentation( - buildThreadFeed(items.map((entry, index) => projected(entry, index))), + feed, { runId: run2, status: "completed", startedAt: at(30), completedAt: at(41) }, new Set(), ); @@ -1807,6 +1808,53 @@ describe("subagent continued by a later turn", () => { `run-fold:${run2}`, "closing-2", ]); + + // While the run works, its fold row already holds that slot with a live timer. + const live = deriveThreadFeedPresentation( + feed, + { runId: run2, status: "running", startedAt: at(30), completedAt: null }, + new Set(), + new Set(), + at(30), + ); + expect(live.slice(3, 6).map((entry) => entry.id)).toEqual([ + "prompt-2", + `run-fold:${run2}`, + expect.not.stringMatching(/^run-fold:/), + ]); + expect(live[4]).toMatchObject({ workingSince: at(30) }); + expect(live.filter((entry) => entry.type === "run-fold")).toHaveLength(2); + }); + + it("puts the live fold after a plan the settled fold leaves in view", () => { + const planned = buildThreadFeed( + [ + user("prompt", run2, 1, 0), + { + ...item("plan", run2, 2, 1), + type: "proposed_plan", + planId: "plan", + markdown: "The plan", + streaming: false, + } as OrchestrationV2TurnItem, + reasoning("reasoning", run2, 3, 2), + assistant("closing", run2, 4, 9), + ].map((entry, index) => projected(entry, index)), + ); + const ids = (running: boolean) => + deriveThreadFeedPresentation( + planned, + running + ? { runId: run2, status: "running", startedAt: at(0), completedAt: null } + : { runId: run2, status: "completed", startedAt: at(0), completedAt: at(9) }, + new Set(), + new Set(), + running ? at(0) : null, + ).map((entry) => entry.id); + const settledIds = ids(false); + const foldIndex = settledIds.indexOf(`run-fold:${run2}`); + expect(foldIndex).toBeGreaterThan(1); + expect(ids(true).indexOf(`run-fold:${run2}`)).toBe(foldIndex); }); }); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index ed85709f30059..e07e7dbc1b29d 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -248,6 +248,8 @@ type ThreadFeedEntryContent = | { readonly type: "run-fold"; readonly deferredWorkItemIds?: ReadonlyArray; + /** Set while the run works: the row shows a live timer and does not toggle. */ + readonly workingSince?: string; readonly id: string; readonly createdAt: string; readonly runId: RunId; @@ -1242,23 +1244,8 @@ function deriveThreadFeedRunFolds( (entry) => entry.id !== terminalAssistantId && !(entry.type === "message" && retainedAnswerIds.has(entry.message.id)) && - entry.type !== "html-render" && - entry.type !== "sent-message" && - entry.type !== "mcp-app" && entry.id !== visibleCompactionId && - !( - entry.type === "activity-group" && - entry.activities.some( - (activity) => - activity.prominent || - activity.workEntry.questionAnswer !== undefined || - activity.projectedItem.item.type === "notification" || - activity.projectedItem.item.type === "handoff" || - // A child still working outlives its settled launching run; - // its group stays visible while any member is live. - isLiveSubagentTurnItem(activity.projectedItem.item), - ) - ), + !staysOutOfFold(entry), ) .map((entry) => entry.id), ); @@ -1426,6 +1413,26 @@ function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLate ); } +/** Rows a fold leaves in view; the live fold skips them too, so settling keeps its place. */ +function staysOutOfFold(entry: ThreadFeedEntry): boolean { + return ( + entry.type === "html-render" || + entry.type === "sent-message" || + entry.type === "mcp-app" || + (entry.type === "activity-group" && + entry.activities.some( + (activity) => + activity.prominent || + activity.workEntry.questionAnswer !== undefined || + activity.projectedItem.item.type === "notification" || + activity.projectedItem.item.type === "handoff" || + // A child still working outlives its settled launching run; + // its group stays visible while any member is live. + isLiveSubagentTurnItem(activity.projectedItem.item), + )) + ); +} + function feedEntryRunId(entry: ThreadFeedEntry): RunId | null { return entry.type === "message" ? (entry.message.runId ?? null) : entry.runId; } @@ -1725,9 +1732,44 @@ export function deriveThreadFeedPresentation( for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId); } } + // The working run's fold row shows its live timer where "Worked for" lands once it settles. + // Zen never folds, so it keeps only the Thinking row. + // Runless work folds under its prompt's key once it settles, so the live row takes that key. + const runlessPrompt = + activeRunId === null && runlessWorkActive + ? sourceFeed.findLast((entry) => isUserMessageEntry(entry) && feedEntryRunId(entry) === null) + : undefined; + const liveRunId = + activeRunId ?? (runlessPrompt ? RunId.make(`runless:${runlessPrompt.id}`) : null); + const liveFold = + !zen && + isWorking && + activeWorkStartedAt !== null && + liveRunId !== null && + !compactionCommandRunIds.has(liveRunId) + ? liveRunFoldRow(liveRunId, activeWorkStartedAt) + : null; + let liveFoldPlaced = false; + // Earlier turns can hold the run's own items (a subagent it continued), so wait for its prompt. + let liveFoldReady = + liveFold !== null && + activeRunId !== null && + !sourceFeed.some((entry) => isUserMessageEntry(entry) && feedEntryRunId(entry) === activeRunId); for (let sourceIndex = 0; sourceIndex < sourceFeed.length; sourceIndex += 1) { const entry = sourceFeed[sourceIndex]!; const feedIndex = retainedFeedIndices[sourceIndex]!; + if (liveFold !== null && !liveFoldPlaced && feedEntryRunId(entry) === activeRunId) { + if (isUserMessageEntry(entry)) { + liveFoldReady = activeRunId !== null || entry === runlessPrompt; + } else if ( + liveFoldReady && + !staysOutOfFold(entry) && + !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) + ) { + result.push(liveFold); + liveFoldPlaced = true; + } + } if (isUserMessageEntry(entry)) { restarts.push({ entry: feedIndex, rowsLength: result.length }); } @@ -1808,6 +1850,7 @@ export function deriveThreadFeedPresentation( ); } } + if (liveFold !== null && !liveFoldPlaced) result.push(liveFold); if ( isWorking && activeWorkStartedAt !== null && @@ -1932,7 +1975,7 @@ function isWorkLogFeedRow(row: ThreadFeedEntry | undefined): boolean { ); } -const LIVE_ACTIVITY_ROW_ID = "live-activity-row"; +export const LIVE_ACTIVITY_ROW_ID = "live-activity-row"; /** Reads the feed before tool visibility filters it, so hidden newer parent work still counts. */ function runningSubagentsAtRunTail(feed: ReadonlyArray, runId: RunId): number { @@ -1947,6 +1990,23 @@ function runningSubagentsAtRunTail(feed: ReadonlyArray, runId: return running; } +let cachedLiveRunFoldRow: Extract | null = null; + +function liveRunFoldRow(runId: RunId, startedAt: string) { + if (cachedLiveRunFoldRow?.runId !== runId || cachedLiveRunFoldRow.workingSince !== startedAt) { + cachedLiveRunFoldRow = { + type: "run-fold", + id: `run-fold:${runId}`, + createdAt: startedAt, + runId, + label: "Working", + expanded: false, + workingSince: startedAt, + }; + } + return cachedLiveRunFoldRow; +} + function thinkingRow( createdAt: string, runId: RunId | null, diff --git a/apps/mobile/src/state/attachments.test.ts b/apps/mobile/src/state/attachments.test.ts index 5f727e3304f94..052c5ef045cb1 100644 --- a/apps/mobile/src/state/attachments.test.ts +++ b/apps/mobile/src/state/attachments.test.ts @@ -6,7 +6,10 @@ import { import { runAttachmentUploadCycle } from "@t3tools/client-runtime/state/attachments"; import * as Cause from "effect/Cause"; import { AsyncResult, AtomRegistry } from "effect/reactivity"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import { afterEach, beforeEach, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ grantedEnvironments: new Set(), @@ -76,24 +79,29 @@ describe("attachment mutation grants", () => { expect(state.remove).toHaveBeenCalledOnce(); }); - it("blocks the upload cycle's asynchronous cleanup after grant revocation", async () => { - state.grantedEnvironments.add("secondary"); - const transport = vi.fn(); - const result = await runAttachmentUploadCycle({ - registry, - ...attachmentEnvironment, - environmentId, - upload: { name: "image.png", mimeType: "image/png", sizeBytes: 1 }, - resolveUploadUrl: () => "https://example.test/upload", - transport, - onMinted: () => { - state.grantedEnvironments.delete("secondary"); - return "cancel"; - }, - }); - expect(result.status).toBe("cancelled"); - expect(state.create).toHaveBeenCalledOnce(); - expect(state.remove).not.toHaveBeenCalled(); - expect(transport).not.toHaveBeenCalled(); - }); + it.effect("blocks the upload cycle's cleanup after grant revocation", () => + Effect.gen(function* () { + state.grantedEnvironments.add("secondary"); + const transferStarted = Promise.withResolvers(); + const cycle = yield* Effect.forkChild( + runAttachmentUploadCycle({ + registry, + ...attachmentEnvironment, + environmentId, + upload: { name: "image.png", mimeType: "image/png", sizeBytes: 1 }, + resolveUploadUrl: () => "https://example.test/upload", + transport: () => + Effect.callback(() => { + state.grantedEnvironments.delete("secondary"); + transferStarted.resolve(); + }), + }), + ); + yield* Effect.promise(() => transferStarted.promise); + // Interrupting deletes the fresh mint, which the revoked grant must refuse. + yield* Fiber.interrupt(cycle); + expect(state.create).toHaveBeenCalledOnce(); + expect(state.remove).not.toHaveBeenCalled(); + }), + ); }); diff --git a/apps/mobile/src/state/composer-attachment-upload-states.ts b/apps/mobile/src/state/composer-attachment-upload-states.ts deleted file mode 100644 index 2dafe12ef678a..0000000000000 --- a/apps/mobile/src/state/composer-attachment-upload-states.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Atom } from "effect/reactivity"; - -import type { ComposerAttachmentUploadState } from "../lib/composerAttachmentUploadQueue"; - -/** The upload worker's per-attachment states, apart from the worker so the outbox can read them. */ -export const composerAttachmentUploadsAtom = Atom.make< - Readonly> ->({}).pipe(Atom.keepAlive); diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts index 81a542a5aca1c..7d8a431150d26 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.test.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts @@ -1,5 +1,7 @@ import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { afterEach, beforeEach, vi } from "vite-plus/test"; type UploadOptions = { signal: AbortSignal; @@ -141,7 +143,9 @@ vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({ ) => native.server.get(query.input.resource.attachmentId) ? { _tag: "Success", value: {} } - : { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } }, + : (await import("effect/reactivity")).AsyncResult.failure( + (await import("effect/Cause")).fail({ _tag: "AssetAttachmentNotFoundError" }), + ), runAtomCommand: async ( _registry: unknown, command: unknown, @@ -167,7 +171,7 @@ vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); return { editingQueuedMessageIdsAtom: Atom.make>({}).pipe(Atom.keepAlive), - dispatchingQueuedMessageIdAtom: Atom.make>({}).pipe(Atom.keepAlive), + dispatchingQueuedMessageIdsAtom: Atom.make>({}).pipe(Atom.keepAlive), useThreadOutboxMessages: () => appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), @@ -296,29 +300,48 @@ function uploadState() { ]; } -it.each(["decode", "write"] as const)( +it.effect.each(["decode", "write"] as const)( "keeps an accepted upload ready when the draft %s fails", - async (fault) => { - native.fault = fault; - if (fault === "decode") - native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":')); - drafts.resetComposerDraftsLoadState(); + (fault) => + Effect.gen(function* () { + native.fault = fault; + if (fault === "decode") + native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":')); + drafts.resetComposerDraftsLoadState(); + const queue = worker(); + yield* Effect.promise(() => queue.settled()); + expect(uploadState()).toEqual({ status: "ready" }); + expect(native.deleted).toEqual([]); + expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull(); + expect(composerAttachmentsStillUploading(sendInput())).toBe(false); + + const message = queuedMessage(); + expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1"); + yield* Effect.promise(() => enqueueThreadOutboxMessage(message)); + const prepared = yield* prepareQueuedMessageAttachments(message); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned"); + expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]); + expect(native.transfer).toHaveBeenCalledTimes(1); + }), +); + +it.effect("uploads again at send time when the server swept a finished upload", () => + Effect.gen(function* () { const queue = worker(); - await queue.settled(); + yield* Effect.promise(() => queue.settled()); expect(uploadState()).toEqual({ status: "ready" }); - expect(native.deleted).toEqual([]); - expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull(); - expect(composerAttachmentsStillUploading(sendInput())).toBe(false); + // The server sweeps pending uploads nothing claimed, here while the draft sat unsent. + native.server.delete("pending-1"); const message = queuedMessage(); - expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1"); - await enqueueThreadOutboxMessage(message); - const prepared = await prepareQueuedMessageAttachments(message); + yield* Effect.promise(() => enqueueThreadOutboxMessage(message)); + const prepared = yield* prepareQueuedMessageAttachments(message); expect(prepared.status).toBe("ready"); if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned"); - expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]); - expect(native.transfer).toHaveBeenCalledTimes(1); - }, + expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-2"]); + expect(native.transfer).toHaveBeenCalledTimes(2); + }), ); it("keeps an upload running when its message is sent mid-upload and records it on the message", async () => { @@ -369,7 +392,8 @@ it("keeps an unexpected draft flush error blocking Send", async () => { expect(composerAttachmentUploadBlockReason(sendInput())).toBe( "Retry or remove the failed attachment", ); - expect(native.deleted).toEqual(["pending-1"]); + // The server sweeps pending uploads nothing claims; a retry uploads again. + expect(native.deleted).toEqual([]); }); it("uploads draft attachments for threads whose ids contain colons", () => { diff --git a/apps/mobile/src/state/composer-attachment-uploads.ts b/apps/mobile/src/state/composer-attachment-uploads.ts index 8e2921c5f62d2..0779d153d3f23 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.ts @@ -1,10 +1,15 @@ -import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { useAtomValue } from "@effect/atom-react"; import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { Atom, AsyncResult } from "effect/reactivity"; +import { + attachmentUploadError, + createAttachmentUploadRegistry, +} from "@t3tools/client-runtime/state/attachment-uploads"; +import { verifyPersistedAttachmentUpload } from "@t3tools/client-runtime/state/attachments"; +import { Atom } from "effect/reactivity"; -import { prepareTurnAttachments } from "../lib/attachmentUpload"; +import { uploadComposerAttachment } from "../lib/attachmentUpload"; import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention"; import { isFileBackedComposerAttachment, @@ -14,16 +19,15 @@ import { composerAttachmentUploadKey, composerDraftEnvironmentId, canUploadComposerAttachment, - createComposerAttachmentUploadQueue, + type ComposerAttachmentUploadState, } from "../lib/composerAttachmentUploadQueue"; import { appAtomRegistry } from "./atom-registry"; -import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; +import { assetEnvironment } from "./assets"; import { environmentServerConfigsAtom } from "./server"; import { flattenQueuedThreadMessages, threadOutboxManager, - threadOutboxRevision, - updateThreadOutboxMessage, + modifyThreadOutboxMessage, type QueuedThreadMessage, } from "./thread-outbox"; import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; @@ -46,11 +50,13 @@ export { composerAttachmentsStillUploading, } from "../lib/composerAttachmentUploadQueue"; -export { composerAttachmentUploadsAtom }; +export const composerAttachmentUploadsAtom = Atom.make< + Readonly> +>({}).pipe(Atom.keepAlive); const uploadStateAtom = Atom.family((key: string) => Atom.map(composerAttachmentUploadsAtom, (states) => states[key]), ); -let uploadQueue: ReturnType | null = null; +let uploadQueue: ReturnType | null = null; export function useComposerAttachmentUploadState( environmentId: EnvironmentId | undefined, @@ -63,7 +69,7 @@ export function useComposerAttachmentUploadState( export function retryComposerAttachmentUpload(environmentId: EnvironmentId, attachmentId: string) { if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return; - uploadQueue?.retry(environmentId, attachmentId); + uploadQueue?.retry(composerAttachmentUploadKey(environmentId, attachmentId)); } type ComposerAttachmentUploadRequest = { @@ -136,33 +142,35 @@ function withUploadedAttachment( }; } -async function recordQueuedAttachmentUpload( +const recordQueuedAttachmentUpload = Effect.fn("ComposerAttachments.recordQueuedUpload")(function* ( environmentId: EnvironmentId, uploaded: DraftComposerAttachment, -): Promise { - const awaiting = () => { - const editing = appAtomRegistry.get(editingQueuedMessageIdsAtom); - return flattenQueuedThreadMessages( - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), - ).flatMap((message) => { - if (message.environmentId !== environmentId || editing[message.messageId]) return []; - const updated = withUploadedAttachment(message, uploaded); - return updated === null - ? [] - : [{ updated, revision: threadOutboxRevision(message.messageId) }]; - }); - }; - let recorded = false; - // A sibling attachment finishing at the same time bumps the revision; reread and retry. - for (let attempt = 0; attempt < 3; attempt++) { - const pending = awaiting(); - if (pending.length === 0) break; - for (const { updated, revision } of pending) { - recorded = (await updateThreadOutboxMessage(updated, revision)) || recorded; - } - } - return recorded; -} +) { + const editing = appAtomRegistry.get(editingQueuedMessageIdsAtom); + const holders = flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ).filter( + (message) => + message.environmentId === environmentId && + !editing[message.messageId] && + withUploadedAttachment(message, uploaded) !== null, + ); + yield* Effect.forEach( + holders, + (message) => + Effect.tryPromise({ + // An editor that opened meanwhile owns the message; its draft records the upload. + try: () => + modifyThreadOutboxMessage(message.messageId, (current) => + appAtomRegistry.get(editingQueuedMessageIdsAtom)[current.messageId] + ? null + : withUploadedAttachment(current, uploaded), + ), + catch: attachmentUploadError, + }), + { concurrency: "unbounded", discard: true }, + ); +}); // Each connected environment's session is read here so a granted or revoked // operate scope re-syncs the queue. @@ -193,8 +201,98 @@ const composerAttachmentUploadRequestsAtom = Atom.make((get) => { }); }).pipe(Atom.withLabel("mobile:composer-attachment-upload-requests")); +/** Saves a finished upload's id on every draft and queued message holding the attachment. */ +const recordComposerAttachmentUpload = Effect.fn("ComposerAttachments.recordUpload")(function* ( + request: ComposerAttachmentUploadRequest, + uploadedId: string, +) { + const { environmentId, attachment } = request; + const uploaded: DraftComposerAttachment = { + ...attachment, + uploadedAttachmentId: uploadedId, + uploadEnvironmentId: environmentId, + }; + const queued = flattenQueuedThreadMessages( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ); + const knownEnvironmentIds = appAtomRegistry + .get(workspaceConnections.environmentsAtom) + .map((environment) => environment.environmentId); + let draftsChanged = false; + for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) { + if ( + composerDraftEnvironmentId(key, knownEnvironmentIds, queued, draft) === environmentId && + draft.attachments.some((candidate) => candidate.id === attachment.id) + ) { + draftsChanged = setComposerDraftAttachmentUpload(key, uploaded) || draftsChanged; + } + } + yield* recordQueuedAttachmentUpload(environmentId, uploaded); + if (!draftsChanged) return; + // A failed draft save only costs a re-upload after restart; the outbox saves its own references. + yield* Effect.tryPromise({ try: () => flushComposerDrafts(), catch: attachmentUploadError }).pipe( + Effect.catchIf( + (error) => isComposerDraftPersistenceError(error.cause), + (error) => + Effect.logWarning( + "[composer-attachments] could not save the uploaded reference", + error.cause, + ), + ), + ); +}); + +const createComposerUploadRegistry = () => + createAttachmentUploadRegistry({ + key: (request) => composerAttachmentUploadKey(request.environmentId, request.attachment.id), + environmentId: (request) => request.environmentId, + concurrencyPerEnvironment: 3, + onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states), + // The file stays on disk while its upload reads it, even if its draft lets go meanwhile. + upload: ({ environmentId, attachment }, reportProgress) => + Effect.acquireUseRelease( + Effect.sync(() => + isFileBackedComposerAttachment(attachment) + ? retainComposerAttachmentFileForPreview(attachment) + : undefined, + ), + () => uploadComposerAttachment(environmentId, attachment, reportProgress), + (release) => Effect.sync(() => release?.()), + ), + onUploaded: recordComposerAttachmentUpload, + }); + +function composerAttachmentUploads() { + uploadQueue ??= createComposerUploadRegistry(); + return uploadQueue; +} + +/** Every send uploads through here, so it joins the composer's upload of the same attachment. */ +export const uploadComposerAttachmentShared = Effect.fn("ComposerAttachments.uploadForSend")( + function* (environmentId: EnvironmentId, attachment: DraftComposerAttachment) { + const uploads = composerAttachmentUploads(); + const request = { environmentId, attachment }; + const key = composerAttachmentUploadKey(environmentId, attachment.id); + // An upload that finished earlier can outlive the server's pending-upload sweep. + const finishedEarlier = uploads.status(key)?.status === "ready"; + const uploadedId = yield* uploads.upload(request); + if (!finishedEarlier) return uploadedId; + const verification = yield* verifyPersistedAttachmentUpload({ + registry: appAtomRegistry, + createAssetUrl: assetEnvironment.createUrl, + environmentId, + attachmentId: uploadedId, + }); + if (verification.status === "verified") return uploadedId; + if (verification.status === "failed") return yield* attachmentUploadError(verification.error); + // Starting over verifies the saved id again and uploads the bytes when it is gone. + uploads.restart(key); + return yield* uploads.upload(request); + }, +); + /** - * Uploads draft attachments to their environment as soon as it is connected and + * Uploads draft and queued attachments to their environment as soon as it is connected and * operable. The queue follows the requests atom for its whole lifetime. */ export function createComposerAttachmentUploadWorker( @@ -203,54 +301,7 @@ export function createComposerAttachmentUploadWorker( > = composerAttachmentUploadRequestsAtom, ) { ensureComposerDraftsLoaded(); - const queue = createComposerAttachmentUploadQueue({ - onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states), - upload: async ({ environmentId, attachment }, signal, onProgress) => { - const release = isFileBackedComposerAttachment(attachment) - ? retainComposerAttachmentFileForPreview(attachment) - : undefined; - const prepared = await settlePromise(() => - prepareTurnAttachments({ - environmentId, - attachments: [attachment], - supportsImageUploads: true, - signal, - onUploadProgress: (_, progress) => onProgress(progress), - persistUploadedReferences: async ([uploaded]) => { - if (signal.aborted || !uploaded) return "abandon"; - const queued = flattenQueuedThreadMessages( - appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), - ); - const knownEnvironmentIds = appAtomRegistry - .get(workspaceConnections.environmentsAtom) - .map((environment) => environment.environmentId); - let retained = false; - for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) { - if ( - composerDraftEnvironmentId(key, knownEnvironmentIds, queued, draft) === - environmentId && - draft.attachments.some((candidate) => candidate.id === attachment.id) - ) { - retained = setComposerDraftAttachmentUpload(key, uploaded) || retained; - } - } - retained = (await recordQueuedAttachmentUpload(environmentId, uploaded)) || retained; - if (!retained) return "abandon"; - // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads. - await flushComposerDrafts().catch((error: unknown) => { - if (!isComposerDraftPersistenceError(error)) throw error; - console.warn("[composer-attachments] could not save the uploaded reference", error); - }); - return "persisted"; - }, - }), - ); - release?.(); - if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared); - return prepared.value.status === "ready"; - }, - }); - uploadQueue = queue; + const queue = composerAttachmentUploads(); const unsubscribe = appAtomRegistry.subscribe(requestsAtom, (requests) => queue.sync(requests), { immediate: true, }); diff --git a/apps/mobile/src/state/edit-pending-thread-message.test.ts b/apps/mobile/src/state/edit-pending-thread-message.test.ts index c9c8b4f6a47f8..c9efb7c934e5c 100644 --- a/apps/mobile/src/state/edit-pending-thread-message.test.ts +++ b/apps/mobile/src/state/edit-pending-thread-message.test.ts @@ -3,7 +3,7 @@ import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contract import type { QueuedThreadMessage } from "./thread-outbox-model"; const state = vi.hoisted(() => ({ - dispatching: null as string | null, + dispatching: {} as Record, held: {} as Record, draft: { text: "Existing draft", attachments: [] as { id: string }[] }, confirm: vi.fn(async () => true), @@ -16,7 +16,7 @@ vi.mock("./atom-registry", () => ({ }, })); vi.mock("./use-thread-outbox", () => ({ - dispatchingQueuedMessageIdAtom: "dispatching", + dispatchingQueuedMessageIdsAtom: "dispatching", editingQueuedMessageIdsAtom: "editing", holdEditingQueuedMessage: (id: string) => { state.held[id] = true; @@ -67,7 +67,7 @@ const message: QueuedThreadMessage = { }; beforeEach(() => { vi.clearAllMocks(); - state.dispatching = null; + state.dispatching = {}; state.held = {}; state.draft = { text: "Existing draft", attachments: [] }; state.confirm.mockResolvedValue(true); @@ -90,7 +90,7 @@ describe("editing a pending message", () => { expect(state.held).toEqual({}); }); it("does not reclaim a message already being dispatched", async () => { - state.dispatching = message.messageId; + state.dispatching = { [message.messageId]: true }; expect(await editPendingThreadMessage(message)).toBe(false); expect(state.confirm).not.toHaveBeenCalled(); expect(state.draft.text).toBe("Existing draft"); diff --git a/apps/mobile/src/state/edit-pending-thread-message.ts b/apps/mobile/src/state/edit-pending-thread-message.ts index e2f3a2bfcb5d5..6e599abf6823d 100644 --- a/apps/mobile/src/state/edit-pending-thread-message.ts +++ b/apps/mobile/src/state/edit-pending-thread-message.ts @@ -16,7 +16,7 @@ import { waitForComposerDraftsLoaded, } from "./use-composer-drafts"; import { - dispatchingQueuedMessageIdAtom, + dispatchingQueuedMessageIdsAtom, editingQueuedMessageIdsAtom, holdEditingQueuedMessage, releaseEditingQueuedMessage, @@ -26,7 +26,7 @@ import { export async function editPendingThreadMessage(message: QueuedThreadMessage): Promise { if ( message.creation || - appAtomRegistry.get(dispatchingQueuedMessageIdAtom) === message.messageId || + appAtomRegistry.get(dispatchingQueuedMessageIdsAtom)[message.messageId] || appAtomRegistry.get(editingQueuedMessageIdsAtom)[message.messageId] ) { return false; diff --git a/apps/mobile/src/state/thread-outbox-manager.ts b/apps/mobile/src/state/thread-outbox-manager.ts index 732db0159b7f7..a83537fdb0a0c 100644 --- a/apps/mobile/src/state/thread-outbox-manager.ts +++ b/apps/mobile/src/state/thread-outbox-manager.ts @@ -176,6 +176,46 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) { return true; }); + /** + * Applies `change` to the message as it stands when this mutation's turn comes, so concurrent + * changes compose instead of failing on each other's revision. `null` leaves it unchanged. + */ + const modify = ( + messageId: MessageId, + change: (message: QueuedThreadMessage) => QueuedThreadMessage | null, + ): Promise => + serialize(async () => { + const current = currentMessages().find((candidate) => candidate.messageId === messageId); + const next = current === undefined ? null : change(current); + if (current === undefined || next === null) return false; + const revision = revisions.get(messageId) ?? 0; + try { + await options.storage.write(next); + } catch (cause) { + throw new ThreadOutboxManagerError({ + operation: "update", + environmentId: next.environmentId, + threadId: next.threadId, + messageId, + cause, + }); + } + // An enqueue publishes without waiting its turn; when one replaced the message during the + // write, it wins and stays durable. + if ((revisions.get(messageId) ?? 0) !== revision || !currentMessages().includes(current)) { + const winner = currentMessages().find((candidate) => candidate.messageId === messageId); + if (winner !== undefined) { + try { + await options.storage.write(winner); + } catch {} + } + return false; + } + bumpRevision(messageId); + setMessages(currentMessages().map((candidate) => (candidate === current ? next : candidate))); + return true; + }); + // Check live ownership too; editor locks can change without message revision updates. const remove = ( message: QueuedThreadMessage, @@ -347,6 +387,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) { confirmQueued, revisionOf: (messageId: MessageId): number => revisions.get(messageId) ?? 0, update, + modify, remove, clearEnvironment, }; diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index 64fe62d8a15f7..2ec0d29eca21a 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -288,6 +288,9 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean { case "EnvironmentRpcUnavailableError": case "EnvironmentNotRegisteredError": return true; + // A shared upload's failure decides by what made the upload fail. + case "AttachmentUploadError": + return "cause" in error && shouldRetryThreadOutboxDelivery(error.cause); default: break; } diff --git a/apps/mobile/src/state/thread-outbox.test.ts b/apps/mobile/src/state/thread-outbox.test.ts index 95333fc5925d2..5ff7bd53a1c7d 100644 --- a/apps/mobile/src/state/thread-outbox.test.ts +++ b/apps/mobile/src/state/thread-outbox.test.ts @@ -718,6 +718,42 @@ describe("thread outbox", () => { registry.dispose(); }); + it("composes concurrent modifications of one message instead of rejecting the later one", async () => { + const registry = AtomRegistry.make(); + const stored = new Map(); + const manager = createThreadOutboxManager({ + registry, + storage: { + load: async () => ({ messages: [], errors: [] }), + write: async (message) => { + stored.set(message.messageId, message); + }, + remove: async () => undefined, + }, + }); + const message = queuedMessage({ + messageId: "message-two-uploads", + createdAt: "2026-06-08T10:00:01.000Z", + }); + await manager.enqueue(message); + + // Two attachments finishing together each record their upload on the same message. + const results = await Promise.all([ + manager.modify(message.messageId, (current) => ({ ...current, text: `${current.text} a` })), + manager.modify(message.messageId, (current) => ({ ...current, text: `${current.text} b` })), + ]); + + expect(results).toEqual([true, true]); + const composed = { ...message, text: `${message.text} a b` }; + expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({ + "environment-1:thread-1": [composed], + }); + expect(stored.get(message.messageId)).toEqual(composed); + await manager.remove(composed); + await expect(manager.modify(message.messageId, (current) => current)).resolves.toBe(false); + registry.dispose(); + }); + it("rejects a stale revision before its payload reaches durable storage", async () => { const registry = AtomRegistry.make(); const writes: string[] = []; diff --git a/apps/mobile/src/state/thread-outbox.ts b/apps/mobile/src/state/thread-outbox.ts index 4a9c7d666e129..24f3c1512abce 100644 --- a/apps/mobile/src/state/thread-outbox.ts +++ b/apps/mobile/src/state/thread-outbox.ts @@ -32,6 +32,14 @@ export function updateThreadOutboxMessage( return threadOutboxManager.update(message, expectedRevision); } +/** Changes the message as it is when its turn comes; false when it is gone or `change` returns null. */ +export function modifyThreadOutboxMessage( + messageId: QueuedThreadMessage["messageId"], + change: (message: QueuedThreadMessage) => QueuedThreadMessage | null, +): Promise { + return threadOutboxManager.modify(messageId, change); +} + export function threadOutboxRevision(messageId: QueuedThreadMessage["messageId"]): number { return threadOutboxManager.revisionOf(messageId); } diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts index d037ac106a025..7051193be1175 100644 --- a/apps/mobile/src/state/thread-task-permissions.test.ts +++ b/apps/mobile/src/state/thread-task-permissions.test.ts @@ -141,7 +141,7 @@ vi.mock("./threads", async () => { }); vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); - return { dispatchingQueuedMessageIdAtom: Atom.make(null), useThreadOutboxMessages: () => ({}) }; + return { dispatchingQueuedMessageIdsAtom: Atom.make({}), useThreadOutboxMessages: () => ({}) }; }); vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue })); vi.mock("./composer-attachment-uploads", async () => { diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts index 263c48195d75d..b8588e0d40082 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts @@ -7,6 +7,8 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { attachmentUploadError } from "@t3tools/client-runtime/state/attachment-uploads"; +import * as Effect from "effect/Effect"; import * as Cause from "effect/Cause"; import { AsyncResult, type Atom } from "effect/reactivity"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; @@ -107,6 +109,7 @@ vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.chec vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable })); vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" })); vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare })); +vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() })); vi.mock("./thread-outbox", async () => { const { createThreadOutboxManager } = await import("./thread-outbox-manager"); const { appAtomRegistry } = await import("./atom-registry"); @@ -135,7 +138,9 @@ vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); return { editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), - dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), + dispatchingQueuedMessageIdsAtom: Atom.make>>({}).pipe( + Atom.keepAlive, + ), retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])), }; @@ -146,7 +151,7 @@ vi.mock("./use-composer-drafts", async () => { composerDraftsAtom: Atom.make({}), removeDeliveredCloudQueuedMessage: async () => {}, appendComposerDraftAttachments: vi.fn(), - flushComposerDrafts: vi.fn(), + flushComposerDrafts: vi.fn(async () => {}), getComposerDraftSnapshot: vi.fn(() => ({ text: state.draftText, attachments: [] })), mergeComposerDraftContent: vi.fn(async (_key: string, input: { text: string }) => { state.draftText += `\n${input.text}`; @@ -161,9 +166,10 @@ vi.mock("./use-composer-drafts", async () => { import { appAtomRegistry } from "./atom-registry"; import { environmentSession } from "./session"; -import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox"; +import { dispatchingQueuedMessageIdsAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox"; + +const sendingMessageIds = () => Object.keys(appAtomRegistry.get(dispatchingQueuedMessageIdsAtom)); import { createThreadOutboxDelivery } from "./threadOutboxDelivery"; -import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; import { workspaceConnections } from "./workspace"; const message = (overrides: Partial = {}): QueuedThreadMessage => ({ @@ -187,8 +193,8 @@ function setOperateGrant(environmentId: string, granted: boolean): void { function runDrain() { const settled = Promise.withResolvers(); - const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { - if (id === null) settled.resolve(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { + if (Object.keys(ids).length === 0) settled.resolve(); }); startDelivery(); return settled.promise.finally(release); @@ -217,7 +223,7 @@ beforeEach(() => { state.familyMount.mockReset().mockReturnValue(() => {}); appAtomRegistry.set(state.threadShells, [state.thread]); appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {}); - appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null); + appAtomRegistry.set(dispatchingQueuedMessageIdsAtom, {}); appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); for (const command of [ state.start, @@ -229,12 +235,14 @@ beforeEach(() => { command.mockReset().mockResolvedValue(AsyncResult.success(undefined)); } state.start.mockResolvedValue(AsyncResult.success({})); - state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({ - status: "ready", - attachments: [], - draftAttachments: attachments, - pendingAttachmentIds: [], - })); + state.prepare.mockReset().mockImplementation(({ attachments }) => + Effect.succeed({ + status: "ready", + attachments: [], + draftAttachments: attachments, + pendingAttachmentIds: [], + }), + ); }); describe("queued PR checkout", () => { @@ -356,7 +364,7 @@ describe("queued task operation access", () => { expect(state.modelUnavailable).toHaveBeenCalledOnce(); expect(state.prepare).not.toHaveBeenCalled(); expect(state.start).not.toHaveBeenCalled(); - expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull(); + expect(sendingMessageIds()).toEqual([]); expect(remaining()).toEqual([queued]); }); @@ -373,17 +381,17 @@ describe("queued task operation access", () => { startDelivery(); appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true }); await state.manager.enqueue(queued); - using confirm = vi.spyOn(state.manager, "confirmQueued"); const delivered = Promise.withResolvers(); - const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { - if (id === null) delivered.resolve(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { + if (Object.keys(ids).length === 0) delivered.resolve(); }); - // Ending the edit wakes the drain through a registry notification, the path on which the - // mount's synchronous row change notifies the drain again mid-pass. + // Ending the edit wakes the thread through a registry notification, the path on which the + // mount's synchronous row change wakes it again while it is deciding. appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); - expect(state.familyMount).toHaveBeenCalledOnce(); - expect(confirm).toHaveBeenCalledOnce(); await delivered.promise.finally(release); + expect(state.familyMount).toHaveBeenCalledOnce(); + // One fiber took the message: a second would have prepared it again. + expect(state.prepare).toHaveBeenCalledOnce(); expect(state.start).toHaveBeenCalledOnce(); expect(remaining()).toEqual([]); }); @@ -485,16 +493,21 @@ describe("queued task operation access", () => { : {}, ); await state.manager.enqueue(queued); - state.prepare.mockImplementationOnce(async ({ attachments }) => { - setOperateGrant("secondary", false); - if (uploadFails) throw new Error("This connection cannot upload attachments."); - return { - status: "ready", - attachments: [], - draftAttachments: attachments, - pendingAttachmentIds: [], - }; - }); + state.prepare.mockImplementationOnce(({ attachments }) => + Effect.suspend(() => { + setOperateGrant("secondary", false); + return uploadFails + ? Effect.fail( + attachmentUploadError(new Error("This connection cannot upload attachments.")), + ) + : Effect.succeed({ + status: "ready", + attachments: [], + draftAttachments: attachments, + pendingAttachmentIds: [], + }); + }), + ); await runDrain(); expect(state.prepare).toHaveBeenCalledOnce(); expect(state.start).not.toHaveBeenCalled(); @@ -536,8 +549,8 @@ describe("queued task whose launch reply is lost", () => { async function fireRetry(): Promise { const settled = Promise.withResolvers(); - const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { - if (id === null) settled.resolve(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { + if (Object.keys(ids).length === 0) settled.resolve(); }); vi.advanceTimersByTime(threadOutboxRetryDelayMs(1)); await settled.promise.finally(release); @@ -569,7 +582,7 @@ describe("queued task whose launch reply is lost", () => { await loseLaunchReply(queuedTask()); setOperateGrant("secondary", false); vi.advanceTimersByTime(threadOutboxRetryDelayMs(1)); - expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull(); + expect(sendingMessageIds()).toEqual([]); expect(state.start).toHaveBeenCalledOnce(); expect(remaining()).toHaveLength(1); @@ -657,42 +670,87 @@ describe("compaction before a queued send", () => { describe("queued delivery timing", () => { /** Runs `change`, then resolves once the delivery it starts has settled. */ async function deliveryAfter(change: () => void): Promise { + const started = Promise.withResolvers(); const settled = Promise.withResolvers(); - const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { - if (id === null) settled.resolve(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { + if (Object.keys(ids).length > 0) started.resolve(); + else settled.resolve(); }); change(); - expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).not.toBeNull(); + await started.promise; await settled.promise.finally(release); } - it("waits for the composer's upload of a sent attachment instead of uploading it again", async () => { + it("starts a thread's next message only after its interrupted send has finished", async () => { setOperateGrant("secondary", true); - const photo = { - id: "photo-1", - type: "image" as const, - name: "photo.png", - mimeType: "image/png", - sizeBytes: 3, - previewUri: "file:///photo.png", - fileUri: "file:///photo.png", - }; - appAtomRegistry.set(composerAttachmentUploadsAtom, { - "secondary:photo-1": { status: "uploading", progress: 0.5 }, + const firstStarted = Promise.withResolvers(); + const finishFirst = Promise.withResolvers>(); + state.start.mockImplementationOnce(async () => { + firstStarted.resolve(); + return finishFirst.promise; }); - state.cleanups.push(() => appAtomRegistry.set(composerAttachmentUploadsAtom, {})); - await state.manager.enqueue(message({ attachments: [photo] })); + const first = message(); + await state.manager.enqueue(first); startDelivery(); - expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull(); + await firstStarted.promise; + // The queue empties under the running send, then the thread gets its next message. + await state.manager.remove(first); + const allDelivered = Promise.withResolvers(); + const release = appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, () => { + if (remaining().length === 0) allDelivered.resolve(); + }); + await state.manager.enqueue( + message({ messageId: MessageId.make("next"), commandId: CommandId.make("next-command") }), + ); + // The next message waits; only the interrupted send is still marked as sending. + expect(sendingMessageIds()).toEqual(["message"]); + expect(state.start).toHaveBeenCalledOnce(); + finishFirst.resolve(AsyncResult.success({})); + await allDelivered.promise.finally(release); + expect(state.start).toHaveBeenCalledTimes(2); + }); - await deliveryAfter(() => - appAtomRegistry.set(composerAttachmentUploadsAtom, { - "secondary:photo-1": { status: "ready" }, + it("sends another thread's message while one thread's send is still running", async () => { + setOperateGrant("secondary", true); + const other = { ...state.thread, id: "other" }; + appAtomRegistry.set(state.threadShells, [state.thread, other]); + const slowStarted = Promise.withResolvers(); + const finishSlow = Promise.withResolvers>(); + state.start.mockImplementation(async ({ input }: { input: { threadId: string } }) => { + if (input.threadId !== "thread") return AsyncResult.success({}); + slowStarted.resolve(); + return finishSlow.promise; + }); + /** Resolves once only these message ids are still queued. */ + const queuedBecomes = (ids: ReadonlyArray) => { + const reached = Promise.withResolvers(); + const release = appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, () => { + if ( + remaining() + .map((queued) => queued.messageId) + .join() === ids.join() + ) { + reached.resolve(); + } + }); + return reached.promise.finally(release); + }; + await state.manager.enqueue(message()); + startDelivery(); + await slowStarted.promise; + const otherDelivered = queuedBecomes(["message"]); + await state.manager.enqueue( + message({ + threadId: ThreadId.make("other"), + messageId: MessageId.make("other-message"), + commandId: CommandId.make("other-command"), }), ); - expect(state.prepare).toHaveBeenCalledOnce(); - expect(state.start).toHaveBeenCalledOnce(); - expect(remaining()).toEqual([]); + await otherDelivered; + const allDelivered = queuedBecomes([]); + finishSlow.resolve(AsyncResult.success({})); + await allDelivered; + expect(state.start).toHaveBeenCalledTimes(2); }); it("sends at once when its environment reconnects instead of waiting out the backoff", async () => { diff --git a/apps/mobile/src/state/threadOutboxDelivery.test.ts b/apps/mobile/src/state/threadOutboxDelivery.test.ts index f7d67f4349397..aa6e04c1867c8 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.test.ts @@ -2,6 +2,8 @@ import { acknowledgedThreadMessagesAtom, pruneCaughtUpAcknowledgedThreadMessages, } from "./acknowledged-thread-messages"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import { CommandId, EnvironmentId, @@ -10,7 +12,8 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it } from "@effect/vitest"; +import { afterEach, beforeEach, vi } from "vite-plus/test"; import type { PreparedTurnAttachments } from "../lib/attachmentUpload"; @@ -84,6 +87,7 @@ vi.mock("../lib/uuid", () => ({ vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: harness.prepareTurnAttachments, })); +vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() })); vi.mock("./projects", () => ({ environmentProjects: {} })); @@ -119,7 +123,7 @@ vi.mock("./use-thread-outbox", async () => { const { Atom } = await import("effect/reactivity"); return { editingQueuedMessageIdsAtom: Atom.make>({}).pipe(Atom.keepAlive), - dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), + dispatchingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), threadOutboxShellStatusesAtom: Atom.make(new Map()), }; @@ -158,6 +162,7 @@ import { recoverFailedThreadDraft } from "./recover-failed-thread-draft"; import { editingQueuedMessageIdsAtom } from "./use-thread-outbox"; import { completeQueuedMessageDelivery, + type DeliveryRetry, prepareQueuedMessageAttachments, recoverEditedCreationAfterDelivery, removeAcknowledgedExistingThreadMessage, @@ -233,441 +238,522 @@ afterEach(() => { harness.prepareTurnAttachments.mockReset(); }); -describe("thread outbox attachment preparation", () => { - it("keeps a denied message queued without starting its attachment upload", async () => { - const message = queuedMessage({ - messageId: "denied-queued-message", - text: "Keep this queued", - fileUri: "file:///documents/keep.pdf", - }); - await harness.manager.enqueue(message); - harness.prepareTurnAttachments.mockResolvedValueOnce({ - status: "ready", - attachments: [], - draftAttachments: message.attachments, - pendingAttachmentIds: [], - }); - harness.canOperate = false; - await expect(prepareQueuedMessageAttachments(message)).resolves.toEqual({ - status: "abandoned", - }); - expect(harness.prepareTurnAttachments).not.toHaveBeenCalled(); - expect(remainingMessages()).toEqual([message]); - }); +/** True once a delivery step handled its message, false when it asks to retry. */ +const handled = (step: Effect.Effect) => + step.pipe(Effect.as(true), Effect.catchTags({ DeliveryRetry: () => Effect.succeed(false) })); - it("abandons reused uploads when an editor saves changed text during verification", async () => { - const message = withReusedFileUpload( - queuedMessage({ - messageId: "message-reused-upload-race", - text: "original text", - fileUri: "file:///documents/t3-composer-attachments/reused.pdf", - }), - "pending-reused-upload", - ); - const preparationStarted = Promise.withResolvers(); - const preparationBarrier = Promise.withResolvers(); - harness.prepareTurnAttachments.mockImplementationOnce(async () => { - preparationStarted.resolve(); - return preparationBarrier.promise; - }); - await harness.manager.enqueue(message); - appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); - - const preparation = prepareQueuedMessageAttachments(message); - await preparationStarted.promise; - const edited = { ...message, text: "saved editor text" }; - await harness.manager.update(edited); - appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); - preparationBarrier.resolve({ - status: "ready", - attachments: [], - draftAttachments: message.attachments, - pendingAttachmentIds: ["pending-reused-upload"], - }); +describe("thread outbox attachment preparation", () => { + it.effect("keeps a denied message queued without starting its attachment upload", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "denied-queued-message", + text: "Keep this queued", + fileUri: "file:///documents/keep.pdf", + }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + harness.prepareTurnAttachments.mockReturnValueOnce( + Effect.succeed({ + status: "ready", + attachments: [], + draftAttachments: message.attachments, + pendingAttachmentIds: [], + }), + ); + harness.canOperate = false; + expect(yield* prepareQueuedMessageAttachments(message)).toEqual({ + status: "abandoned", + }); + expect(harness.prepareTurnAttachments).not.toHaveBeenCalled(); + expect(remainingMessages()).toEqual([message]); + }), + ); - await expect(preparation).resolves.toEqual({ status: "abandoned" }); - expect(remainingMessages()).toEqual([edited]); - }); + it.effect("abandons reused uploads when an editor saves changed text during verification", () => + Effect.gen(function* () { + const message = withReusedFileUpload( + queuedMessage({ + messageId: "message-reused-upload-race", + text: "original text", + fileUri: "file:///documents/t3-composer-attachments/reused.pdf", + }), + "pending-reused-upload", + ); + const preparationStarted = Promise.withResolvers(); + const preparationBarrier = Promise.withResolvers(); + harness.prepareTurnAttachments.mockImplementationOnce(() => + Effect.promise(() => { + preparationStarted.resolve(); + return preparationBarrier.promise; + }), + ); + yield* Effect.promise(() => harness.manager.enqueue(message)); + appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); - it("uses the known next revision after persisting uploaded references", async () => { - const message = queuedMessage({ - messageId: "message-new-upload-revision", - text: "upload this file", - fileUri: "file:///documents/t3-composer-attachments/new.pdf", - }); - const uploadedAttachments = message.attachments.map((attachment) => - attachment.type === "file" - ? { - ...attachment, - uploadedAttachmentId: "pending-new-upload", - uploadEnvironmentId: message.environmentId, - } - : attachment, - ); - harness.prepareTurnAttachments.mockImplementationOnce(async (input) => { - expect(await input.persistUploadedReferences?.(uploadedAttachments)).toBe("persisted"); - return { + const preparation = yield* Effect.forkChild(prepareQueuedMessageAttachments(message), { + startImmediately: true, + }); + yield* Effect.promise(() => preparationStarted.promise); + const edited = { ...message, text: "saved editor text" }; + yield* Effect.promise(() => harness.manager.update(edited)); + appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); + preparationBarrier.resolve({ status: "ready", attachments: [], - draftAttachments: uploadedAttachments, - pendingAttachmentIds: ["pending-new-upload"], - }; - }); - await harness.manager.enqueue(message); - const revision = harness.manager.revisionOf(message.messageId); + draftAttachments: message.attachments, + pendingAttachmentIds: ["pending-reused-upload"], + }); - const result = await prepareQueuedMessageAttachments(message); + expect(yield* Fiber.join(preparation)).toEqual({ status: "abandoned" }); + expect(remainingMessages()).toEqual([edited]); + }), + ); - expect(result).toMatchObject({ - status: "ready", - persistedMessage: { attachments: uploadedAttachments }, - deliveryRevision: revision + 1, - }); - expect(harness.manager.revisionOf(message.messageId)).toBe(revision + 1); - }); + it.effect("uses the known next revision after persisting uploaded references", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-new-upload-revision", + text: "upload this file", + fileUri: "file:///documents/t3-composer-attachments/new.pdf", + }); + const uploadedAttachments = message.attachments.map((attachment) => + attachment.type === "file" + ? { + ...attachment, + uploadedAttachmentId: "pending-new-upload", + uploadEnvironmentId: message.environmentId, + } + : attachment, + ); + harness.prepareTurnAttachments.mockImplementationOnce((input) => + Effect.gen(function* () { + expect(yield* input.persistUploadedReferences!(uploadedAttachments)).toBe("persisted"); + return { + status: "ready", + attachments: [], + draftAttachments: uploadedAttachments, + pendingAttachmentIds: ["pending-new-upload"], + } as const; + }), + ); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const revision = harness.manager.revisionOf(message.messageId); - it("does not prepare a payload that was already replaced", async () => { - const message = queuedMessage({ messageId: "message-stale-before-upload", text: "old" }); - await harness.manager.enqueue(message); - const edited = { ...message, text: "new" }; - await harness.manager.update(edited); + const result = yield* prepareQueuedMessageAttachments(message); - await expect(prepareQueuedMessageAttachments(message)).resolves.toEqual({ - status: "abandoned", - }); - expect(harness.prepareTurnAttachments).not.toHaveBeenCalled(); - expect(remainingMessages()).toEqual([edited]); - }); -}); + expect(result).toMatchObject({ + status: "ready", + persistedMessage: { attachments: uploadedAttachments }, + deliveryRevision: revision + 1, + }); + expect(harness.manager.revisionOf(message.messageId)).toBe(revision + 1); + }), + ); -describe("thread outbox drain delivery cleanup", () => { - it("drops caught-up acknowledged rows at the next delivery without subscribing to the thread", async () => { - const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" }); - const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" }); - await harness.manager.enqueue(first); - await harness.manager.enqueue(second); - - await expect( - completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId), 7), - ).resolves.toBe("removed"); - expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ - { ...first, sequence: 7 }, - ]); - - // The thread applied the message, but its bounded window does not hold it. - appAtomRegistry.set(harness.threadState, { - data: Option.some({ messages: [{ id: "unrelated" }] }), - sequence: 7, - }); - expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toHaveLength(1); - - await expect( - completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId), 9), - ).resolves.toBe("removed"); - expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ - { ...second, sequence: 9 }, - ]); - }); + it.effect("does not prepare a payload that was already replaced", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-stale-before-upload", text: "old" }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const edited = { ...message, text: "new" }; + yield* Effect.promise(() => harness.manager.update(edited)); - it("drops an acknowledged row once the open thread catches up, so a reload cannot resurrect it", async () => { - const message = queuedMessage({ messageId: "paged-out-later", text: "Delivered" }); - await harness.manager.enqueue(message); - await completeQueuedMessageDelivery(message, harness.manager.revisionOf(message.messageId), 7); + expect(yield* prepareQueuedMessageAttachments(message)).toEqual({ + status: "abandoned", + }); + expect(harness.prepareTurnAttachments).not.toHaveBeenCalled(); + expect(remainingMessages()).toEqual([edited]); + }), + ); +}); - pruneCaughtUpAcknowledgedThreadMessages( - scopedThreadKey(message.environmentId, message.threadId), - { - sequence: 6, - messages: [], - }, - ); - expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ - { ...message, sequence: 7 }, - ]); - - pruneCaughtUpAcknowledgedThreadMessages( - scopedThreadKey(message.environmentId, message.threadId), - { - sequence: 7, - messages: [], - }, - ); - expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([]); - }); +describe("thread outbox drain delivery cleanup", () => { + it.effect( + "drops caught-up acknowledged rows at the next delivery without subscribing to the thread", + () => + Effect.gen(function* () { + const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" }); + const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" }); + yield* Effect.promise(() => harness.manager.enqueue(first)); + yield* Effect.promise(() => harness.manager.enqueue(second)); + + expect( + yield* completeQueuedMessageDelivery( + first, + harness.manager.revisionOf(first.messageId), + 7, + ), + ).toBe("removed"); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ + { ...first, sequence: 7 }, + ]); + + // The thread applied the message, but its bounded window does not hold it. + appAtomRegistry.set(harness.threadState, { + data: Option.some({ messages: [{ id: "unrelated" }] }), + sequence: 7, + }); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toHaveLength(1); + + expect( + yield* completeQueuedMessageDelivery( + second, + harness.manager.revisionOf(second.messageId), + 9, + ), + ).toBe("removed"); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ + { ...second, sequence: 9 }, + ]); + }), + ); - it("removes an acknowledged outbox item even when the sign-out archive write fails", async () => { - const message = queuedMessage({ messageId: "archive-write-failure", text: "Delivered" }); - await harness.manager.enqueue(message); - await composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ - message.environmentId, - ]); - harness.draftFile.setWriteError(new Error("Draft storage unavailable")); - - await expect( - completeQueuedMessageDelivery( - message, - harness.manager.revisionOf(message.messageId), - undefined, - ), - ).resolves.toBe("removed"); - expect(remainingMessages()).toEqual([]); + it.effect( + "drops an acknowledged row once the open thread catches up, so a reload cannot resurrect it", + () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "paged-out-later", text: "Delivered" }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + yield* completeQueuedMessageDelivery( + message, + harness.manager.revisionOf(message.messageId), + 7, + ); + + pruneCaughtUpAcknowledgedThreadMessages( + scopedThreadKey(message.environmentId, message.threadId), + { + sequence: 6, + messages: [], + }, + ); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([ + { ...message, sequence: 7 }, + ]); - harness.draftFile.setWriteError(null); - await composerDrafts.flushComposerDrafts(); - appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { accountId: null, signedOut: {} }); - composerDrafts.resetComposerDraftsLoadState(); - await composerDrafts.restoreCloudComposerDrafts("account-a"); - expect(remainingMessages()).toEqual([]); - }); + pruneCaughtUpAcknowledgedThreadMessages( + scopedThreadKey(message.environmentId, message.threadId), + { + sequence: 7, + messages: [], + }, + ); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([]); + }), + ); - it.each([false, true])( - "does not restore a message delivered after the sign-out snapshot (outbox already cleared: %s)", - async (cleared) => { - const message = queuedMessage({ - messageId: "delivered-during-sign-out", - text: "Already delivered", - }); - await harness.manager.enqueue(message); - const deliveryRevision = harness.manager.revisionOf(message.messageId); - await composerDrafts.archiveCloudComposerDrafts( - "account-a", - new Set([message.environmentId]), - [message.environmentId], + it.effect("removes an acknowledged outbox item even when the sign-out archive write fails", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "archive-write-failure", text: "Delivered" }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + yield* Effect.promise(() => + composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ + message.environmentId, + ]), ); - expect( - appAtomRegistry.get(composerDrafts.composerCloudDraftsAtom).signedOut["account-a"] - ?.queuedMessages, - ).toEqual([message]); + harness.draftFile.setWriteError(new Error("Draft storage unavailable")); - if (cleared) await harness.manager.clearEnvironment(message.environmentId); - await expect( - completeQueuedMessageDelivery(message, deliveryRevision, undefined), - ).resolves.toBe(cleared ? "edited" : "removed"); + expect( + yield* completeQueuedMessageDelivery( + message, + harness.manager.revisionOf(message.messageId), + undefined, + ), + ).toBe("removed"); + expect(remainingMessages()).toEqual([]); + harness.draftFile.setWriteError(null); + yield* Effect.promise(() => composerDrafts.flushComposerDrafts()); appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { accountId: null, signedOut: {}, }); composerDrafts.resetComposerDraftsLoadState(); - await composerDrafts.restoreCloudComposerDrafts("account-a"); + yield* Effect.promise(() => composerDrafts.restoreCloudComposerDrafts("account-a")); expect(remainingMessages()).toEqual([]); - }, + }), ); - it("preserves an archived edit when an older payload finishes delivery", async () => { - const message = queuedMessage({ messageId: "edited-during-sign-out", text: "Original" }); - await harness.manager.enqueue(message); - const deliveryRevision = harness.manager.revisionOf(message.messageId); - const edited = { ...message, text: "Keep this edit" }; - await harness.manager.update(edited); - await composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ - message.environmentId, - ]); - await harness.manager.clearEnvironment(message.environmentId); - await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe( - "edited", - ); - await composerDrafts.restoreCloudComposerDrafts("account-a"); - expect(remainingMessages()).toEqual([edited]); - }); - - it("retries only cleanup after an acknowledged send removal fails", async () => { - const message = queuedMessage({ messageId: "message-acknowledged", text: "delivered" }); - const acknowledged = new Set([message.messageId]); - harness.removeOutboxMessage.mockRejectedValueOnce(new Error("storage unavailable")); - await harness.manager.enqueue(message); - - await expect(removeAcknowledgedExistingThreadMessage(message, acknowledged)).resolves.toBe( - false, - ); - expect(remainingMessages()).toEqual([message]); - expect(acknowledged).toEqual(new Set([message.messageId])); - - await expect(removeAcknowledgedExistingThreadMessage(message, acknowledged)).resolves.toBe( - true, - ); - expect(remainingMessages()).toEqual([]); - expect(acknowledged).toEqual(new Set()); - }); - - it("keeps an edited message and its files when delivery cleanup loses the revision race", async () => { - const message = queuedMessage({ - messageId: "message-edited", - text: "original", - fileUri: "file:///documents/t3-composer-attachments/report.pdf", - }); - await harness.manager.enqueue(message); - const deliveryRevision = harness.manager.revisionOf(message.messageId); - const edited = { ...message, text: "edited while the turn delivered" }; - await harness.manager.update(edited); + it.effect.each([false, true])( + "does not restore a message delivered after the sign-out snapshot (outbox already cleared: %s)", + (cleared) => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "delivered-during-sign-out", + text: "Already delivered", + }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const deliveryRevision = harness.manager.revisionOf(message.messageId); + yield* Effect.promise(() => + composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ + message.environmentId, + ]), + ); + expect( + appAtomRegistry.get(composerDrafts.composerCloudDraftsAtom).signedOut["account-a"] + ?.queuedMessages, + ).toEqual([message]); + + if (cleared) { + yield* Effect.promise(() => harness.manager.clearEnvironment(message.environmentId)); + } + expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( + cleared ? "edited" : "removed", + ); + + appAtomRegistry.set(composerDrafts.composerCloudDraftsAtom, { + accountId: null, + signedOut: {}, + }); + composerDrafts.resetComposerDraftsLoadState(); + yield* Effect.promise(() => composerDrafts.restoreCloudComposerDrafts("account-a")); + expect(remainingMessages()).toEqual([]); + }), + ); - await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe( - "edited", - ); + it.effect("preserves an archived edit when an older payload finishes delivery", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "edited-during-sign-out", text: "Original" }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const deliveryRevision = harness.manager.revisionOf(message.messageId); + const edited = { ...message, text: "Keep this edit" }; + yield* Effect.promise(() => harness.manager.update(edited)); + yield* Effect.promise(() => + composerDrafts.archiveCloudComposerDrafts("account-a", new Set([message.environmentId]), [ + message.environmentId, + ]), + ); + yield* Effect.promise(() => harness.manager.clearEnvironment(message.environmentId)); + expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( + "edited", + ); + yield* Effect.promise(() => composerDrafts.restoreCloudComposerDrafts("account-a")); + expect(remainingMessages()).toEqual([edited]); + }), + ); - expect(remainingMessages()).toEqual([edited]); - expect(harness.removePersistedFile).not.toHaveBeenCalled(); - }); + it.effect("retries only cleanup after an acknowledged send removal fails", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-acknowledged", text: "delivered" }); + const acknowledged = new Set([message.messageId]); + harness.removeOutboxMessage.mockRejectedValueOnce(new Error("storage unavailable")); + yield* Effect.promise(() => harness.manager.enqueue(message)); - it("removes the delivered message when no edit was accepted", async () => { - const message = queuedMessage({ messageId: "message-clean", text: "hello" }); - await harness.manager.enqueue(message); - const deliveryRevision = harness.manager.revisionOf(message.messageId); + expect(yield* handled(removeAcknowledgedExistingThreadMessage(message, acknowledged))).toBe( + false, + ); + expect(remainingMessages()).toEqual([message]); + expect(acknowledged).toEqual(new Set([message.messageId])); - await expect(completeQueuedMessageDelivery(message, deliveryRevision, undefined)).resolves.toBe( - "removed", - ); + expect(yield* handled(removeAcknowledgedExistingThreadMessage(message, acknowledged))).toBe( + true, + ); + expect(remainingMessages()).toEqual([]); + expect(acknowledged).toEqual(new Set()); + }), + ); - expect(remainingMessages()).toEqual([]); - expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([message]); - }); + it.effect( + "keeps an edited message and its files when delivery cleanup loses the revision race", + () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-edited", + text: "original", + fileUri: "file:///documents/t3-composer-attachments/report.pdf", + }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const deliveryRevision = harness.manager.revisionOf(message.messageId); + const edited = { ...message, text: "edited while the turn delivered" }; + yield* Effect.promise(() => harness.manager.update(edited)); + + expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( + "edited", + ); + + expect(remainingMessages()).toEqual([edited]); + expect(harness.removePersistedFile).not.toHaveBeenCalled(); + }), + ); - it("keeps a delivered message when its editor opens during storage removal", async () => { - const message = queuedMessage({ - messageId: "message-editor-removal-race", - text: "keep editor changes", - fileUri: "file:///documents/t3-composer-attachments/editor-race.pdf", - }); - const removeStarted = Promise.withResolvers(); - const removeBarrier = Promise.withResolvers(); - harness.removeOutboxMessage.mockImplementationOnce(async () => { - removeStarted.resolve(); - await removeBarrier.promise; - }); - await harness.manager.enqueue(message); - const deliveryRevision = harness.manager.revisionOf(message.messageId); + it.effect("removes the delivered message when no edit was accepted", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-clean", text: "hello" }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const deliveryRevision = harness.manager.revisionOf(message.messageId); - const cleanup = completeQueuedMessageDelivery(message, deliveryRevision, undefined); - await removeStarted.promise; - appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); - removeBarrier.resolve(); + expect(yield* completeQueuedMessageDelivery(message, deliveryRevision, undefined)).toBe( + "removed", + ); - await expect(cleanup).resolves.toBe("edited"); - expect(remainingMessages()).toEqual([message]); - expect(harness.removePersistedFile).not.toHaveBeenCalled(); - }); -}); + expect(remainingMessages()).toEqual([]); + expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([message]); + }), + ); -describe("thread outbox delivered creation recovery", () => { - it("keeps an edit accepted while the older payload is persisted to the draft", async () => { - const message = queuedMessage({ - messageId: "message-recovery-race", - text: "original queued text", - fileUri: "file:///documents/t3-composer-attachments/report.pdf", - }); - const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent; - const mergeCompleted = Promise.withResolvers(); - const releaseRecovery = Promise.withResolvers(); - const mergeSpy = vi - .spyOn(composerDrafts, "mergeComposerDraftContent") - .mockImplementation(async (draftKey, content) => { - const result = await originalMergeComposerDraftContent(draftKey, content); - mergeCompleted.resolve(); - await releaseRecovery.promise; - return result; + it.effect("keeps a delivered message when its editor opens during storage removal", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-editor-removal-race", + text: "keep editor changes", + fileUri: "file:///documents/t3-composer-attachments/editor-race.pdf", }); - - try { - await harness.manager.enqueue(message); - const recovery = recoverEditedCreationAfterDelivery(message); - await mergeCompleted.promise; - - const newer = { ...message, text: "edited while recovery persisted the draft" }; - await harness.manager.update(newer); - - releaseRecovery.resolve(); - await expect(recovery).resolves.toBe(false); - - expect(remainingMessages()).toEqual([newer]); - expect( - composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`), - ).toMatchObject({ text: message.text, attachments: [] }); - expect(harness.removePersistedFile).not.toHaveBeenCalled(); - } finally { - releaseRecovery.resolve(); - mergeSpy.mockRestore(); - } - }); - - it("leaves recovery to an editor that opens while the draft persists", async () => { - const message = queuedMessage({ - messageId: "message-recovery-editor", - text: "recover this text", - fileUri: "file:///documents/t3-composer-attachments/editor.pdf", - }); - const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent; - const mergeCompleted = Promise.withResolvers(); - const releaseRecovery = Promise.withResolvers(); - const mergeSpy = vi - .spyOn(composerDrafts, "mergeComposerDraftContent") - .mockImplementation(async (draftKey, content) => { - const result = await originalMergeComposerDraftContent(draftKey, content); - mergeCompleted.resolve(); - await releaseRecovery.promise; - return result; + const removeStarted = Promise.withResolvers(); + const removeBarrier = Promise.withResolvers(); + harness.removeOutboxMessage.mockImplementationOnce(async () => { + removeStarted.resolve(); + await removeBarrier.promise; }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + const deliveryRevision = harness.manager.revisionOf(message.messageId); - try { - await harness.manager.enqueue(message); - const recovery = recoverEditedCreationAfterDelivery(message); - await mergeCompleted.promise; + const cleanup = yield* Effect.forkChild( + completeQueuedMessageDelivery(message, deliveryRevision, undefined), + { startImmediately: true }, + ); + yield* Effect.promise(() => removeStarted.promise); appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); + removeBarrier.resolve(); - releaseRecovery.resolve(); - await expect(recovery).resolves.toBe(true); - + expect(yield* Fiber.join(cleanup)).toBe("edited"); expect(remainingMessages()).toEqual([message]); - expect( - composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`), - ).toMatchObject({ text: message.text, attachments: [] }); expect(harness.removePersistedFile).not.toHaveBeenCalled(); - } finally { - releaseRecovery.resolve(); - mergeSpy.mockRestore(); - } - }); - - it("retries a failed removal without duplicating recovered draft content", async () => { - const message = queuedMessage({ - messageId: "message-recovery-removal", - text: "recover once", - fileUri: "file:///documents/t3-composer-attachments/retry.pdf", - }); - const draftKey = `${message.environmentId}:${message.threadId}`; - const removeSpy = vi - .spyOn(harness.manager, "remove") - .mockRejectedValueOnce(new Error("storage unavailable")); + }), + ); +}); - try { - await harness.manager.enqueue(message); +describe("thread outbox delivered creation recovery", () => { + it.effect("keeps an edit accepted while the older payload is persisted to the draft", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-recovery-race", + text: "original queued text", + fileUri: "file:///documents/t3-composer-attachments/report.pdf", + }); + const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent; + const mergeCompleted = Promise.withResolvers(); + const releaseRecovery = Promise.withResolvers(); + const mergeSpy = vi + .spyOn(composerDrafts, "mergeComposerDraftContent") + .mockImplementation(async (draftKey, content) => { + const result = await originalMergeComposerDraftContent(draftKey, content); + mergeCompleted.resolve(); + await releaseRecovery.promise; + return result; + }); + + try { + yield* Effect.promise(() => harness.manager.enqueue(message)); + const recovery = yield* Effect.forkChild( + handled(recoverEditedCreationAfterDelivery(message)), + { startImmediately: true }, + ); + yield* Effect.promise(() => mergeCompleted.promise); + + const newer = { ...message, text: "edited while recovery persisted the draft" }; + yield* Effect.promise(() => harness.manager.update(newer)); + + releaseRecovery.resolve(); + expect(yield* Fiber.join(recovery)).toBe(false); + + expect(remainingMessages()).toEqual([newer]); + expect( + composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`), + ).toMatchObject({ text: message.text, attachments: [] }); + expect(harness.removePersistedFile).not.toHaveBeenCalled(); + } finally { + releaseRecovery.resolve(); + mergeSpy.mockRestore(); + } + }), + ); - await expect(recoverEditedCreationAfterDelivery(message)).resolves.toBe(false); - expect(remainingMessages()).toEqual([message]); + it.effect("leaves recovery to an editor that opens while the draft persists", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-recovery-editor", + text: "recover this text", + fileUri: "file:///documents/t3-composer-attachments/editor.pdf", + }); + const originalMergeComposerDraftContent = composerDrafts.mergeComposerDraftContent; + const mergeCompleted = Promise.withResolvers(); + const releaseRecovery = Promise.withResolvers(); + const mergeSpy = vi + .spyOn(composerDrafts, "mergeComposerDraftContent") + .mockImplementation(async (draftKey, content) => { + const result = await originalMergeComposerDraftContent(draftKey, content); + mergeCompleted.resolve(); + await releaseRecovery.promise; + return result; + }); + + try { + yield* Effect.promise(() => harness.manager.enqueue(message)); + const recovery = yield* Effect.forkChild( + handled(recoverEditedCreationAfterDelivery(message)), + { startImmediately: true }, + ); + yield* Effect.promise(() => mergeCompleted.promise); + appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); - await expect(recoverEditedCreationAfterDelivery(message)).resolves.toBe(true); + releaseRecovery.resolve(); + expect(yield* Fiber.join(recovery)).toBe(true); + + expect(remainingMessages()).toEqual([message]); + expect( + composerDrafts.getComposerDraftSnapshot(`${message.environmentId}:${message.threadId}`), + ).toMatchObject({ text: message.text, attachments: [] }); + expect(harness.removePersistedFile).not.toHaveBeenCalled(); + } finally { + releaseRecovery.resolve(); + mergeSpy.mockRestore(); + } + }), + ); - const draft = composerDrafts.getComposerDraftSnapshot(draftKey); - expect(draft.text).toBe(message.text); - expect(draft.attachments).toEqual(message.attachments); - expect(remainingMessages()).toEqual([]); - expect(harness.removePersistedFile).not.toHaveBeenCalled(); - } finally { - removeSpy.mockRestore(); - } - }); + it.effect("retries a failed removal without duplicating recovered draft content", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-recovery-removal", + text: "recover once", + fileUri: "file:///documents/t3-composer-attachments/retry.pdf", + }); + const draftKey = `${message.environmentId}:${message.threadId}`; + const removeSpy = vi + .spyOn(harness.manager, "remove") + .mockRejectedValueOnce(new Error("storage unavailable")); + + try { + yield* Effect.promise(() => harness.manager.enqueue(message)); + + expect(yield* handled(recoverEditedCreationAfterDelivery(message))).toBe(false); + expect(remainingMessages()).toEqual([message]); + + expect(yield* handled(recoverEditedCreationAfterDelivery(message))).toBe(true); + + const draft = composerDrafts.getComposerDraftSnapshot(draftKey); + expect(draft.text).toBe(message.text); + expect(draft.attachments).toEqual(message.attachments); + expect(remainingMessages()).toEqual([]); + expect(harness.removePersistedFile).not.toHaveBeenCalled(); + } finally { + removeSpy.mockRestore(); + } + }), + ); - it("keeps the queue entry when the recovered draft cannot persist", async () => { - const message = queuedMessage({ - messageId: "message-recovery-persistence", - text: "recover after persistence returns", - }); - await harness.manager.enqueue(message); - harness.draftFile.setWriteError(new Error("disk full")); + it.effect("keeps the queue entry when the recovered draft cannot persist", () => + Effect.gen(function* () { + const message = queuedMessage({ + messageId: "message-recovery-persistence", + text: "recover after persistence returns", + }); + yield* Effect.promise(() => harness.manager.enqueue(message)); + harness.draftFile.setWriteError(new Error("disk full")); - await expect(recoverEditedCreationAfterDelivery(message)).resolves.toBe(false); + expect(yield* handled(recoverEditedCreationAfterDelivery(message))).toBe(false); - expect(remainingMessages()).toEqual([message]); - }); + expect(remainingMessages()).toEqual([message]); + }), + ); }); describe("thread outbox recovery rollback", () => { @@ -720,111 +806,121 @@ describe("thread outbox recovery rollback", () => { ); }); - it("restores a rejected new task as its own draft for the project", async () => { - const message: QueuedThreadMessage = { - ...queuedMessage({ messageId: "message-creation-restore", text: "new task text" }), - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, - creation: { - projectId: ProjectId.make("project-1"), - workspaceMode: "local", - branch: null, - worktreePath: null, - }, - }; - await harness.manager.enqueue(message); + it.effect("restores a rejected new task as its own draft for the project", () => + Effect.gen(function* () { + const message: QueuedThreadMessage = { + ...queuedMessage({ messageId: "message-creation-restore", text: "new task text" }), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, + creation: { + projectId: ProjectId.make("project-1"), + workspaceMode: "local", + branch: null, + worktreePath: null, + }, + }; + yield* Effect.promise(() => harness.manager.enqueue(message)); - await expect(restoreRejectedQueuedMessage(message, "rejected by server")).resolves.toBe( - "restored", - ); + expect(yield* restoreRejectedQueuedMessage(message, "rejected by server")).toBe("restored"); - expect( - composerDrafts.getComposerDraftSnapshot(`new-task:restored-${message.messageId}`), - ).toMatchObject({ - text: message.text, - attachments: message.attachments, - modelSelection: message.modelSelection, - project: { - environmentId: message.environmentId, - projectId: message.creation!.projectId, - createdAt: message.createdAt, - }, - }); - expect(remainingMessages()).toEqual([]); - expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); - expect( - appAtomRegistry.get(pendingThreadCreationOutcomesAtom)[ - `${message.environmentId}:${message.threadId}` - ], - ).toEqual({ kind: "failed", message, reason: "rejected by server" }); - }); + expect( + composerDrafts.getComposerDraftSnapshot(`new-task:restored-${message.messageId}`), + ).toMatchObject({ + text: message.text, + attachments: message.attachments, + modelSelection: message.modelSelection, + project: { + environmentId: message.environmentId, + projectId: message.creation!.projectId, + createdAt: message.createdAt, + }, + }); + expect(remainingMessages()).toEqual([]); + expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); + expect( + appAtomRegistry.get(pendingThreadCreationOutcomesAtom)[ + `${message.environmentId}:${message.threadId}` + ], + ).toEqual({ kind: "failed", message, reason: "rejected by server" }); + }), + ); - it("does not record a creation outcome for a rejected follow-up message", async () => { - const message = queuedMessage({ messageId: "message-followup-restore", text: "follow up" }); - await harness.manager.enqueue(message); + it.effect("does not record a creation outcome for a rejected follow-up message", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-followup-restore", text: "follow up" }); + yield* Effect.promise(() => harness.manager.enqueue(message)); - await expect(restoreRejectedQueuedMessage(message, "rejected")).resolves.toBe("restored"); + expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("restored"); - expect(appAtomRegistry.get(pendingThreadCreationOutcomesAtom)).toEqual({}); - expect( - appAtomRegistry.get(threadComposerErrorsAtom)[`${message.environmentId}:${message.threadId}`], - ).toEqual({ message: "rejected", messageId: message.messageId }); - }); + expect(appAtomRegistry.get(pendingThreadCreationOutcomesAtom)).toEqual({}); + expect( + appAtomRegistry.get(threadComposerErrorsAtom)[ + `${message.environmentId}:${message.threadId}` + ], + ).toEqual({ message: "rejected", messageId: message.messageId }); + }), + ); - it("leaves no error when the restored text is resent before recovery finishes", async () => { - const message = queuedMessage({ messageId: "message-resent", text: "resend me" }); - const threadKey = `${message.environmentId}:${message.threadId}`; - await harness.manager.enqueue(message); - const unsubscribe = appAtomRegistry.subscribe(composerDrafts.composerDraftsAtom, (drafts) => { - if (drafts[threadKey]?.text === "resend me") { - unsubscribe(); - clearThreadComposerError(threadKey); - void composerDrafts.clearComposerDraftContent(threadKey); - } - }); + it.effect("leaves no error when the restored text is resent before recovery finishes", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-resent", text: "resend me" }); + const threadKey = `${message.environmentId}:${message.threadId}`; + yield* Effect.promise(() => harness.manager.enqueue(message)); + const unsubscribe = appAtomRegistry.subscribe(composerDrafts.composerDraftsAtom, (drafts) => { + if (drafts[threadKey]?.text === "resend me") { + unsubscribe(); + clearThreadComposerError(threadKey); + void composerDrafts.clearComposerDraftContent(threadKey); + } + }); - await expect(restoreRejectedQueuedMessage(message, "rejected")).resolves.toBe("restored"); + expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("restored"); - expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); - }); + expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); + }), + ); - it("withdraws the error when an edit makes the recovery back out", async () => { - const message = queuedMessage({ messageId: "message-edited-mid-recovery", text: "edit me" }); - const threadKey = `${message.environmentId}:${message.threadId}`; - await harness.manager.enqueue(message); - const unsubscribe = appAtomRegistry.subscribe(composerDrafts.composerDraftsAtom, (drafts) => { - if (drafts[threadKey]?.text === "edit me") { - unsubscribe(); - appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); - } - }); + it.effect("withdraws the error when an edit makes the recovery back out", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-edited-mid-recovery", text: "edit me" }); + const threadKey = `${message.environmentId}:${message.threadId}`; + yield* Effect.promise(() => harness.manager.enqueue(message)); + const unsubscribe = appAtomRegistry.subscribe(composerDrafts.composerDraftsAtom, (drafts) => { + if (drafts[threadKey]?.text === "edit me") { + unsubscribe(); + appAtomRegistry.set(editingQueuedMessageIdsAtom, { [message.messageId]: true }); + } + }); - await expect(restoreRejectedQueuedMessage(message, "rejected")).resolves.toBe("deferred"); + expect(yield* restoreRejectedQueuedMessage(message, "rejected")).toBe("deferred"); - expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); - expect(remainingMessages()).toEqual([message]); - }); + expect(appAtomRegistry.get(threadComposerErrorsAtom)).toEqual({}); + expect(remainingMessages()).toEqual([message]); + }), + ); - it("rolls a failed recovery merge back so the retry cannot duplicate the text", async () => { - const message = queuedMessage({ messageId: "message-restore", text: "queued text" }); - const draftKey = `${message.environmentId}:${message.threadId}`; - appAtomRegistry.set(composerDrafts.composerDraftsAtom, { - [draftKey]: { text: "typed offline", attachments: [] }, - }); - await harness.manager.enqueue(message); + it.effect("rolls a failed recovery merge back so the retry cannot duplicate the text", () => + Effect.gen(function* () { + const message = queuedMessage({ messageId: "message-restore", text: "queued text" }); + const draftKey = `${message.environmentId}:${message.threadId}`; + appAtomRegistry.set(composerDrafts.composerDraftsAtom, { + [draftKey]: { text: "typed offline", attachments: [] }, + }); + yield* Effect.promise(() => harness.manager.enqueue(message)); - harness.draftFile.setWriteError(new Error("disk full")); - await expect(restoreRejectedQueuedMessage(message, "too large")).resolves.toBe("retry"); + harness.draftFile.setWriteError(new Error("disk full")); + expect(yield* restoreRejectedQueuedMessage(message, "too large")).toBe("retry"); - expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe("typed offline"); - expect(remainingMessages()).toEqual([message]); + expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe("typed offline"); + expect(remainingMessages()).toEqual([message]); - harness.draftFile.setWriteError(null); - await expect(restoreRejectedQueuedMessage(message, "too large")).resolves.toBe("restored"); + harness.draftFile.setWriteError(null); + expect(yield* restoreRejectedQueuedMessage(message, "too large")).toBe("restored"); - expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe( - "typed offline\n\nqueued text", - ); - expect(remainingMessages()).toEqual([]); - expect(appAtomRegistry.get(threadComposerErrorsAtom)[draftKey]?.message).toBe("too large"); - }); + expect(composerDrafts.getComposerDraftSnapshot(draftKey).text).toBe( + "typed offline\n\nqueued text", + ); + expect(remainingMessages()).toEqual([]); + expect(appAtomRegistry.get(threadComposerErrorsAtom)[draftKey]?.message).toBe("too large"); + }), + ); }); diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index 74cf7597e0ef7..5eb87964571db 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -23,13 +23,20 @@ import { } from "@t3tools/contracts"; import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Latch from "effect/Latch"; +import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import { createDebugLogger } from "../lib/debugLog"; +import type { DraftComposerAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn"; import { serializeComposerMessageForServer, uploadedComposerContext } from "../lib/composerContext"; -import { prepareTurnAttachments, type PreparedTurnAttachments } from "../lib/attachmentUpload"; +import { prepareTurnAttachments } from "../lib/attachmentUpload"; import { randomHex } from "../lib/uuid"; import { describeUnavailableModelSelection, @@ -48,11 +55,7 @@ import { } from "./pending-thread-creation"; import { environmentProjects } from "./projects"; import { environmentServerConfigsAtom, serverEnvironment } from "./server"; -import { composerAttachmentUploadsAtom } from "./composer-attachment-upload-states"; -import { - queuedAttachmentsStillUploading, - uploadingComposerAttachmentKeys, -} from "../lib/composerAttachmentUploadQueue"; +import { uploadComposerAttachmentShared } from "./composer-attachment-uploads"; import { gitEnvironment } from "./git"; import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session"; import { @@ -90,7 +93,7 @@ import { waitForComposerDraftsLoaded, } from "./use-composer-drafts"; import { - dispatchingQueuedMessageIdAtom, + dispatchingQueuedMessageIdsAtom, editingQueuedMessageIdsAtom, retryingQueuedMessageIdsAtom, threadOutboxShellStatusesAtom, @@ -175,12 +178,17 @@ function setQueuedMessageRetrying(queuedMessageId: MessageId, retrying: boolean) function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void { // An attempt in flight is sending, even while its retry count is kept. setQueuedMessageRetrying(queuedMessageId, false); - appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId); + appAtomRegistry.set(dispatchingQueuedMessageIdsAtom, { + ...appAtomRegistry.get(dispatchingQueuedMessageIdsAtom), + [queuedMessageId]: true, + }); } function finishDispatchingQueuedMessage(queuedMessageId: MessageId): void { - const current = appAtomRegistry.get(dispatchingQueuedMessageIdAtom); - appAtomRegistry.set(dispatchingQueuedMessageIdAtom, current === queuedMessageId ? null : current); + const { [queuedMessageId]: _finished, ...others } = appAtomRegistry.get( + dispatchingQueuedMessageIdsAtom, + ); + appAtomRegistry.set(dispatchingQueuedMessageIdsAtom, others); } function findThread( @@ -208,53 +216,94 @@ function settingsCommandId(message: QueuedThreadMessage, setting: string): Comma return CommandId.make(`${message.commandId}:${setting}`); } -export async function prepareQueuedMessageAttachments(queuedMessage: QueuedThreadMessage): Promise< - | { - readonly status: "ready"; - readonly prepared: PreparedTurnAttachments; - readonly persistedMessage: QueuedThreadMessage; - readonly deliveryRevision: number; - } - | { readonly status: "abandoned" } -> { - if (!(await confirmThreadOutboxMessageQueued(queuedMessage))) { - return { status: "abandoned" }; - } - if (!readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope)) { - return { status: "abandoned" }; - } - const revision = threadOutboxRevision(queuedMessage.messageId); - if (!isQueuedMessagePayloadCurrent(queuedMessage, revision)) { - return { status: "abandoned" }; - } - let persistedMessage = queuedMessage; - let deliveryRevision = revision; - const result = await prepareTurnAttachments({ - environmentId: queuedMessage.environmentId, - attachments: queuedMessage.attachments, - supportsImageUploads: true, - persistUploadedReferences: async (draftAttachments) => { - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - return "abandon"; - } - const updatedMessage = { ...queuedMessage, attachments: draftAttachments }; - if (!(await updateThreadOutboxMessage(updatedMessage, revision))) { - return "abandon"; - } - persistedMessage = updatedMessage; - deliveryRevision = revision + 1; - return "persisted"; - }, - }); - if ( - result.status === "abandoned" || - !isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) - ) { - return { status: "abandoned" }; +/** Outbox or draft storage refused a step; the step decides what that means for the message. */ +class ThreadOutboxStorageError extends Schema.TaggedError()( + "ThreadOutboxStorageError", + { + operation: Schema.Literals([ + "forget-sign-out-snapshot", + "remove-delivered", + "remove-acknowledged", + "remove-unsendable", + "hand-back-to-draft", + "restore-to-draft", + "undo-draft-merge", + "load-drafts", + "flush-drafts", + "remove-recovered", + "remove-restored", + ]), + messageId: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Queued message ${this.messageId} could not ${this.operation.replaceAll("-", " ")}.`; } - return { status: "ready", prepared: result, persistedMessage, deliveryRevision }; } +const storage = ( + operation: ThreadOutboxStorageError["operation"], + messageId: MessageId, + write: () => Promise, +) => + Effect.tryPromise({ + try: write, + catch: (cause) => new ThreadOutboxStorageError({ operation, messageId, cause }), + }); + +/** The head was not handled; back off and try it again. */ +export class DeliveryRetry extends Schema.TaggedError()("DeliveryRetry", {}) {} + +const retryDelivery = Effect.fail(new DeliveryRetry()); + +const isEditingQueuedMessage = (messageId: MessageId): boolean => + appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId] === true; + +const confirmQueued = (message: QueuedThreadMessage) => + Effect.promise(() => confirmThreadOutboxMessageQueued(message)); + +const abandoned = { status: "abandoned" } as const; + +export const prepareQueuedMessageAttachments = Effect.fn("ThreadOutbox.prepareAttachments")( + function* (queuedMessage: QueuedThreadMessage) { + if (!(yield* confirmQueued(queuedMessage))) return abandoned; + if (!readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope)) { + return abandoned; + } + const revision = threadOutboxRevision(queuedMessage.messageId); + if (!isQueuedMessagePayloadCurrent(queuedMessage, revision)) return abandoned; + let persistedMessage = queuedMessage; + let deliveryRevision = revision; + const result = yield* prepareTurnAttachments({ + environmentId: queuedMessage.environmentId, + attachments: queuedMessage.attachments, + supportsImageUploads: true, + uploadAttachment: (attachment) => + uploadComposerAttachmentShared(queuedMessage.environmentId, attachment), + persistUploadedReferences: Effect.fn("ThreadOutbox.persistUploadedReferences")(function* ( + draftAttachments: ReadonlyArray, + ) { + if (isEditingQueuedMessage(queuedMessage.messageId)) return "abandon" as const; + const updatedMessage = { ...queuedMessage, attachments: draftAttachments }; + if (!(yield* Effect.promise(() => updateThreadOutboxMessage(updatedMessage, revision)))) { + return "abandon" as const; + } + persistedMessage = updatedMessage; + deliveryRevision = revision + 1; + return "persisted" as const; + }), + }); + if ( + result.status === "abandoned" || + !isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) + ) { + return abandoned; + } + return { status: "ready", prepared: result, persistedMessage, deliveryRevision } as const; + }, +); + function isQueuedMessagePayloadCurrent( message: QueuedThreadMessage, expectedRevision: number, @@ -267,273 +316,279 @@ function isQueuedMessagePayloadCurrent( ); } -export async function completeQueuedMessageDelivery( +const forgetCloudQueuedMessage = (queuedMessage: QueuedThreadMessage) => + storage("forget-sign-out-snapshot", queuedMessage.messageId, () => + removeDeliveredCloudQueuedMessage(queuedMessage), + ).pipe( + Effect.catch((error) => + Effect.logWarning("[thread-outbox] could not update sign-out snapshot after delivery", { + messageId: queuedMessage.messageId, + error: error.cause, + }), + ), + ); + +export const completeQueuedMessageDelivery = Effect.fn("ThreadOutbox.completeDelivery")(function* ( queuedMessage: QueuedThreadMessage, deliveryRevision: number, - sequence: number | undefined, -): Promise<"removed" | "edited" | "failed"> { + sequence?: number, +) { clearThreadComposerError( scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId), queuedMessage.messageId, ); - try { - await removeDeliveredCloudQueuedMessage(queuedMessage).catch((error) => { - console.warn("[thread-outbox] could not update sign-out snapshot after delivery", { - messageId: queuedMessage.messageId, - error, - }); - }); - // Editors can acquire entries during startTurn without bumping revisions; CAS alone would lose unsaved edits. - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - return "edited"; - } - retainAcknowledgedThreadMessage( - sequence === undefined ? queuedMessage : { ...queuedMessage, sequence }, - ); - const removed = await removeThreadOutboxMessage( + yield* forgetCloudQueuedMessage(queuedMessage); + // Editors can acquire entries during startTurn without bumping revisions; CAS alone would lose unsaved edits. + if (isEditingQueuedMessage(queuedMessage.messageId)) return "edited" as const; + retainAcknowledgedThreadMessage( + sequence === undefined ? queuedMessage : { ...queuedMessage, sequence }, + ); + const removed = yield* storage("remove-delivered", queuedMessage.messageId, () => + removeThreadOutboxMessage( queuedMessage, deliveryRevision, - () => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId], - ); - if (!removed) { - forgetAcknowledgedThreadMessage(queuedMessage); - threadOutboxDebug.log("delivered message was edited before cleanup", { + () => !isEditingQueuedMessage(queuedMessage.messageId), + ), + ).pipe( + Effect.catch((error) => + Effect.logWarning("[thread-outbox] failed to remove delivered queued message", { environmentId: queuedMessage.environmentId, threadId: queuedMessage.threadId, messageId: queuedMessage.messageId, - }); - return "edited"; - } - return "removed"; - } catch (error) { - forgetAcknowledgedThreadMessage(queuedMessage); - console.warn("[thread-outbox] failed to remove delivered queued message", { - environmentId: queuedMessage.environmentId, - threadId: queuedMessage.threadId, - messageId: queuedMessage.messageId, - error, - }); - return "failed"; - } -} + error: error.cause, + }).pipe(Effect.as(null)), + ), + ); + if (removed === true) return "removed" as const; + forgetAcknowledgedThreadMessage(queuedMessage); + if (removed === null) return "failed" as const; + threadOutboxDebug.log("delivered message was edited before cleanup", { + environmentId: queuedMessage.environmentId, + threadId: queuedMessage.threadId, + messageId: queuedMessage.messageId, + }); + return "edited" as const; +}); -export async function removeAcknowledgedExistingThreadMessage( - queuedMessage: QueuedThreadMessage, - acknowledgedMessageIds: Set, -): Promise { - try { - await removeDeliveredCloudQueuedMessage(queuedMessage).catch((error) => { - console.warn("[thread-outbox] could not update sign-out snapshot after delivery", { +export const removeAcknowledgedExistingThreadMessage = Effect.fn( + "ThreadOutbox.removeAcknowledgedMessage", +)(function* (queuedMessage: QueuedThreadMessage, acknowledgedMessageIds: Set) { + yield* forgetCloudQueuedMessage(queuedMessage); + const removed = yield* storage("remove-acknowledged", queuedMessage.messageId, () => + removeThreadOutboxMessage(queuedMessage), + ).pipe( + Effect.catch((error) => + Effect.logWarning("[thread-outbox] failed to remove acknowledged queued message", { + environmentId: queuedMessage.environmentId, + threadId: queuedMessage.threadId, messageId: queuedMessage.messageId, - error, - }); - }); - const removed = await removeThreadOutboxMessage(queuedMessage); - if (removed) { - acknowledgedMessageIds.delete(queuedMessage.messageId); - } - return removed; - } catch (error) { - console.warn("[thread-outbox] failed to remove acknowledged queued message", { - environmentId: queuedMessage.environmentId, - threadId: queuedMessage.threadId, - messageId: queuedMessage.messageId, - error, - }); - return false; - } -} + error: error.cause, + }).pipe(Effect.as(false)), + ), + ); + if (!removed) return yield* retryDelivery; + acknowledgedMessageIds.delete(queuedMessage.messageId); +}); -export async function recoverEditedCreationAfterDelivery( - queuedMessage: QueuedThreadMessage, -): Promise { - const kept = Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom)) - .flat() - .find((candidate) => candidate.messageId === queuedMessage.messageId); - if (!kept) { - return true; - } - const keptRevision = threadOutboxRevision(kept.messageId); - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) { - return true; - } - const draftKey = scopedThreadKey(kept.environmentId, kept.threadId); - try { - // Merge before removal to retain file ownership; allow overflow and let send guards require trimming. - await mergeComposerDraftContent(draftKey, { - text: kept.text, - context: kept.context, - attachments: [], - }); - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) { - return true; - } - if (threadOutboxRevision(kept.messageId) !== keptRevision) { - return false; - } - const existingAttachmentIds = new Set( - getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id), - ); - appendComposerDraftAttachments( - draftKey, - kept.attachments.filter((attachment) => !existingAttachmentIds.has(attachment.id)), - { restore: true }, +/** Hands a new task edited after its launch back to the composer, then drops it from the queue. */ +export const recoverEditedCreationAfterDelivery = Effect.fn("ThreadOutbox.recoverEditedCreation")( + function* (queuedMessage: QueuedThreadMessage) { + const kept = Object.values( + appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + ) + .flat() + .find((candidate) => candidate.messageId === queuedMessage.messageId); + if (!kept || isEditingQueuedMessage(kept.messageId)) return; + const keptRevision = threadOutboxRevision(kept.messageId); + const draftKey = scopedThreadKey(kept.environmentId, kept.threadId); + const handedBack = yield* Effect.gen(function* () { + // Merge before removal to retain file ownership; allow overflow and let send guards require trimming. + yield* storage("hand-back-to-draft", kept.messageId, () => + mergeComposerDraftContent(draftKey, { + text: kept.text, + context: kept.context, + attachments: [], + }), + ); + if (isEditingQueuedMessage(kept.messageId)) return "edited" as const; + if (threadOutboxRevision(kept.messageId) !== keptRevision) return "changed" as const; + const existingAttachmentIds = new Set( + getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id), + ); + appendComposerDraftAttachments( + draftKey, + kept.attachments.filter((attachment) => !existingAttachmentIds.has(attachment.id)), + { restore: true }, + ); + updateComposerDraftSettings(draftKey, { + ...(kept.modelSelection !== undefined ? { modelSelection: kept.modelSelection } : {}), + ...(kept.runtimeMode !== undefined ? { runtimeMode: kept.runtimeMode } : {}), + ...(kept.interactionMode !== undefined ? { interactionMode: kept.interactionMode } : {}), + }); + // Flush before removal: append only schedules persistence, leaving the queue as the sole durable copy. + yield* storage("flush-drafts", kept.messageId, () => flushComposerDrafts()); + return "handed-back" as const; + }).pipe( + Effect.catch((error) => + Effect.logWarning( + "[thread-outbox] could not hand an edited pending task to the composer", + error.cause, + ).pipe(Effect.as("failed" as const)), + ), ); - updateComposerDraftSettings(draftKey, { - ...(kept.modelSelection !== undefined ? { modelSelection: kept.modelSelection } : {}), - ...(kept.runtimeMode !== undefined ? { runtimeMode: kept.runtimeMode } : {}), - ...(kept.interactionMode !== undefined ? { interactionMode: kept.interactionMode } : {}), - }); - // Flush before removal: append only schedules persistence, leaving the queue as the sole durable copy. - await flushComposerDrafts(); - } catch (error) { - console.warn("[thread-outbox] could not hand an edited pending task to the composer", error); - return false; - } - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) { - return true; - } - try { - return await removeThreadOutboxMessage( - kept, - keptRevision, - () => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId], + if (handedBack === "edited") return; + if (handedBack !== "handed-back") return yield* retryDelivery; + if (isEditingQueuedMessage(kept.messageId)) return; + const removed = yield* storage("remove-recovered", kept.messageId, () => + removeThreadOutboxMessage(kept, keptRevision, () => !isEditingQueuedMessage(kept.messageId)), + ).pipe( + Effect.catch((error) => + Effect.logWarning( + "[thread-outbox] could not remove recovered pending task", + error.cause, + ).pipe(Effect.as(false)), + ), ); - } catch (error) { - console.warn("[thread-outbox] could not remove recovered pending task", error); - return false; - } -} - -export async function restoreRejectedQueuedMessage( - queuedMessage: QueuedThreadMessage, - message: string, -): Promise<"restored" | "deferred" | "blocked" | "retry"> { - const draftKey = recoveryDraftKey(queuedMessage); - const threadKey = scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId); - let rollback: { readonly snapshot: ComposerDraft; readonly merged: ComposerDraft } | null = null; - try { - if ( - appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] || - !(await confirmThreadOutboxMessageQueued(queuedMessage)) || - appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] - ) { - return "deferred"; - } - const revision = threadOutboxRevision(queuedMessage.messageId); + if (!removed) return yield* retryDelivery; + }, +); - await waitForComposerDraftsLoaded(); - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - return "deferred"; - } - const originalDraft = getComposerDraftSnapshot(draftKey); - const existingAttachmentIds = new Set( - originalDraft.attachments.map((attachment) => attachment.id), - ); - const addedAttachmentCount = queuedMessage.attachments.filter( - (attachment) => !existingAttachmentIds.has(attachment.id), - ).length; - if (existingAttachmentIds.size + addedAttachmentCount > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { - setThreadComposerError( - threadKey, - `Remove attachments from the draft before restoring this message. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`, - queuedMessage.messageId, +/** + * Hands an undeliverable message back to its draft with the reason. "blocked" means the draft + * cannot take it yet (attachment cap); "deferred" means an editor or newer write owns it. + */ +export const restoreRejectedQueuedMessage = Effect.fn("ThreadOutbox.restoreRejectedMessage")( + function* (queuedMessage: QueuedThreadMessage, message: string) { + const draftKey = recoveryDraftKey(queuedMessage); + const threadKey = scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId); + const editing = () => isEditingQueuedMessage(queuedMessage.messageId); + // Until the queue drops the message, a failure undoes the merge, keeping concurrent edits. + let rollback: { readonly snapshot: ComposerDraft; readonly merged: ComposerDraft } | null = + null; + const undo = (snapshot: ComposerDraft, merged: ComposerDraft) => + storage("undo-draft-merge", queuedMessage.messageId, () => + undoComposerDraftMerge(draftKey, snapshot, merged), ); - return "blocked"; - } + return yield* Effect.gen(function* () { + if (editing() || !(yield* confirmQueued(queuedMessage)) || editing()) { + return "deferred" as const; + } + const revision = threadOutboxRevision(queuedMessage.messageId); + yield* storage("load-drafts", queuedMessage.messageId, () => waitForComposerDraftsLoaded()); + if (editing()) return "deferred" as const; + const originalDraft = getComposerDraftSnapshot(draftKey); + const existingAttachmentIds = new Set( + originalDraft.attachments.map((attachment) => attachment.id), + ); + const addedAttachmentCount = queuedMessage.attachments.filter( + (attachment) => !existingAttachmentIds.has(attachment.id), + ).length; + if (existingAttachmentIds.size + addedAttachmentCount > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + setThreadComposerError( + threadKey, + `Remove attachments from the draft before restoring this message. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`, + queuedMessage.messageId, + ); + return "blocked" as const; + } - const withdrawError = () => clearThreadComposerError(threadKey, queuedMessage.messageId); - if (!queuedMessage.creation) { - setThreadComposerError(threadKey, message, queuedMessage.messageId); - } - let mergedDraft: ComposerDraft; - try { + const withdraw = (merged: ComposerDraft) => + Effect.sync(() => clearThreadComposerError(threadKey, queuedMessage.messageId)).pipe( + Effect.andThen(undo(originalDraft, merged)), + Effect.as("deferred" as const), + ); + if (!queuedMessage.creation) { + setThreadComposerError(threadKey, message, queuedMessage.messageId); + } stampRecoveryDraftProject(queuedMessage, draftKey); - await mergeComposerDraftContent(draftKey, { - text: queuedMessage.text, - context: queuedMessage.context, - attachments: queuedMessage.attachments, - }); - } finally { - // Capture rollback in finally because merge publishes even on persistence failure; undo must preserve concurrent edits. - mergedDraft = getComposerDraftSnapshot(draftKey); - rollback = { snapshot: originalDraft, merged: mergedDraft }; - } - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - withdrawError(); - await undoComposerDraftMerge(draftKey, originalDraft, mergedDraft); - return "deferred"; - } - updateComposerDraftSettings(draftKey, { - ...(queuedMessage.modelSelection ? { modelSelection: queuedMessage.modelSelection } : {}), - ...(queuedMessage.runtimeMode ? { runtimeMode: queuedMessage.runtimeMode } : {}), - ...(queuedMessage.interactionMode ? { interactionMode: queuedMessage.interactionMode } : {}), - ...(queuedMessage.freshContext ? { freshContext: true } : {}), - ...(queuedMessage.creation - ? { - workspaceSelection: { - mode: queuedMessage.creation.workspaceMode, - branch: queuedMessage.creation.branch, - worktreePath: queuedMessage.creation.worktreePath, - pullRequestReference: queuedMessage.creation.pullRequestReference, - ...(queuedMessage.creation.startFromOrigin !== undefined - ? { startFromOrigin: queuedMessage.creation.startFromOrigin } - : {}), - }, - } - : {}), - }); - const restoredDraft = getComposerDraftSnapshot(draftKey); - rollback = { snapshot: originalDraft, merged: restoredDraft }; - await flushComposerDrafts(); - if ( - appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] || - !(await confirmThreadOutboxMessageQueued(queuedMessage)) || - appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] - ) { - withdrawError(); - await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft); - return "deferred"; - } - if ( - !(await removeThreadOutboxMessage( - queuedMessage, - revision, - () => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId], - )) - ) { - withdrawError(); - await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft); - return "deferred"; - } - // After queue removal, the draft owns content and must never roll back. - rollback = null; - if (queuedMessage.creation) { - withdrawError(); - recordPendingThreadCreationOutcome({ - kind: "failed", - message: queuedMessage, - reason: message, + // The merge publishes even when persisting it fails, so the rollback is captured either way. + yield* storage("restore-to-draft", queuedMessage.messageId, () => + mergeComposerDraftContent(draftKey, { + text: queuedMessage.text, + context: queuedMessage.context, + attachments: queuedMessage.attachments, + }), + ).pipe( + Effect.ensuring( + Effect.sync(() => { + rollback = { snapshot: originalDraft, merged: getComposerDraftSnapshot(draftKey) }; + }), + ), + ); + if (editing()) return yield* withdraw(getComposerDraftSnapshot(draftKey)); + updateComposerDraftSettings(draftKey, { + ...(queuedMessage.modelSelection ? { modelSelection: queuedMessage.modelSelection } : {}), + ...(queuedMessage.runtimeMode ? { runtimeMode: queuedMessage.runtimeMode } : {}), + ...(queuedMessage.interactionMode + ? { interactionMode: queuedMessage.interactionMode } + : {}), + ...(queuedMessage.freshContext ? { freshContext: true } : {}), + ...(queuedMessage.creation + ? { + workspaceSelection: { + mode: queuedMessage.creation.workspaceMode, + branch: queuedMessage.creation.branch, + worktreePath: queuedMessage.creation.worktreePath, + pullRequestReference: queuedMessage.creation.pullRequestReference, + ...(queuedMessage.creation.startFromOrigin !== undefined + ? { startFromOrigin: queuedMessage.creation.startFromOrigin } + : {}), + }, + } + : {}), }); - } - return "restored"; - } catch (error) { - if (rollback !== null) { - await undoComposerDraftMerge(draftKey, rollback.snapshot, rollback.merged).catch( - (undoError) => { - console.warn("[thread-outbox] failed to persist a recovery rollback", undoError); - }, + const restoredDraft = getComposerDraftSnapshot(draftKey); + rollback = { snapshot: originalDraft, merged: restoredDraft }; + yield* storage("flush-drafts", queuedMessage.messageId, () => flushComposerDrafts()); + if (editing() || !(yield* confirmQueued(queuedMessage)) || editing()) { + return yield* withdraw(restoredDraft); + } + const removed = yield* storage("remove-restored", queuedMessage.messageId, () => + removeThreadOutboxMessage(queuedMessage, revision, () => !editing()), ); - } - console.warn("[thread-outbox] failed to restore an undeliverable message", error); - setThreadComposerError( - threadKey, - error instanceof Error ? error.message : "The unsent message could not be restored.", - queuedMessage.messageId, + if (!removed) return yield* withdraw(restoredDraft); + // After queue removal, the draft owns content and must never roll back. + rollback = null; + if (queuedMessage.creation) { + clearThreadComposerError(threadKey, queuedMessage.messageId); + recordPendingThreadCreationOutcome({ + kind: "failed", + message: queuedMessage, + reason: message, + }); + } + return "restored" as const; + }).pipe( + Effect.catch((error) => + Effect.gen(function* () { + const pending: typeof rollback = rollback; + if (pending !== null) { + yield* undo(pending.snapshot, pending.merged).pipe( + Effect.catch((undoError) => + Effect.logWarning( + "[thread-outbox] failed to persist a recovery rollback", + undoError.cause, + ), + ), + ); + } + yield* Effect.logWarning( + "[thread-outbox] failed to restore an undeliverable message", + error.cause, + ); + setThreadComposerError( + threadKey, + error.cause instanceof Error + ? error.cause.message + : "The unsent message could not be restored.", + queuedMessage.messageId, + ); + return "retry" as const; + }), + ), ); - return "retry"; - } -} + }, +); /** Derive keys from message ids so failed recovery retries reuse the same draft. */ function recoveryDraftKey(queuedMessage: QueuedThreadMessage): string { @@ -555,14 +610,10 @@ function stampRecoveryDraftProject(queuedMessage: QueuedThreadMessage, draftKey: }); } -async function preserveUploadedAttachmentsForEditor( - originalMessage: QueuedThreadMessage, - uploadedMessage: QueuedThreadMessage, -): Promise { - if (!originalMessage.creation) { - return; - } - +const preserveUploadedAttachmentsForEditor = Effect.fn( + "ThreadOutbox.preserveUploadedAttachmentsForEditor", +)(function* (originalMessage: QueuedThreadMessage, uploadedMessage: QueuedThreadMessage) { + if (!originalMessage.creation) return; const draftKey = `pending-task:${originalMessage.messageId}`; const draft = getComposerDraftSnapshot(draftKey); const uploadedById = new Map( @@ -586,18 +637,13 @@ async function preserveUploadedAttachmentsForEditor( uploadEnvironmentId: uploaded.uploadEnvironmentId, }; }); - if (changed) { - replaceComposerDraftAttachments(draftKey, nextAttachments); - await flushComposerDrafts(); - } -} + if (!changed) return; + replaceComposerDraftAttachments(draftKey, nextAttachments); + yield* Effect.promise(() => flushComposerDrafts()); +}); -// Everything a drain pass decides from. Each queued environment's session is -// read here so a granted or revoked operate scope re-runs the drain. -const uploadingComposerAttachmentKeysAtom = Atom.map( - composerAttachmentUploadsAtom, - uploadingComposerAttachmentKeys, -); +// Everything delivery decides from. Each queued environment's session is read +// here so a granted or revoked operate scope wakes delivery. const deliveryInputsAtom = Atom.make((get) => { const connectedEnvironments = get(workspaceConnections.environmentsAtom); @@ -613,7 +659,6 @@ const deliveryInputsAtom = Atom.make((get) => { } } return { - dispatchingQueuedMessageId: get(dispatchingQueuedMessageIdAtom), editingQueuedMessageIds: get(editingQueuedMessageIdsAtom), queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom), shellStatuses: get(threadOutboxShellStatusesAtom), @@ -622,8 +667,6 @@ const deliveryInputsAtom = Atom.make((get) => { serverConfigs: get(environmentServerConfigsAtom), connectedEnvironments, operableEnvironments, - // Wakes a message waiting on the upload worker when that upload settles. - uploadingAttachmentKeys: get(uploadingComposerAttachmentKeysAtom), }; }).pipe(Atom.withLabel("mobile:thread-outbox:delivery-inputs")); @@ -653,11 +696,11 @@ function deliveredSequence( return AsyncResult.isSuccess(result) ? result.value.sequence : undefined; } -const runDeliveryCommand = ( +const deliveryCommand = ( command: AtomCommand, input: W, -): Promise> => - runAtomCommand(appAtomRegistry, command, input, { reportFailure: false }); +): Effect.Effect> => + Effect.promise(() => runAtomCommand(appAtomRegistry, command, input, { reportFailure: false })); function reportCommandFailure( queuedMessage: QueuedThreadMessage, @@ -688,14 +731,33 @@ function reportCommandFailure( interface ThreadOutboxRetry { readonly attempt: number; readonly notBefore: number; - readonly timer: ReturnType; } +/** A thread's delivery fiber; `retiring` once interrupted, until the fiber has exited. */ +interface ThreadFiber { + readonly wake: Latch.Latch; + fiber: Fiber.Fiber | undefined; + retiring: boolean; +} + +/** What a thread's delivery fiber does next with the head of its queue. */ +type ThreadDeliveryStep = + /** Nothing to send until an input changes, or until `until` when a backoff is running. */ + | { readonly _tag: "Wait"; readonly until?: number } + /** The head failed without a send; back off before trying it again. */ + | { readonly _tag: "Backoff"; readonly messageId: MessageId } + | { + readonly _tag: "Dispatch"; + readonly messageId: MessageId; + /** Succeeds once the message is handled (sent, removed or handed back). */ + readonly run: Effect.Effect; + }; + /** - * Delivers queued thread messages one at a time. A drain pass runs whenever its inputs - * change (outbox, locks, shells, projects, configs, connections, scopes) and when a retry - * backoff expires. `dispatchingQueuedMessageIdAtom` is the single in-flight slot; clearing - * it re-runs the drain for the next message. + * Delivers queued thread messages, one fiber per thread so a slow send in one thread never + * holds another. Each fiber sends its thread's head message in order, backs off after a + * failure, and otherwise waits until an input changes (outbox, locks, shells, projects, + * configs, connections, scopes). */ export function createThreadOutboxDelivery(): { readonly drain: () => void; @@ -725,52 +787,29 @@ export function createThreadOutboxDelivery(): { const scheduleRetry = (messageId: MessageId): void => { if (disposed) return; - const previous = retries.get(messageId); - if (previous !== undefined) clearTimeout(previous.timer); - const attempt = (previous?.attempt ?? 0) + 1; - const delayMs = threadOutboxRetryDelayMs(attempt); + const attempt = (retries.get(messageId)?.attempt ?? 0) + 1; retries.set(messageId, { attempt, - notBefore: Date.now() + delayMs, - timer: setTimeout(drain, delayMs), + notBefore: Date.now() + threadOutboxRetryDelayMs(attempt), }); setQueuedMessageRetrying(messageId, true); }; const clearRetry = (messageId: MessageId): void => { - const retry = retries.get(messageId); - if (retry === undefined) return; - clearTimeout(retry.timer); - retries.delete(messageId); + if (!retries.delete(messageId)) return; setQueuedMessageRetrying(messageId, false); }; - // A delivery that throws backs off like any failure. Releasing the slot - // without a retry would re-run the drain straight into the same message. - const settle = (messageId: MessageId, delivery: Promise): void => { - void delivery - .then( - (sent) => (sent ? clearRetry(messageId) : scheduleRetry(messageId)), - (error: unknown) => { - console.warn("[thread-outbox] queued message delivery threw", { messageId, error }); - scheduleRetry(messageId); - }, - ) - .finally(() => finishDispatchingQueuedMessage(messageId)); - }; - // An over-cap draft blocks recovery until the user changes its attachments; // parking on the draft avoids hammering the restore with backoff retries. - const restoreQueuedMessage = async ( + const restoreQueuedMessage = Effect.fn("ThreadOutbox.restoreQueuedMessage")(function* ( queuedMessage: QueuedThreadMessage, message: string, - ): Promise => { - const result = await restoreRejectedQueuedMessage(queuedMessage, message); - if (result !== "blocked") { - return result !== "retry"; - } - if (disposed || blockedRecoveries.has(queuedMessage.messageId)) { - return true; + ) { + const result = yield* restoreRejectedQueuedMessage(queuedMessage, message); + if (result === "retry") return yield* retryDelivery; + if (result !== "blocked" || disposed || blockedRecoveries.has(queuedMessage.messageId)) { + return; } const draftKey = recoveryDraftKey(queuedMessage); const editorDraftKey = queuedMessage.creation @@ -793,23 +832,22 @@ export function createThreadOutboxDelivery(): { } blockedRecoveries.delete(queuedMessage.messageId); active.unsubscribe(); - drain(); + wakeThreads(); }); blockedRecoveries.set(queuedMessage.messageId, { message: queuedMessage, unsubscribe }); - return true; - }; + }); - const sendQueuedMessage = async ( + const sendQueuedMessage = Effect.fn("ThreadOutbox.sendQueuedMessage")(function* ( queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell, - ): Promise => { + ) { const hasAccess = () => readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope); - if (!hasAccess()) return true; + if (!hasAccess()) return; const serverConfig = appAtomRegistry.get( serverEnvironment.configValueAtom(queuedMessage.environmentId), ); - if (!serverConfig) return false; + if (!serverConfig) return yield* retryDelivery; const settings = resolveQueuedThreadSettings(queuedMessage, thread, serverConfig.providers); if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, thread.projectId)) { const { title, detail } = describeUnavailableModelSelection( @@ -817,7 +855,7 @@ export function createThreadOutboxDelivery(): { settings.modelSelection, thread.projectId, ); - return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); + return yield* restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); } // The server would refuse this mode in settings sync, which retries forever; stop first. const runtimeModeDenial = managedRuntimeModeDenial( @@ -825,12 +863,12 @@ export function createThreadOutboxDelivery(): { settings.runtimeMode, ); if (runtimeModeDenial !== undefined) { - return restoreQueuedMessage(queuedMessage, runtimeModeDenial); + return yield* restoreQueuedMessage(queuedMessage, runtimeModeDenial); } if (settings.runtimeMode !== thread.runtimeMode) { - if (!hasAccess()) return true; - const runtimeResult = await runDeliveryCommand(threadEnvironment.setRuntimeMode, { + if (!hasAccess()) return; + const runtimeResult = yield* deliveryCommand(threadEnvironment.setRuntimeMode, { environmentId: queuedMessage.environmentId, input: { commandId: settingsCommandId(queuedMessage, "runtime-mode"), @@ -841,13 +879,13 @@ export function createThreadOutboxDelivery(): { }); if (AsyncResult.isFailure(runtimeResult)) { reportCommandFailure(queuedMessage, runtimeResult, "settings-sync"); - return false; + return yield* retryDelivery; } } if (settings.interactionMode !== thread.interactionMode) { - if (!hasAccess()) return true; - const interactionResult = await runDeliveryCommand(threadEnvironment.setInteractionMode, { + if (!hasAccess()) return; + const interactionResult = yield* deliveryCommand(threadEnvironment.setInteractionMode, { environmentId: queuedMessage.environmentId, input: { commandId: settingsCommandId(queuedMessage, "interaction-mode"), @@ -858,51 +896,48 @@ export function createThreadOutboxDelivery(): { }); if (AsyncResult.isFailure(interactionResult)) { reportCommandFailure(queuedMessage, interactionResult, "settings-sync"); - return false; + return yield* retryDelivery; } } - let prepared: PreparedTurnAttachments; - let persistedMessage: QueuedThreadMessage; - let deliveryRevision: number; - if (!hasAccess()) return true; - try { - const preparedResult = await prepareQueuedMessageAttachments(queuedMessage); - if (preparedResult.status === "abandoned") { - return true; - } - prepared = preparedResult.prepared; - persistedMessage = preparedResult.persistedMessage; - deliveryRevision = preparedResult.deliveryRevision; - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - await preserveUploadedAttachmentsForEditor(queuedMessage, preparedResult.persistedMessage); - return true; - } - } catch (error) { - if (!hasAccess()) return true; + if (!hasAccess()) return; + // Waiting on the shared upload is the one part of a send that may be cut short. + const preparedExit = yield* Effect.exit( + Effect.interruptible(prepareQueuedMessageAttachments(queuedMessage)), + ); + if (Exit.isFailure(preparedExit)) { + if (Cause.hasInterruptsOnly(preparedExit.cause)) return yield* Effect.interrupt; + const error = Cause.squash(preparedExit.cause); + if (!hasAccess()) return; logThreadOutboxUploadFailure(queuedMessage, error); if (!shouldRetryThreadOutboxDelivery(error)) { - return restoreQueuedMessage( + return yield* restoreQueuedMessage( queuedMessage, error instanceof Error ? error.message : "An attachment could not upload.", ); } - return false; + return yield* retryDelivery; + } + if (preparedExit.value.status === "abandoned") return; + const { prepared, persistedMessage, deliveryRevision } = preparedExit.value; + if (isEditingQueuedMessage(queuedMessage.messageId)) { + yield* preserveUploadedAttachmentsForEditor(queuedMessage, persistedMessage); + return; } if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) { - return true; + return; } const currentConfig = appAtomRegistry.get( serverEnvironment.configValueAtom(queuedMessage.environmentId), ); - if (!currentConfig) return false; + if (!currentConfig) return yield* retryDelivery; if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, thread.projectId)) { const { title, detail } = describeUnavailableModelSelection( currentConfig, settings.modelSelection, thread.projectId, ); - return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); + return yield* restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); } const sendSettings = resolveQueuedThreadSettings( queuedMessage, @@ -910,9 +945,9 @@ export function createThreadOutboxDelivery(): { currentConfig.providers, ); if (queuedMessage.compactBeforeSend === true) { - if (!hasAccess()) return true; + if (!hasAccess()) return; // Queued, since steering a running turn with a compaction is rejected. - const compactionResult = await runDeliveryCommand(threadEnvironment.startTurn, { + const compactionResult = yield* deliveryCommand(threadEnvironment.startTurn, { environmentId: queuedMessage.environmentId, input: { commandId: settingsCommandId(queuedMessage, "compact"), @@ -933,16 +968,16 @@ export function createThreadOutboxDelivery(): { resendAfterSocketLoss: false, }, }); - if (AsyncResult.isFailure(compactionResult) && !hasAccess()) return true; + if (AsyncResult.isFailure(compactionResult) && !hasAccess()) return; const compactionFailure = reportCommandFailure(queuedMessage, compactionResult, "start-turn"); - if (compactionFailure?.action === "retry") return false; + if (compactionFailure?.action === "retry") return yield* retryDelivery; if (compactionFailure?.action === "restore") { - return restoreQueuedMessage(persistedMessage, compactionFailure.message); + return yield* restoreQueuedMessage(persistedMessage, compactionFailure.message); } - if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) return true; + if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) return; } - if (!hasAccess()) return true; - const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { + if (!hasAccess()) return; + const deliveryResult = yield* deliveryCommand(threadEnvironment.startTurn, { environmentId: queuedMessage.environmentId, input: { commandId: queuedMessage.commandId, @@ -974,43 +1009,40 @@ export function createThreadOutboxDelivery(): { resendAfterSocketLoss: false, }, }); - if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true; + if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return; const failure = reportCommandFailure(queuedMessage, deliveryResult, "start-turn"); if (failure?.action === "retry") { - return false; + return yield* retryDelivery; } if (failure?.action === "restore") { - return restoreQueuedMessage(persistedMessage, failure.message); + return yield* restoreQueuedMessage(persistedMessage, failure.message); } acknowledgedExistingThreadMessageIds.add(persistedMessage.messageId); - const delivered = - (await completeQueuedMessageDelivery( - persistedMessage, - deliveryRevision, - deliveredSequence(deliveryResult), - )) === "removed"; - if (delivered) { - acknowledgedExistingThreadMessageIds.delete(persistedMessage.messageId); - } - return delivered; - }; + const outcome = yield* completeQueuedMessageDelivery( + persistedMessage, + deliveryRevision, + deliveredSequence(deliveryResult), + ); + if (outcome !== "removed") return yield* retryDelivery; + acknowledgedExistingThreadMessageIds.delete(persistedMessage.messageId); + }); - const sendQueuedCreation = async ( + const sendQueuedCreation = Effect.fn("ThreadOutbox.sendQueuedCreation")(function* ( queuedMessage: QueuedThreadMessage, creation: QueuedThreadCreation, projectCwd: string, - ): Promise => { + ) { const hasAccess = () => readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope); - if (!hasAccess()) return true; + if (!hasAccess()) return; const modelSelection = queuedMessage.modelSelection; if (modelSelection === undefined) { - return false; + return yield* retryDelivery; } const serverConfig = appAtomRegistry.get( serverEnvironment.configValueAtom(queuedMessage.environmentId), ); - if (!serverConfig) return false; + if (!serverConfig) return yield* retryDelivery; const settings = resolveQueuedThreadSettings( queuedMessage, { @@ -1026,84 +1058,81 @@ export function createThreadOutboxDelivery(): { settings.modelSelection, creation.projectId, ); - return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); + return yield* restoreQueuedMessage(queuedMessage, `${title}. ${detail}`); } const runtimeModeDenial = managedRuntimeModeDenial( serverConfig.managedPolicy, settings.runtimeMode, ); if (runtimeModeDenial !== undefined) { - return restoreQueuedMessage(queuedMessage, runtimeModeDenial); + return yield* restoreQueuedMessage(queuedMessage, runtimeModeDenial); } - let prepared: PreparedTurnAttachments; - let persistedMessage: QueuedThreadMessage; - let deliveryRevision: number; - try { - const preparedResult = await prepareQueuedMessageAttachments(queuedMessage); - if (preparedResult.status === "abandoned") { - return true; - } - prepared = preparedResult.prepared; - persistedMessage = preparedResult.persistedMessage; - deliveryRevision = preparedResult.deliveryRevision; - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - await preserveUploadedAttachmentsForEditor(queuedMessage, preparedResult.persistedMessage); - return true; - } - } catch (error) { - if (!hasAccess()) return true; + // Waiting on the shared upload is the one part of a send that may be cut short. + const preparedExit = yield* Effect.exit( + Effect.interruptible(prepareQueuedMessageAttachments(queuedMessage)), + ); + if (Exit.isFailure(preparedExit)) { + if (Cause.hasInterruptsOnly(preparedExit.cause)) return yield* Effect.interrupt; + const error = Cause.squash(preparedExit.cause); + if (!hasAccess()) return; logThreadOutboxUploadFailure(queuedMessage, error); if (!shouldRetryThreadOutboxDelivery(error)) { - return restoreQueuedMessage( + return yield* restoreQueuedMessage( queuedMessage, error instanceof Error ? error.message : "An attachment could not upload.", ); } - return false; + return yield* retryDelivery; + } + if (preparedExit.value.status === "abandoned") return; + const { prepared, persistedMessage, deliveryRevision } = preparedExit.value; + if (isEditingQueuedMessage(queuedMessage.messageId)) { + yield* preserveUploadedAttachmentsForEditor(queuedMessage, persistedMessage); + return; } if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) { - return true; + return; } const currentConfig = appAtomRegistry.get( serverEnvironment.configValueAtom(queuedMessage.environmentId), ); - if (!currentConfig) return false; + if (!currentConfig) return yield* retryDelivery; if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, creation.projectId)) { const { title, detail } = describeUnavailableModelSelection( currentConfig, settings.modelSelection, creation.projectId, ); - return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); + return yield* restoreQueuedMessage(persistedMessage, `${title}. ${detail}`); } const sendSettings = resolveQueuedThreadSettings( queuedMessage, settings, currentConfig.providers, ); - if (!hasAccess()) return true; + if (!hasAccess()) return; let workspace = creation; const launched = launchedCreations.get(persistedMessage.messageId); if (launched?.revision === deliveryRevision) { workspace = launched.workspace; } else if (creation.pullRequestReference) { - const checkout = await runDeliveryCommand(gitEnvironment.preparePullRequestThread, { + const checkout = yield* deliveryCommand(gitEnvironment.preparePullRequestThread, { environmentId: queuedMessage.environmentId, input: { cwd: projectCwd, reference: creation.pullRequestReference, mode: "worktree" }, }); if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) || !hasAccess()) - return true; + return; const failure = reportCommandFailure(queuedMessage, checkout, "start-turn"); - if (failure?.action === "retry") return false; + if (failure?.action === "retry") return yield* retryDelivery; if (failure?.action === "restore") - return restoreQueuedMessage(persistedMessage, failure.message); - if (!AsyncResult.isSuccess(checkout)) return false; + return yield* restoreQueuedMessage(persistedMessage, failure.message); + if (!AsyncResult.isSuccess(checkout)) return yield* retryDelivery; if (!checkout.value.worktreePath || !checkout.value.isOnPullRequestHead) { const { shortLabel } = ( sourceControlClients.findByChangeRequestUrl(creation.pullRequestReference) ?? sourceControlClients.get(undefined) ).changeRequest; - return restoreQueuedMessage( + return yield* restoreQueuedMessage( persistedMessage, `The ${shortLabel} worktree has local changes and could not update to the ${shortLabel} head. Resolve them before trying again.`, ); @@ -1117,7 +1146,7 @@ export function createThreadOutboxDelivery(): { }; } launchedCreations.set(persistedMessage.messageId, { revision: deliveryRevision, workspace }); - const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { + const deliveryResult = yield* deliveryCommand(threadEnvironment.startTurn, { environmentId: queuedMessage.environmentId, input: buildProjectThreadStartTurnInput({ projectId: creation.projectId, @@ -1146,65 +1175,305 @@ export function createThreadOutboxDelivery(): { worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex), }), }); - if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true; + if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return; const failure = reportCommandFailure(queuedMessage, deliveryResult, "start-turn"); if (failure?.action === "retry") { - return false; + return yield* retryDelivery; } if (failure?.action === "restore") { - return restoreQueuedMessage(persistedMessage, failure.message); + return yield* restoreQueuedMessage(persistedMessage, failure.message); } recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage }); - const outcome = await completeQueuedMessageDelivery( + const outcome = yield* completeQueuedMessageDelivery( persistedMessage, deliveryRevision, deliveredSequence(deliveryResult), ); if (outcome === "edited") { - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) { - return true; - } - return recoverEditedCreationAfterDelivery(persistedMessage); + if (isEditingQueuedMessage(queuedMessage.messageId)) return; + return yield* recoverEditedCreationAfterDelivery(persistedMessage); } - return outcome === "removed"; - }; - - // A pass writes atoms the pass reads (family mounts, the dispatch slot), and the registry - // notifies subscribers synchronously, so drain() can be called from inside a pass. That call - // only asks for another pass; a nested pass would decide from inputs the outer one is still - // acting on and could start a second delivery. - let draining = false; - let drainRequested = false; - function drain(): void { - if (disposed) return; - if (draining) { - drainRequested = true; - return; - } - draining = true; - try { - do { - if (disposed) return; - drainRequested = false; - drainPass(); - } while (drainRequested); - } finally { - draining = false; - } - } + if (outcome !== "removed") return yield* retryDelivery; + }); - function drainPass(): void { + /** The head of one thread's queue, as the inputs stand now. */ + function nextStep( + threadKey: string, + queuedMessages: ReadonlyArray, + inputs: Atom.Type, + ): ThreadDeliveryStep { const { - dispatchingQueuedMessageId, editingQueuedMessageIds, - queuedMessagesByThreadKey, shellStatuses, threads, projects, serverConfigs, connectedEnvironments, operableEnvironments, - } = appAtomRegistry.get(deliveryInputsAtom); + } = inputs; + const nextQueuedMessage = queuedMessages[0]; + if (!nextQueuedMessage) { + return { _tag: "Wait" }; + } + const messageId = nextQueuedMessage.messageId; + if ( + nextQueuedMessage.creation === undefined && + acknowledgedExistingThreadMessageIds.has(messageId) + ) { + if (retryNotBefore(messageId) > Date.now()) { + return { _tag: "Wait", until: retryNotBefore(messageId) }; + } + return { + _tag: "Dispatch", + messageId, + run: removeAcknowledgedExistingThreadMessage( + nextQueuedMessage, + acknowledgedExistingThreadMessageIds, + ), + }; + } + if (editingQueuedMessageIds[messageId]) { + return { _tag: "Wait" }; + } + const blockedRecovery = blockedRecoveries.get(messageId); + if (blockedRecovery) { + if (blockedRecovery.message === nextQueuedMessage) { + return { _tag: "Wait" }; + } + blockedRecoveries.delete(messageId); + blockedRecovery.unsubscribe(); + } + if (retryNotBefore(messageId) > Date.now()) { + return { _tag: "Wait", until: retryNotBefore(messageId) }; + } + let thread = findThread(threads, nextQueuedMessage); + if (thread && scopedThreadKey(thread.environmentId, thread.id) !== threadKey) { + return { _tag: "Wait" }; + } + + const creation = nextQueuedMessage.creation; + const environment = connectedEnvironments.find( + (candidate) => candidate.environmentId === nextQueuedMessage.environmentId, + ); + const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty"; + const serverConfig = serverConfigs.get(nextQueuedMessage.environmentId); + let familyRead: ThreadFamilyRead | undefined; + if ( + thread === undefined && + creation === undefined && + serverConfig?.shellThreadFamilies === true + ) { + // The family keeps the row readable through dispatch once it loads; the current shell + // generation's read decides whether the thread is gone. + if (!familyMounts.has(nextQueuedMessage.messageId)) { + familyMounts.set( + nextQueuedMessage.messageId, + threadFamilies.mount( + appAtomRegistry, + nextQueuedMessage.environmentId, + nextQueuedMessage.threadId, + ), + ); + } + familyRead = threadFamilyRead( + appAtomRegistry.get( + threadFamilies.familyAtom(nextQueuedMessage.environmentId, nextQueuedMessage.threadId), + ), + ); + if (familyRead === "settled") { + // The rows read at the start of this pass can lag the family that just settled; + // decide from the merged rows as they are now. + thread = findThread( + appAtomRegistry.get(environmentThreadShells.threadShellsAtom), + nextQueuedMessage, + ); + } else if (familyRead === "failed") { + threadFamilies.refresh( + appAtomRegistry, + nextQueuedMessage.environmentId, + nextQueuedMessage.threadId, + ); + } + } + const resendLaunch = + creation !== undefined && + launchedCreations.get(messageId)?.revision === threadOutboxRevision(messageId); + const deliveryAction = resolveThreadOutboxDeliveryAction({ + isCreation: creation !== undefined, + // A resend goes through the same gates as the first launch. + threadExists: thread !== undefined && !resendLaunch, + shellStatus, + environmentConnected: environment?.connectionState === "connected", + ...(familyRead === undefined ? {} : { familyRead }), + }); + if ( + deliveryAction === "wait" && + shellStatus === "live" && + familyRead !== undefined && + familyRead !== "settled" + ) { + // An empty family read changes no merged row, so nothing else would wake the thread. + return { _tag: "Backoff", messageId }; + } + if (deliveryAction === "send" && !operableEnvironments.has(nextQueuedMessage.environmentId)) { + return { _tag: "Wait" }; + } + const dispatchStep = resolveThreadOutboxDispatchStep({ + deliveryAction, + fileAttachments: nextQueuedMessage.attachments.filter( + (attachment) => attachment.type === "file", + ), + serverConfig: serverConfig + ? { + maxFileUploadBytes: + serverConfig.environment.capabilities.fileAttachments?.maxUploadBytes, + } + : null, + }); + if (dispatchStep.step === "wait") { + return { _tag: "Wait" }; + } + if (dispatchStep.step === "retry") { + return { _tag: "Backoff", messageId }; + } + if (dispatchStep.step === "restore") { + const attachmentError = dispatchStep.reason; + return { + _tag: "Dispatch", + messageId, + run: Effect.gen(function* () { + if (!(yield* confirmQueued(nextQueuedMessage)) || isEditingQueuedMessage(messageId)) { + return; + } + yield* restoreQueuedMessage(nextQueuedMessage, attachmentError); + }), + }; + } + const creationProjectCwd = + creation !== undefined + ? (findCreationProject(projects, nextQueuedMessage)?.workspaceRoot ?? + creation.projectCwd ?? + null) + : null; + if (deliveryAction === "send" && creation !== undefined) { + if (!isQueuedThreadCreationSendable(nextQueuedMessage)) { + return { _tag: "Wait" }; + } + if (creationProjectCwd === null && shellStatus !== "live") { + return { _tag: "Wait" }; + } + } + + const removeQueuedMessage = (warning: string) => + storage("remove-unsendable", messageId, () => + removeThreadOutboxMessage(nextQueuedMessage), + ).pipe( + Effect.catch((error) => + Effect.logWarning(warning, { + environmentId: nextQueuedMessage.environmentId, + threadId: nextQueuedMessage.threadId, + messageId, + error: error.cause, + }).pipe(Effect.andThen(retryDelivery)), + ), + Effect.asVoid, + ); + // Confirm durability before sending; optimistic enqueue can still roll back on write failure. + const run = Effect.gen(function* () { + if (!(yield* confirmQueued(nextQueuedMessage))) return; + // An editor that took the message after confirmation owns it; that is not a failure. + if (isEditingQueuedMessage(messageId)) return; + if (deliveryAction === "send") { + const liveThread = findThread( + appAtomRegistry.get(environmentThreadShells.threadShellsAtom), + nextQueuedMessage, + ); + const liveDeliveryAction = resolveThreadOutboxDeliveryAction({ + isCreation: creation !== undefined, + threadExists: liveThread !== undefined && !resendLaunch, + shellStatus, + environmentConnected: environment?.connectionState === "connected", + }); + if (liveDeliveryAction !== "send") return; + } + if (deliveryAction === "remove") { + // Edited since launch, or launched before a restart that lost the revision: hand it back. + return yield* creation !== undefined + ? recoverEditedCreationAfterDelivery(nextQueuedMessage) + : removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread"); + } + if (creation !== undefined) { + return yield* creationProjectCwd !== null + ? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd) + : removeQueuedMessage("[thread-outbox] dropped pending task for a missing project"); + } + return yield* thread !== undefined + ? sendQueuedMessage(nextQueuedMessage, thread) + : retryDelivery; + }); + return { _tag: "Dispatch", messageId, run }; + } + + // One fiber per thread with queued messages. Opening a thread's latch wakes its fiber to + // reconsider its head; the fiber closes it before reading the inputs, so no wake is lost. + // An entry outlives its interrupted fiber until that fiber exits, so a thread never has two. + const threadFibers = new Map(); + + const deliverThread = (threadKey: string, wake: Latch.Latch) => + Effect.forever( + Effect.gen(function* () { + yield* wake.close; + const inputs = appAtomRegistry.get(deliveryInputsAtom); + const step = nextStep(threadKey, inputs.queuedMessagesByThreadKey[threadKey] ?? [], inputs); + if (step._tag === "Backoff") { + scheduleRetry(step.messageId); + return; + } + if (step._tag === "Wait") { + if (step.until === undefined) { + yield* wake.await; + return; + } + const now = yield* Clock.currentTimeMillis; + yield* wake.await.pipe( + Effect.timeoutOrElse({ + duration: Math.max(0, step.until - now), + orElse: () => Effect.void, + }), + ); + return; + } + // A send that started finishes, even when its thread leaves the queue meanwhile; only + // its wait on a shared upload stops early. + beginDispatchingQueuedMessage(step.messageId); + const sent = yield* step.run.pipe( + Effect.as(true), + Effect.catchTags({ DeliveryRetry: () => Effect.succeed(false) }), + // A send that throws backs off like any failure, not straight back into the send. + Effect.catchDefect((error) => + Effect.logWarning("[thread-outbox] queued message delivery threw", { + messageId: step.messageId, + error, + }).pipe(Effect.as(false)), + ), + Effect.ensuring(Effect.sync(() => finishDispatchingQueuedMessage(step.messageId))), + Effect.uninterruptible, + ); + if (sent) clearRetry(step.messageId); + else scheduleRetry(step.messageId); + }), + ); + + function wakeThreads(): void { + for (const { wake } of threadFibers.values()) wake.openUnsafe(); + } + + /** Starts a fiber for each thread with queued messages, stops the rest, and wakes them all. */ + function onInputs(): void { + if (disposed) return; + const { queuedMessagesByThreadKey, serverConfigs, connectedEnvironments } = + appAtomRegistry.get(deliveryInputsAtom); + const queued = Object.values(queuedMessagesByThreadKey).flat(); // Failures while an environment was unreachable say nothing about it now; a backoff // started then would hold a message for up to its full delay after reconnecting. const ready = new Set( @@ -1216,30 +1485,19 @@ export function createThreadOutboxDelivery(): { ) .map((environment) => environment.environmentId), ); - for (const message of Object.values(queuedMessagesByThreadKey).flat()) { + for (const message of queued) { if (ready.has(message.environmentId) && !readyEnvironmentIds.has(message.environmentId)) { clearRetry(message.messageId); } } readyEnvironmentIds = ready; - if (dispatchingQueuedMessageId !== null) { - return; - } - const queuedMessageIds = new Set( - Object.values(queuedMessagesByThreadKey) - .flat() - .map((message) => message.messageId), - ); + const queuedMessageIds = new Set(queued.map((message) => message.messageId)); for (const messageId of acknowledgedExistingThreadMessageIds) { - if (!queuedMessageIds.has(messageId)) { - acknowledgedExistingThreadMessageIds.delete(messageId); - } + if (!queuedMessageIds.has(messageId)) acknowledgedExistingThreadMessageIds.delete(messageId); } for (const messageId of launchedCreations.keys()) { - if (!queuedMessageIds.has(messageId)) { - launchedCreations.delete(messageId); - } + if (!queuedMessageIds.has(messageId)) launchedCreations.delete(messageId); } for (const [messageId, release] of familyMounts) { if (!queuedMessageIds.has(messageId)) { @@ -1248,230 +1506,36 @@ export function createThreadOutboxDelivery(): { } } - for (const [threadKey, queuedMessages] of Object.entries(queuedMessagesByThreadKey)) { - const nextQueuedMessage = queuedMessages[0]; - if (!nextQueuedMessage) { - continue; - } - const messageId = nextQueuedMessage.messageId; - if ( - nextQueuedMessage.creation === undefined && - acknowledgedExistingThreadMessageIds.has(messageId) - ) { - if (retryNotBefore(messageId) > Date.now()) { - continue; - } - beginDispatchingQueuedMessage(messageId); - settle( - messageId, - removeAcknowledgedExistingThreadMessage( - nextQueuedMessage, - acknowledgedExistingThreadMessageIds, - ), - ); - return; - } - if (editingQueuedMessageIds[messageId]) { - continue; - } - const blockedRecovery = blockedRecoveries.get(messageId); - if (blockedRecovery) { - if (blockedRecovery.message === nextQueuedMessage) { - continue; - } - blockedRecoveries.delete(messageId); - blockedRecovery.unsubscribe(); - } - if (retryNotBefore(messageId) > Date.now()) { - continue; - } - if ( - queuedAttachmentsStillUploading({ - environmentId: nextQueuedMessage.environmentId, - attachments: nextQueuedMessage.attachments, - states: appAtomRegistry.get(composerAttachmentUploadsAtom), - }) - ) { - continue; - } - - let thread = findThread(threads, nextQueuedMessage); - if (thread && scopedThreadKey(thread.environmentId, thread.id) !== threadKey) { - continue; - } - - const creation = nextQueuedMessage.creation; - const environment = connectedEnvironments.find( - (candidate) => candidate.environmentId === nextQueuedMessage.environmentId, - ); - const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty"; - const serverConfig = serverConfigs.get(nextQueuedMessage.environmentId); - let familyRead: ThreadFamilyRead | undefined; - if ( - thread === undefined && - creation === undefined && - serverConfig?.shellThreadFamilies === true - ) { - // The family keeps the row readable through dispatch once it loads; the current shell - // generation's read decides whether the thread is gone. - if (!familyMounts.has(nextQueuedMessage.messageId)) { - familyMounts.set( - nextQueuedMessage.messageId, - threadFamilies.mount( - appAtomRegistry, - nextQueuedMessage.environmentId, - nextQueuedMessage.threadId, - ), - ); - } - familyRead = threadFamilyRead( - appAtomRegistry.get( - threadFamilies.familyAtom(nextQueuedMessage.environmentId, nextQueuedMessage.threadId), - ), - ); - if (familyRead === "settled") { - // The rows read at the start of this pass can lag the family that just settled; - // decide from the merged rows as they are now. - thread = findThread( - appAtomRegistry.get(environmentThreadShells.threadShellsAtom), - nextQueuedMessage, - ); - } else if (familyRead === "failed") { - threadFamilies.refresh( - appAtomRegistry, - nextQueuedMessage.environmentId, - nextQueuedMessage.threadId, - ); - } - } - const resendLaunch = - creation !== undefined && - launchedCreations.get(messageId)?.revision === threadOutboxRevision(messageId); - const deliveryAction = resolveThreadOutboxDeliveryAction({ - isCreation: creation !== undefined, - // A resend goes through the same gates as the first launch. - threadExists: thread !== undefined && !resendLaunch, - shellStatus, - environmentConnected: environment?.connectionState === "connected", - ...(familyRead === undefined ? {} : { familyRead }), - }); - if ( - deliveryAction === "wait" && - shellStatus === "live" && - familyRead !== undefined && - familyRead !== "settled" - ) { - // An empty family read changes no merged row, so nothing else would wake the drain. - scheduleRetry(messageId); - continue; - } - if (deliveryAction === "send" && !operableEnvironments.has(nextQueuedMessage.environmentId)) { - continue; - } - const dispatchStep = resolveThreadOutboxDispatchStep({ - deliveryAction, - fileAttachments: nextQueuedMessage.attachments.filter( - (attachment) => attachment.type === "file", - ), - serverConfig: serverConfig - ? { - maxFileUploadBytes: - serverConfig.environment.capabilities.fileAttachments?.maxUploadBytes, - } - : null, - }); - if (dispatchStep.step === "wait") { - continue; - } - if (dispatchStep.step === "retry") { - scheduleRetry(messageId); - continue; - } - if (dispatchStep.step === "restore") { - const attachmentError = dispatchStep.reason; - beginDispatchingQueuedMessage(messageId); - settle( - messageId, - confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => - !queued || appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId] - ? true - : restoreQueuedMessage(nextQueuedMessage, attachmentError), - ), - ); - return; - } - const creationProjectCwd = - creation !== undefined - ? (findCreationProject(projects, nextQueuedMessage)?.workspaceRoot ?? - creation.projectCwd ?? - null) - : null; - if (deliveryAction === "send" && creation !== undefined) { - if (!isQueuedThreadCreationSendable(nextQueuedMessage)) { - continue; - } - if (creationProjectCwd === null && shellStatus !== "live") { - continue; - } - } - - beginDispatchingQueuedMessage(messageId); - const removeQueuedMessage = (warning: string) => - removeThreadOutboxMessage(nextQueuedMessage).then( - () => true, - (error) => { - console.warn(warning, { - environmentId: nextQueuedMessage.environmentId, - threadId: nextQueuedMessage.threadId, - messageId, - error, - }); - return false; - }, - ); - // Confirm durability before sending; optimistic enqueue can still roll back on write failure. - const delivery = confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => { - if (!queued) { - return true; - } - // Re-check editor ownership after confirmation; return true to defer without failure backoff. - if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId]) { - return true; - } - if (deliveryAction === "send") { - const liveThread = findThread( - appAtomRegistry.get(environmentThreadShells.threadShellsAtom), - nextQueuedMessage, - ); - const liveDeliveryAction = resolveThreadOutboxDeliveryAction({ - isCreation: creation !== undefined, - threadExists: liveThread !== undefined && !resendLaunch, - shellStatus, - environmentConnected: environment?.connectionState === "connected", - }); - if (liveDeliveryAction !== "send") { - return true; - } - } - return deliveryAction === "remove" - ? creation !== undefined - ? // Edited since launch, or launched before a restart that lost the revision: hand it back. - recoverEditedCreationAfterDelivery(nextQueuedMessage) - : removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread") - : creation !== undefined - ? creationProjectCwd !== null - ? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd) - : removeQueuedMessage("[thread-outbox] dropped pending task for a missing project") - : thread !== undefined - ? sendQueuedMessage(nextQueuedMessage, thread) - : Promise.resolve(false); + for (const [threadKey, entry] of threadFibers) { + if ((queuedMessagesByThreadKey[threadKey]?.length ?? 0) > 0 || entry.retiring) continue; + entry.retiring = true; + if (entry.fiber !== undefined) Effect.runFork(Fiber.interrupt(entry.fiber)); + } + for (const [threadKey, messages] of Object.entries(queuedMessagesByThreadKey)) { + if (messages.length === 0 || threadFibers.has(threadKey)) continue; + // Registered before the fiber starts: its first step runs synchronously and can re-enter here. + const entry: ThreadFiber = { + wake: Latch.makeUnsafe(true), + fiber: undefined, + retiring: false, + }; + threadFibers.set(threadKey, entry); + const fiber = Effect.runFork(deliverThread(threadKey, entry.wake)); + entry.fiber = fiber; + fiber.addObserver(() => { + if (threadFibers.get(threadKey) !== entry) return; + threadFibers.delete(threadKey); + // A message queued while this fiber finished its send starts the next fiber now. + if (!disposed) onInputs(); }); - settle(messageId, delivery); - return; + if (entry.retiring) Effect.runFork(Fiber.interrupt(fiber)); } + wakeThreads(); } - const stopDraining = appAtomRegistry.subscribe(deliveryInputsAtom, drain, { immediate: true }); + const stopDelivering = appAtomRegistry.subscribe(deliveryInputsAtom, onInputs, { + immediate: true, + }); const stopCollectingOutcomes = appAtomRegistry.subscribe( settledCreationOutcomeKeysAtom, (threadKeys) => { @@ -1481,12 +1545,15 @@ export function createThreadOutboxDelivery(): { ); return { - drain, + drain: wakeThreads, dispose: () => { disposed = true; - stopDraining(); + stopDelivering(); stopCollectingOutcomes(); - for (const retry of retries.values()) clearTimeout(retry.timer); + for (const { fiber } of threadFibers.values()) { + if (fiber !== undefined) Effect.runFork(Fiber.interrupt(fiber)); + } + threadFibers.clear(); retries.clear(); appAtomRegistry.set(retryingQueuedMessageIdsAtom, {}); for (const blocked of blockedRecoveries.values()) blocked.unsubscribe(); diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index 200b2b165c6b5..0f0e4a69419fb 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -1,4 +1,6 @@ import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads"; import { applyShellStreamEvent, @@ -1213,63 +1215,67 @@ describe("mobile composer drafts", () => { expect(composerAttachmentCleanupMocks.remove).toHaveBeenCalledExactlyOnceWith(image.fileUri); }); - it("keeps an image through an inline read after its draft is removed", async () => { - const { prepareTurnAttachments } = - await vi.importActual("../lib/attachmentUpload"); - const image = { - id: "image-reading", - type: "image" as const, - name: "photo.png", - mimeType: "image/png", - sizeBytes: 3, - fileUri: "file:///documents/t3-composer-attachments/photo.png", - previewUri: "file:///documents/t3-composer-attachments/photo.png", - }; - const readStarted = Promise.withResolvers(); - const read = Promise.withResolvers(); - const removed = Promise.withResolvers(); - let imageExists = true; - composerDraftFileMocks.readImage.mockImplementation(async () => { - readStarted.resolve(); - await read.promise; - if (!imageExists) throw new Error("The image was deleted during its read"); - return "YWJj"; - }); - composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { - imageExists = false; - removed.resolve(); - }); - appendComposerDraftAttachments("environment-1:thread-1", [image]); - await flushComposerDrafts(); - const preparing = prepareTurnAttachments({ - environmentId: EnvironmentId.make("environment-1"), - attachments: [image], - }); - onTestFinished(async () => { - read.resolve(); - await preparing.catch(() => undefined); - }); - await readStarted.promise; - clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true }); - await releaseUnusedComposerAttachmentFiles([image]); - expect(imageExists).toBe(true); - - read.resolve(); - const prepared = await preparing; - expect(prepared.status).toBe("ready"); - if (prepared.status !== "ready") return; - expect(prepared.attachments).toEqual([ - { - type: "image", + it.effect("keeps an image through an inline read after its draft is removed", () => + Effect.gen(function* () { + const { prepareTurnAttachments } = yield* Effect.promise(() => + vi.importActual("../lib/attachmentUpload"), + ); + const image = { + id: "image-reading", + type: "image" as const, name: "photo.png", mimeType: "image/png", sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - }, - ]); - await removed.promise; - expect(imageExists).toBe(false); - }); + fileUri: "file:///documents/t3-composer-attachments/photo.png", + previewUri: "file:///documents/t3-composer-attachments/photo.png", + }; + const readStarted = Promise.withResolvers(); + const read = Promise.withResolvers(); + const removed = Promise.withResolvers(); + let imageExists = true; + composerDraftFileMocks.readImage.mockImplementation(async () => { + readStarted.resolve(); + await read.promise; + if (!imageExists) throw new Error("The image was deleted during its read"); + return "YWJj"; + }); + composerAttachmentCleanupMocks.remove.mockImplementationOnce(async () => { + imageExists = false; + removed.resolve(); + }); + appendComposerDraftAttachments("environment-1:thread-1", [image]); + yield* Effect.promise(() => flushComposerDrafts()); + // Without image uploads the image is inlined, so nothing goes through the upload registry. + const preparing = yield* Effect.forkChild( + prepareTurnAttachments({ + environmentId: EnvironmentId.make("environment-1"), + attachments: [image], + uploadAttachment: vi.fn(), + }), + ); + onTestFinished(() => read.resolve()); + yield* Effect.promise(() => readStarted.promise); + clearComposerDraftContent("environment-1:thread-1", { deferAttachmentCleanup: true }); + yield* Effect.promise(() => releaseUnusedComposerAttachmentFiles([image])); + expect(imageExists).toBe(true); + + read.resolve(); + const prepared = yield* Fiber.join(preparing); + expect(prepared.status).toBe("ready"); + if (prepared.status !== "ready") return; + expect(prepared.attachments).toEqual([ + { + type: "image", + name: "photo.png", + mimeType: "image/png", + sizeBytes: 3, + dataUrl: "data:image/png;base64,YWJj", + }, + ]); + yield* Effect.promise(() => removed.promise); + expect(imageExists).toBe(false); + }), + ); it("keeps a failed-send draft's pending upload for retry", async () => { const outboxLoad = vi.spyOn(threadOutboxManager, "load").mockResolvedValue(true); diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 08b9e20b27f60..58f2da087ea41 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -1,4 +1,5 @@ import { useComposerAttachmentActions } from "./use-composer-attachment-actions"; +import * as Effect from "effect/Effect"; import * as Dialog from "../components/ui/Dialog"; import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; import { readEnvironmentScope } from "./session"; @@ -72,6 +73,7 @@ import { pendingThreadCreationMessage } from "./pending-thread-creation"; import { composerAttachmentUploadBlockReason, composerAttachmentUploadsAtom, + uploadComposerAttachmentShared, } from "./composer-attachment-uploads"; import { appendComposerDraftAttachments, @@ -120,7 +122,7 @@ import { } from "./use-thread-detail"; import { useThreadSelection } from "./use-thread-selection"; import { enqueueThreadOutboxMessage } from "./thread-outbox"; -import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox"; +import { dispatchingQueuedMessageIdsAtom, useThreadOutboxMessages } from "./use-thread-outbox"; import { threadEnvironment } from "./threads"; import { useAtomCommand } from "./use-atom-command"; @@ -215,7 +217,7 @@ export function useThreadComposerState(input: { const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems(); const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom); const queuedMessagesByThreadKey = useThreadOutboxMessages(); - const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom); + const dispatchingQueuedMessageIds = useAtomValue(dispatchingQueuedMessageIdsAtom); const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState< Record> >({}); @@ -238,6 +240,10 @@ export function useThreadComposerState(input: { (message) => message.creation === undefined, ) : []; + // The thread sends one message at a time, the head of its queue. + const dispatchingQueuedMessageId = + selectedThreadQueuedMessages.find((message) => dispatchingQueuedMessageIds[message.messageId]) + ?.messageId ?? null; const feedbackSubmissions = selectedThreadKey ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? []) : []; @@ -510,11 +516,15 @@ export function useThreadComposerState(input: { setIsSavingQueuedEdit(true); const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities; const prepared = await settlePromise(() => - prepareTurnAttachments({ - environmentId: thread.environmentId, - attachments: draft.attachments, - supportsImageUploads: capabilities !== undefined, - }), + Effect.runPromise( + prepareTurnAttachments({ + environmentId: thread.environmentId, + attachments: draft.attachments, + supportsImageUploads: capabilities !== undefined, + uploadAttachment: (attachment) => + uploadComposerAttachmentShared(thread.environmentId, attachment), + }), + ), ); if (AsyncResult.isFailure(prepared)) { savingQueuedEditRef.current = false; diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts index bc1f3ea149e1b..8edb8e033b361 100644 --- a/apps/mobile/src/state/use-thread-outbox.ts +++ b/apps/mobile/src/state/use-thread-outbox.ts @@ -26,10 +26,10 @@ export const editingQueuedMessageIdsAtom = Atom.make(null).pipe( - Atom.keepAlive, - Atom.withLabel("mobile:thread-outbox:dispatching-message-id"), -); +/** Messages being sent now: at most one per thread, the head of its queue. */ +export const dispatchingQueuedMessageIdsAtom = Atom.make< + Readonly>> +>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-outbox:dispatching-message-ids")); /** Messages waiting out a retry backoff, which can repeat for as long as the failure lasts. */ export const retryingQueuedMessageIdsAtom = Atom.make>>>( diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index d137305317327..8f2e133b2a6e3 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -215,6 +215,30 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("serves the background image published beside an environment theme", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + yield* fs.makeDirectory(environmentThemesDir, { recursive: true }); + const imagePath = `${environmentThemesDir}/frieren.png`; + yield* fs.writeFile(imagePath, screenshotPng); + const result = yield* issueAssetUrl({ + resource: { _tag: "environment-theme-background", themeId: "frieren" }, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + const token = suffix.slice(0, separator); + const asset = yield* resolveAsset(token, suffix.slice(separator + 1)); + expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(imagePath) }); + if (asset?.kind !== "file") return; + const response = yield* assetFileResponse(asset); + expect(response.headers["content-type"]).toBe("image/png"); + + yield* fs.remove(imagePath); + expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toBeNull(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("issues exact URLs for media and browser documents outside the workspace", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 5674372bee1a9..362d00fca9230 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -17,6 +17,7 @@ import { ThreadId, NativeAppIconReference, TurnItemId, + EnvironmentThemeId, } from "@t3tools/contracts"; import { hostPreviewMimeTypeFromExtension, @@ -52,6 +53,7 @@ import * as AssetSigner from "./AssetSigner.ts"; import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; +import { findThemeBackground } from "../environmentTheme.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; @@ -168,6 +170,12 @@ const AssetClaimsSchema = Schema.Union([ app: NativeAppIconReference, expiresAt: Schema.Number, }), + Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("environment-theme-background"), + themeId: EnvironmentThemeId, + expiresAt: Schema.Number, + }), Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("tool-output-image"), @@ -834,6 +842,17 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i imageDimensions = readImageDimensions(image.bytes); break; } + case "environment-theme-background": { + // Published themes go to every client, so any client may read their backgrounds. + claims = { + version: 1, + kind: "environment-theme-background", + themeId: input.resource.themeId, + expiresAt, + }; + fileName = `${input.resource.themeId}-background`; + break; + } case "native-app-icon": { claims = { version: 1, @@ -982,6 +1001,24 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null; } + if (claims.kind === "environment-theme-background") { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + // The themes directory may be a symlink; openMediaFile refuses any path that is not canonical. + const themesDir = yield* fileSystem + .realPath(config.environmentThemesDir) + .pipe(Effect.orElseSucceed(() => null)); + const background = themesDir === null ? null : findThemeBackground(themesDir, claims.themeId); + if (background === null) return null; + const file = yield* openMediaFile(background.path).pipe( + Effect.tapError((cause) => + Effect.logError("Failed to open theme background.", { path: background.path, cause }), + ), + Effect.orElseSucceed(() => null), + ); + return file ? ({ kind: "file", path: background.path, file } satisfies ResolvedAsset) : null; + } + if (claims.kind === "native-app-icon") { const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver; const iconPath = yield* nativeAppIconResolver.resolve(claims.app); diff --git a/apps/server/src/environmentTheme.test.ts b/apps/server/src/environmentTheme.test.ts index 241c89546c228..a0bd921ad3f2e 100644 --- a/apps/server/src/environmentTheme.test.ts +++ b/apps/server/src/environmentTheme.test.ts @@ -304,6 +304,35 @@ it.layer(NodeServices.layer)("environment theme", (it) => { ); }); + it.effect( + "reports the image beside a theme as its background, with a new revision per file", + () => + withEnvironmentThemes( + { "look.json": encodeThemeFile(NIGHTFALL_THEME), "look.png": "first" }, + Effect.gen(function* () { + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const background = Effect.map(currentThemes, (themes) => themes[0]?.background); + const image = path.join(environmentThemesDir, "look.png"); + + const first = yield* background; + assert.isDefined(first); + yield* fs.writeFileString(image, "a longer second image"); + assert.notStrictEqual(yield* background, first); + + yield* fs.remove(image); + assert.isUndefined(yield* background); + if (symlinksSupported) { + const outside = path.join(environmentThemesDir, "..", "outside.png"); + yield* fs.writeFileString(outside, "outside"); + yield* fs.symlink(outside, image); + assert.isUndefined(yield* background); + } + }), + ), + ); + it.effect("keeps the served theme when an update does not fit the size limit", () => { const large = (name: string): EnvironmentThemeFile => ({ ...NIGHTFALL_THEME, diff --git a/apps/server/src/environmentTheme.ts b/apps/server/src/environmentTheme.ts index 1e7f4d3052301..0d45fd02de79d 100644 --- a/apps/server/src/environmentTheme.ts +++ b/apps/server/src/environmentTheme.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open // flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose. import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; import { type DefaultAppearancePreference, @@ -52,6 +53,10 @@ const MAX_THEME_FILES = 32; export const MAX_THEME_FILE_BYTES = 6 * THEME_CSS_MAX_LENGTH + 16 * 1024; const MAX_THEME_TOTAL_BYTES = 6 * MAX_THEME_FILE_BYTES; +/** A theme's background is `.` beside `.json`; earlier extensions win. */ +const THEME_BACKGROUND_EXTENSIONS = ["webp", "png", "jpg", "jpeg"] as const; +const MAX_THEME_BACKGROUND_BYTES = 16 * 1024 * 1024; + interface PublishedThemes { readonly seq: number; readonly themes: ReadonlyArray; @@ -101,6 +106,8 @@ export class EnvironmentThemeService extends Context.Service< readonly read: (themeId?: string) => Effect.Effect< { readonly current: string; + /** Where theme files and their background images live. */ + readonly themesDir: string; readonly themes: ReadonlyArray; readonly theme?: EnvironmentTheme; }, @@ -173,6 +180,35 @@ export const readThemeFileGuarded = (filePath: string, maxBytes: number): string } }; +/** + * The background image published beside `themeId`, if any. Symlinks and oversized files are + * skipped. `entries` lets a directory scan skip lookups for names it did not list. + */ +export function findThemeBackground( + themesDir: string, + themeId: string, + entries?: ReadonlySet, +): { readonly path: string; readonly revision: string } | null { + for (const extension of THEME_BACKGROUND_EXTENSIONS) { + const name = `${themeId}.${extension}`; + if (entries !== undefined && !entries.has(name)) continue; + // Native separators: the asset route refuses a path that differs from its canonical form. + const filePath = NodePath.join(themesDir, name); + let info: NodeFS.BigIntStats; + try { + info = NodeFS.lstatSync(filePath, { bigint: true }); + } catch { + continue; + } + if (!info.isFile() || info.size > MAX_THEME_BACKGROUND_BYTES) continue; + return { + path: filePath, + revision: [info.ino, info.size, info.mtimeNs].map((part) => part.toString(36)).join("-"), + }; + } + return null; +} + export const readPublishedThemes = Effect.fn(function* (themesDir: string) { const fs = yield* FileSystem.FileSystem; const entries = yield* fs @@ -180,6 +216,7 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) { .pipe(Effect.orElseSucceed((): Array => [])); const themes: Array = []; + const entryNames = new Set(entries); let examined = 0; let totalBytes = 0; for (const entry of entries.toSorted()) { @@ -232,7 +269,8 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) { break; } - themes.push({ id, ...file }); + const background = findThemeBackground(themesDir, id, entryNames); + themes.push({ id, ...file, ...(background ? { background: background.revision } : {}) }); } return themes; }); @@ -406,7 +444,8 @@ const make = Effect.gen(function* () { )(function* (themeId) { const { themes } = yield* refresh; const { defaultTheme } = yield* settings.getSettings; - if (themeId === undefined) return { current: defaultTheme, themes }; + const themesDir = environmentThemesDir; + if (themeId === undefined) return { current: defaultTheme, themesDir, themes }; const theme = themes.find((candidate) => candidate.id === themeId); if (theme === undefined) { return yield* new EnvironmentThemeRefusedError({ @@ -415,7 +454,7 @@ const make = Effect.gen(function* () { known: themes.map(({ id }) => id), }); } - return { current: defaultTheme, themes, theme }; + return { current: defaultTheme, themesDir, themes, theme }; }); return { diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index d1bae5d859d65..5c5c9636406e1 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1746,7 +1746,7 @@ const make = Effect.gen(function* () { messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: ["assistant_message", "error"], + turnItemTypes: ["assistant_message", "error", "system_notice"], }) .pipe(Effect.mapError(threadManagementFailure)); const childProjection = { diff --git a/apps/server/src/mcp/toolkits/theme/handlers.ts b/apps/server/src/mcp/toolkits/theme/handlers.ts index ad469095b0e0d..1f8aede7f3996 100644 --- a/apps/server/src/mcp/toolkits/theme/handlers.ts +++ b/apps/server/src/mcp/toolkits/theme/handlers.ts @@ -16,6 +16,7 @@ export const layer = McpToolAccess.toLayer(ThemeToolkit, { const themes = yield* EnvironmentTheme.EnvironmentThemeService; const { current, + themesDir, themes: published, theme, } = yield* themes.read(themeId).pipe( @@ -30,8 +31,14 @@ export const layer = McpToolAccess.toLayer(ThemeToolkit, { return { current, builtIn: BUILT_IN_THEME_IDS, - published: published.map(({ id, name, css }) => ({ id, name, hasCss: Boolean(css) })), - ...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id"]) }), + published: published.map(({ id, name, css, background }) => ({ + id, + name, + hasCss: Boolean(css), + hasBackground: background !== undefined, + })), + ...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id", "background"]) }), + themesDir, guide: THEME_GUIDE, }; }), diff --git a/apps/server/src/mcp/toolkits/theme/tools.ts b/apps/server/src/mcp/toolkits/theme/tools.ts index f055e8776180f..716c540b2c41e 100644 --- a/apps/server/src/mcp/toolkits/theme/tools.ts +++ b/apps/server/src/mcp/toolkits/theme/tools.ts @@ -41,9 +41,11 @@ const ThemeReadTool = Tool.make("t3_theme_read", { id: EnvironmentThemeId, name: Schema.String, hasCss: Schema.Boolean, + hasBackground: Schema.Boolean, }), ), theme: Schema.optionalKey(EnvironmentThemeFile), + themesDir: Schema.String, guide: Schema.String, }), }) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index cf533de93e4d6..b2b27327b66dc 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -15224,6 +15224,126 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #37708 a gateway that holds the request open leaves Claude silent after "requesting" + it.effect.each([ + { case: "after the prompt starts", requesting: false, backgroundProgress: false }, + { case: "after a request goes out", requesting: true, backgroundProgress: false }, + { case: "while a skill it forked runs", requesting: false, forkedTask: true }, + { + case: "while an earlier background agent starts a nested task", + requesting: false, + nestedTaskStarted: true, + }, + { + case: "while an earlier background task reports progress", + requesting: false, + backgroundProgress: true, + }, + ])( + "does not keep a turn silently running when Claude goes quiet $case", + ({ requesting, backgroundProgress = false, forkedTask = false, nestedTaskStarted = false }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-silent-after-started"), + text: "start again", + attachments: [], + }), + ); + // Captured from Claude Code 2.1.325 against a gateway that never answers /v1/messages. + for (const [index, state] of (["queued", "started"] as const).entries()) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state, + uuid: `00000000-0000-4000-8000-00000000079${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + } + if (requesting) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "requesting", + uuid: "00000000-0000-4000-8000-000000000792", + session_id: WAKE_NATIVE_SESSION, + }), + ); + } + if (backgroundProgress) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: "earlier-background-task", + description: "Earlier background task", + usage: { total_tokens: 1, tool_uses: 0, duration_ms: 1 }, + uuid: "00000000-0000-4000-8000-000000000793", + session_id: WAKE_NATIVE_SESSION, + }), + ); + } + if (nestedTaskStarted) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "earlier-nested-task", + description: "Nested task of an earlier background agent", + spawn_depth: 2, + uuid: "00000000-0000-4000-8000-000000000795", + session_id: WAKE_NATIVE_SESSION, + }), + ); + } + if (forkedTask) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "forked-skill-task", + description: "Forked skill", + uuid: "00000000-0000-4000-8000-000000000794", + session_id: WAKE_NATIVE_SESSION, + }), + ); + } + assert.lengthOf(harness.terminalEvents(), 0); + + yield* TestClock.adjust("1 hour"); + yield* yieldTicks(50); + const surfaced = + harness.terminalEvents().length > 0 || + harness.events.some( + (event) => + event.type === "turn_item.updated" && + (event.turnItem.type === "system_notice" || event.turnItem.type === "error"), + ); + if (forkedTask) { + assert.lengthOf(harness.terminalEvents(), 0, "a long forked skill was failed as silence"); + } else { + assert.isTrue(surfaced, "an hour of silence after the prompt started surfaced nothing"); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it it.effect.each([ { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index fa8d3684f0f23..34d81c88d3559 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4949,6 +4949,8 @@ function formatClaudeUsageLimitWait(waitMs: number): string { interface ActiveClaudeTurnContext { retryBudgetFailure?: OrchestrationV2ProviderFailure; + // Set when the prompt starts or a request goes out; cleared by the turn's next frame. + unansweredRequestSince?: DateTime.Utc | undefined; readonly queryPolicy: ClaudeRuntimeQueryPolicy; readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; readonly autoCompactWindow: string; @@ -6397,40 +6399,73 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( : undefined; }); const retry = yield* isCurrentRetry; - // A user Stop already in flight keeps its interrupted outcome. - if ( - retry === undefined || - (yield* Ref.get(interruptedTurns)).has(context.providerTurnId) - ) - return; - context.retryBudgetFailure = { ...retry.failure, retryable: false }; - const liveQuery = yield* Ref.get(queryContext); - yield* interruptTurn({ - providerThread: context.input.providerThread, - providerTurnId: context.providerTurnId, - }).pipe( - Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), - Effect.catch((cause) => - Effect.logWarning("orchestration-v2.claude-retry-budget-stop-failed", { cause }), - ), - ); - if (liveQuery === null || (yield* isCurrentRetry) === undefined) return; - // The CLI did not confirm the stop; settle the turn without it. - const ownedLiveQuery = yield* Ref.modify(queryContext, (current) => - current?.query === liveQuery.query ? [true, null] : [false, current], - ); - if (!ownedLiveQuery) return; - liveQuery.stopping = true; - yield* liveQuery.query.close.pipe( - Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), - Effect.ignore, + if (retry === undefined) return; + yield* failStalledTurn( + context, + { ...retry.failure, retryable: false }, + Effect.map(isCurrentRetry, (current) => current !== undefined), ); - yield* finalizeActiveTurnAfterQueryExit(liveQuery); - yield* endSubagentCallsOfClosedQuery(liveQuery.nativeThreadId, "interrupted"); - yield* Deferred.succeed(liveQuery.closed, undefined); }, ); + // Partial messages are on, so a started prompt or a sent request streams within seconds. + // A gateway can hold the request open without ever letting the CLI time out and retry. + const failUnansweredRequest = Effect.fn("ClaudeAdapterV2.failUnansweredRequest")(function* ( + context: ActiveClaudeTurnContext, + since: DateTime.Utc, + ) { + const isUnanswered = Effect.map( + Ref.get(activeTurn), + (active) => active === context && context.unansweredRequestSince === since, + ); + if (!(yield* isUnanswered)) return; + yield* failStalledTurn( + context, + makeProviderFailure({ + class: "transport_error", + code: "claude_request_unanswered", + message: `Claude sent nothing for ${PROVIDER_RETRY_BUDGET_MS / 60_000} minutes. The API or a gateway in front of it is not responding.`, + retryable: false, + }), + // Once the stop is sent, a frame clearing the silence must not skip forced settlement. + Effect.map(Ref.get(activeTurn), (active) => active === context), + ); + }); + + const failStalledTurn = Effect.fn("ClaudeAdapterV2.failStalledTurn")(function* ( + context: ActiveClaudeTurnContext, + failure: OrchestrationV2ProviderFailure, + stillStalled: Effect.Effect, + ) { + // A user Stop already in flight keeps its interrupted outcome. + if ((yield* Ref.get(interruptedTurns)).has(context.providerTurnId)) return; + context.retryBudgetFailure = failure; + const liveQuery = yield* Ref.get(queryContext); + yield* interruptTurn({ + providerThread: context.input.providerThread, + providerTurnId: context.providerTurnId, + }).pipe( + Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.claude-retry-budget-stop-failed", { cause }), + ), + ); + if (liveQuery === null || !(yield* stillStalled)) return; + // The CLI did not confirm the stop; settle the turn without it. + const ownedLiveQuery = yield* Ref.modify(queryContext, (current) => + current?.query === liveQuery.query ? [true, null] : [false, current], + ); + if (!ownedLiveQuery) return; + liveQuery.stopping = true; + yield* liveQuery.query.close.pipe( + Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), + Effect.ignore, + ); + yield* finalizeActiveTurnAfterQueryExit(liveQuery); + yield* endSubagentCallsOfClosedQuery(liveQuery.nativeThreadId, "interrupted"); + yield* Deferred.succeed(liveQuery.closed, undefined); + }); + const rememberProviderThread = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (providerThread: OrchestrationV2ProviderThread) { @@ -10556,6 +10591,33 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } return; } + if (context === (yield* Ref.get(activeTurn))) { + const lifecycle = claudePromptLifecycle(message); + if ( + (message.type === "system" && + message.subtype === "status" && + message.status === "requesting") || + (lifecycle?.state === "started" && lifecycle.uuid === context.promptUuid) + ) { + const since = yield* DateTime.now; + context.unansweredRequestSince = since; + yield* failUnansweredRequest(context, since).pipe( + Effect.delay(PROVIDER_RETRY_BUDGET_MS), + Effect.forkIn(sessionScope), + ); + } else if ( + // Background tasks from earlier turns keep streaming while the root request hangs. + // Only the root starts depth-1 tasks, so such a start (a forked skill) is this turn's. + Reflect.get(message, "parent_tool_use_id") == null && + !( + message.type === "system" && + message.subtype.startsWith("task_") && + !(message.subtype === "task_started" && (message.spawn_depth ?? 1) <= 1) + ) + ) { + context.unansweredRequestSince = undefined; + } + } const focusedPlugin = claudeFocusRequestedPanePlugin(message); if (focusedPlugin !== null && context === (yield* Ref.get(activeTurn))) { yield* Effect.logWarning("orchestration-v2.claude-mod-pane-focus-unsupported", { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 4308e780ba4fb..019dcf4ec0edb 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -3743,7 +3743,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { { hook: "wrong-turn", status: "interrupted", expected: false }, { hook: "wrong-thread", status: "interrupted", expected: false }, { hook: "unscoped", status: "interrupted", expected: false }, - { hook: "stopped", status: "completed", expected: false }, + { hook: "stopped", status: "completed", expected: true }, { hook: "stopped", status: "failed", expected: false }, ] as const)( "correlates $hook hook output with a $status turn only", diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index c464b1e3c287a..d1ddd569e60d5 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6435,7 +6435,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( runOrdinal: input.context.input.runOrdinal, status: terminalStatus, failure: null, - ...(terminalStatus === "interrupted" && input.context.hookStopReason !== undefined + ...(input.context.hookStopReason !== undefined ? { reason: input.context.hookStopReason } : {}), threadDisposition: "reusable", diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index e26487fdf2667..72ea19a442dba 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -57,6 +57,7 @@ import * as ProviderTurnStartServiceTestkit from "./ProviderTurnStartService.tes import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { PROVIDER_STOP_REASON_SIGNAL } from "@t3tools/provider-core/server/subagentProjection"; import * as ProviderContinuationService from "./ProviderContinuationService.ts"; const layerPlatformTest = Layer.merge( @@ -3251,6 +3252,7 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( id: EventId.make(`event:followup-command-awaited-${ending}`), type: "provider-thread.updated", threadId: child.childThreadId, + runId: followupRun.id, driver, providerInstanceId: modelSelection.instanceId, occurredAt: now, @@ -3431,6 +3433,329 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( }), ); + it.effect("settles a follow-up whose own run started no background work", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread:followup-earlier-work-parent"); + const projectId = ProjectId.make("project:followup-earlier-work"); + const parentRunId = RunId.make("run:followup-earlier-work-parent"); + const rootNodeId = NodeId.make("node:followup-earlier-work-parent"); + yield* seedParentWithTerminalTask({ + threadId: parentThreadId, + projectId, + runId: parentRunId, + rootNodeId, + taskId: NodeId.make("node:followup-earlier-work-seed"), + deliveryState: "acknowledged", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId, + projectId, + parentRunId, + rootNodeId, + name: "followup-earlier-work-child", + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + yield* orchestrator.recoverDelegatedTasks; + const parent = yield* orchestrator.getThreadProjection(parentThreadId); + const childProviderThread = { + ...parent.providerThreads[0]!, + id: ProviderThreadId.make("provider-thread:followup-earlier-work-child"), + appThreadId: child.childThreadId, + }; + + // An earlier run of the child left an awaited build running. + yield* eventSink.write({ + commandId: reconcileCommandId("followup-earlier-work-build"), + events: [ + { + id: EventId.make("event:followup-earlier-work-build"), + type: "provider-thread.updated", + threadId: child.childThreadId, + runId: child.childRunId, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + ...childProviderThread, + pendingBackgroundTasks: [ + { taskId: "build", kind: "command" as const, awaited: true as const }, + ], + }, + }, + ], + }); + + const followupMessageId = MessageId.make("message:followup-earlier-work-send"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make("command:followup-earlier-work-send"), + threadId: child.childThreadId, + senderThreadId: parentThreadId, + messageId: followupMessageId, + text: "Reply with exactly PONG.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + }); + const followupRun = (yield* orchestrator.getThreadProjection( + child.childThreadId, + )).runs.find((run) => run.userMessageId === followupMessageId)!; + const followupTaskId = followupRun.delegatedTaskId!; + + // The follow-up's run answers and ends without starting any background work. + yield* eventSink.write({ + commandId: reconcileCommandId("followup-earlier-work-answered"), + events: [ + // The provider resends its whole roster during the follow-up's run. + { + id: EventId.make("event:followup-earlier-work-roster"), + type: "provider-thread.updated", + threadId: child.childThreadId, + runId: followupRun.id, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + ...childProviderThread, + pendingBackgroundTasks: [ + { taskId: "build", kind: "command" as const, awaited: true as const }, + ], + }, + }, + { + id: EventId.make("event:followup-earlier-work-answer"), + type: "message.updated", + threadId: child.childThreadId, + runId: followupRun.id, + occurredAt: now, + payload: { + id: MessageId.make("message:followup-earlier-work-answer"), + threadId: child.childThreadId, + runId: followupRun.id, + nodeId: null, + role: "assistant", + text: "PONG", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + createdAt: now, + updatedAt: now, + }, + }, + { + id: EventId.make("event:followup-earlier-work-run-completed"), + type: "run.updated", + threadId: child.childThreadId, + runId: followupRun.id, + occurredAt: now, + payload: { ...followupRun, status: "completed", startedAt: now, completedAt: now }, + }, + ], + }); + yield* orchestrator.recoverDelegatedTasks; + + const followup = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === followupTaskId, + ); + assert.equal(followup?.status, "completed"); + assert.equal(followup?.result, "PONG"); + }), + ); + + it.effect("settles a follow-up when its own work ends while another's still runs", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread:followup-own-work-parent"); + const projectId = ProjectId.make("project:followup-own-work"); + const parentRunId = RunId.make("run:followup-own-work-parent"); + const rootNodeId = NodeId.make("node:followup-own-work-parent"); + yield* seedParentWithTerminalTask({ + threadId: parentThreadId, + projectId, + runId: parentRunId, + rootNodeId, + taskId: NodeId.make("node:followup-own-work-seed"), + deliveryState: "acknowledged", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId, + projectId, + parentRunId, + rootNodeId, + name: "followup-own-work-child", + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + yield* orchestrator.recoverDelegatedTasks; + const parent = yield* orchestrator.getThreadProjection(parentThreadId); + const childProviderThread = { + ...parent.providerThreads[0]!, + id: ProviderThreadId.make("provider-thread:followup-own-work-child"), + appThreadId: child.childThreadId, + }; + const awaited = (taskId: string) => ({ + taskId, + kind: "command" as const, + awaited: true as const, + }); + const roster = (name: string, runId: RunId, tasks: ReadonlyArray) => ({ + id: EventId.make(`event:followup-own-work-roster-${name}`), + type: "provider-thread.updated" as const, + threadId: child.childThreadId, + runId, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { ...childProviderThread, pendingBackgroundTasks: tasks.map(awaited) }, + }); + const settledTask = (taskId: NodeId, afterSequence: number) => + eventSink.stream({ afterSequence, eventType: "subagent.updated" }).pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === taskId && + stored.event.payload.status === "completed", + ), + Stream.take(1), + Stream.runDrain, + ); + const send = (name: string) => + Effect.gen(function* () { + const messageId = MessageId.make(`message:followup-own-work-send-${name}`); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make(`command:followup-own-work-send-${name}`), + threadId: child.childThreadId, + senderThreadId: parentThreadId, + messageId, + text: `Start build ${name} in the background and wait on it.`, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + }); + return (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find( + (run) => run.userMessageId === messageId, + )!; + }); + + // Follow-up A starts awaited build a, answers and ends its turn. + const runA = yield* send("a"); + yield* eventSink.write({ + commandId: reconcileCommandId("followup-own-work-a-ended"), + events: [ + roster("a", runA.id, ["a"]), + { + id: EventId.make("event:followup-own-work-a-answer"), + type: "message.updated", + threadId: child.childThreadId, + runId: runA.id, + occurredAt: now, + payload: { + id: MessageId.make("message:followup-own-work-a-answer"), + threadId: child.childThreadId, + runId: runA.id, + nodeId: null, + role: "assistant", + text: "A-DONE", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + createdAt: now, + updatedAt: now, + }, + }, + { + id: EventId.make("event:followup-own-work-a-completed"), + type: "run.updated", + threadId: child.childThreadId, + runId: runA.id, + occurredAt: now, + payload: { ...runA, status: "completed", startedAt: now, completedAt: now }, + }, + ], + }); + yield* orchestrator.recoverDelegatedTasks; + + // Follow-up B starts awaited build b and is still running. + const runB = yield* send("b"); + yield* eventSink.write({ + commandId: reconcileCommandId("followup-own-work-b-started"), + events: [ + { + id: EventId.make("event:followup-own-work-b-running"), + type: "run.updated", + threadId: child.childThreadId, + runId: runB.id, + occurredAt: now, + payload: { ...runB, status: "running", startedAt: now }, + }, + roster("ab", runB.id, ["a", "b"]), + ], + }); + // Run updates react in order, so the barrier settling means B's start was handled too. + const barrier = yield* seedRestartCancelledChild({ + parentThreadId, + projectId, + parentRunId, + rootNodeId, + name: "followup-own-work-barrier", + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + const beforeBarrier = yield* eventSink.latestSequence(); + yield* eventSink.write({ + events: [ + { + ...runEvent({ + threadId: barrier.childThreadId, + runId: barrier.childRunId, + ordinal: 1, + status: "completed", + now, + }), + id: EventId.make("event:followup-own-work-barrier-ended"), + }, + ], + }); + yield* settledTask(barrier.taskId, beforeBarrier); + assert.equal( + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === runA.delegatedTaskId, + )?.status, + "running", + ); + + // Build a ends; the roster still holds b, and no run update follows. + const beforeSettle = yield* eventSink.latestSequence(); + yield* eventSink.write({ + commandId: reconcileCommandId("followup-own-work-a-settled"), + events: [roster("b", runB.id, ["b"])], + }); + yield* settledTask(runA.delegatedTaskId!, beforeSettle); + const tasks = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents; + assert.equal(tasks.find((task) => task.id === runA.delegatedTaskId)?.result, "A-DONE"); + assert.equal(tasks.find((task) => task.id === runB.delegatedTaskId)?.status, "running"); + }), + ); + it.effect("waits for a run the follow-up's child queued on its own thread", () => Effect.gen(function* () { const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; @@ -4652,6 +4977,7 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { it.effect("cancelling a task whose child already finished keeps its completed result", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; const now = yield* DateTime.now; const threadId = ThreadId.make("thread:cancel-finished-parent"); const projectId = ProjectId.make("project:cancel-finished-parent"); @@ -4678,6 +5004,43 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { runStatus: "completed", now, }); + const stopReason = "sessionStart hook (user): Plugin guard blocked this session."; + yield* eventSink.write({ + commandId: CommandId.make("command:cancel-finished-child:stop-reason"), + events: [ + { + id: EventId.make("event:cancel-finished-child:stop-reason"), + type: "turn-item.updated", + threadId: child.childThreadId, + runId: child.childRunId, + nodeId: rootNodeId, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + id: IdAllocator.derive.runSignalTurnItem({ + runId: child.childRunId, + signal: PROVIDER_STOP_REASON_SIGNAL, + }), + type: "system_notice", + level: "warning", + threadId: child.childThreadId, + runId: child.childRunId, + nodeId: rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 98, + status: "completed", + title: "Stopped by the provider", + startedAt: now, + completedAt: now, + updatedAt: now, + message: stopReason, + }, + }, + ], + }); yield* orchestrator.cancelDelegatedTask({ parentThreadId: threadId, taskId: child.taskId, @@ -4693,6 +5056,10 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { (row) => row.id === child.taskId, ); assert.equal(task?.status, "completed"); + assert.equal( + task?.result, + `Child task completed without an assistant result.\n\n${stopReason}`, + ); assert.isUndefined(task?.cancelledRunId); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 214f6cf360e20..ff96b2fbac1ac 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -23,14 +23,15 @@ import { import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Metric from "effect/Metric"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; -import type * as Tracer from "effect/Tracer"; import * as TestClock from "effect/testing/TestClock"; +import * as Tracer from "effect/Tracer"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; import { @@ -1880,7 +1881,21 @@ it.effect.each([false, true])("rejects thread.create for an existing id (deleted ref: { driver: adapter.driver, nativeId: "native-original", strength: "strong" }, }, } as const; - yield* orchestrator.dispatch(create); + const failedSpans: Array = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + if (Exit.isFailure(exit)) failedSpans.push(span.name); + }; + return span; + }, + }); + yield* orchestrator.dispatch(create).pipe(Effect.withTracer(tracer)); + // The id check expects a miss; a failed span there reads as an error in Tempo. + assert.deepEqual(failedSpans, []); if (deleted) { yield* orchestrator.dispatch({ type: "thread.delete", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 27f7aa82fd25c..27b7a2e12878d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1821,10 +1821,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio /** Includes tombstones, which still reserve their id. */ const findThread = (threadId: ThreadId) => - projectionStore.getThread(threadId).pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), - ); + projectionStore + .findThread(threadId) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); /** Side chats live inside their parent, so deleting the parent deletes them too. */ const liveSideChatIds = Effect.fn("Orchestrator.liveSideChatIds")( @@ -1839,11 +1838,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const sideChatIds: Array = []; for (const transfer of contextTransfers) { if (transfer.type !== "fork" || transfer.sourceThreadId !== threadId) continue; - const child = yield* projectionStore - .getThread(transfer.targetThreadId) - .pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - ); + const child = yield* projectionStore.findThread(transfer.targetThreadId); if (child?.lineage.sideChat === true && child.deletedAt === null) { sideChatIds.push(child.id); } @@ -3762,12 +3757,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); // Tombstones reserve their ids too; recreating one would overwrite its history. - const existing = yield* projectionStore.getThread(command.threadId).pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), - ), - ); + const existing = yield* findThread(command.threadId); if (existing !== null) { return yield* new OrchestratorThreadAlreadyExistsError({ commandId: command.commandId, @@ -5643,10 +5633,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (runtimeModeCeiling === undefined) return; const runtimeModes = new Map(); for (const threadId of threadsStartingWork(events)) { - const thread = yield* projectionStore.getThread(threadId).pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), - ); + const thread = yield* findThread(threadId); if (thread !== null) runtimeModes.set(threadId, thread.runtimeMode); } const refusal = runtimeModeCeilingRefusal( @@ -14428,7 +14415,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageRoles: ["assistant"], messageRunIds: [childRun.id], turnItemRunId: childRun.id, - turnItemTypes: ["assistant_message", "error"], + turnItemTypes: ["assistant_message", "error", "system_notice"], }, ); const childProjection = { @@ -15885,18 +15872,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A child whose run ends while its background tasks or its own subagents still run has no // result yet. When that work settles there is no run update to finalize it, so these events - // do it. A background roster counts once it stops holding after it was seen holding. - const providerThreadsWithBackgroundWork = new Set(); + // do it. A roster counts when a task seen holding leaves it, since that may be one follow-up's. + const holdingTaskIdsByProviderThread = new Map>(); const settlesChildWork = (stored: OrchestrationV2StoredEvent) => { const { event } = stored; if (event.type === "subagent.updated") return !isOrchestrationV2WorkActive(event.payload.status); if (event.type !== "provider-thread.updated") return false; - if (backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])) { - providerThreadsWithBackgroundWork.add(event.payload.id); - return false; - } - return providerThreadsWithBackgroundWork.delete(event.payload.id); + const holding = new Set( + (event.payload.pendingBackgroundTasks ?? []) + .filter((task) => backgroundWorkHoldsCompletion([task])) + .map((task) => task.taskId), + ); + const previous = holdingTaskIdsByProviderThread.get(event.payload.id); + if (holding.size > 0) holdingTaskIdsByProviderThread.set(event.payload.id, holding); + else holdingTaskIdsByProviderThread.delete(event.payload.id); + return previous !== undefined && [...previous].some((taskId) => !holding.has(taskId)); }; yield* Stream.merge( eventSink.stream({ diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 5b71a6ac042f1..289bdce2276c0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -625,6 +625,10 @@ export interface ProjectionStoreV2Shape { readonly getThread: ( threadId: ThreadId, ) => Effect.Effect; + /** Like getThread, but a missing thread is null, so an expected miss is not an error span. */ + readonly findThread: ( + threadId: ThreadId, + ) => Effect.Effect; readonly getLimitRecoveryCandidates: (options: { readonly now: DateTime.Utc; readonly autoResume: boolean; @@ -844,6 +848,26 @@ function upsertById(items: ReadonlyArray, return updated; } +/** Adapters resend whole rosters without runs, so a task keeps the run it first appeared under. */ +function attributePendingBackgroundTasks( + next: OrchestrationV2ProviderThread, + previous: Pick | undefined, + runId: OrchestrationV2DomainEvent["runId"], +): OrchestrationV2ProviderThread { + const tasks = next.pendingBackgroundTasks ?? []; + if (tasks.every((task) => task.runId !== undefined)) return next; + const known = new Map( + (previous?.pendingBackgroundTasks ?? []).map((task) => [task.taskId, task.runId]), + ); + return { + ...next, + pendingBackgroundTasks: tasks.map((task) => { + const owner = task.runId ?? (known.has(task.taskId) ? known.get(task.taskId) : runId); + return owner === undefined ? task : { ...task, runId: owner }; + }), + }; +} + function upsertProviderTurn( turns: ReadonlyArray, next: OrchestrationV2ProviderTurn, @@ -1040,7 +1064,14 @@ export function applyToProjection( activeProviderThreadId: event.payload.id, } : base.thread, - providerThreads: upsertById(base.providerThreads, event.payload), + providerThreads: upsertById( + base.providerThreads, + attributePendingBackgroundTasks( + event.payload, + base.providerThreads.find((thread) => thread.id === event.payload.id), + event.runId, + ), + ), }; case "provider-turn.updated": return { @@ -2687,7 +2718,26 @@ export const layer: Layer.Layer = break; } case "provider-thread.updated": { - const payloadJson = yield* encodeProviderThreadPayload(event.payload); + const existingRows = (event.payload.pendingBackgroundTasks ?? []).some( + (task) => task.runId === undefined, + ) + ? yield* sql` + SELECT payload_json + FROM orchestration_v2_projection_provider_threads + WHERE provider_thread_id = ${event.payload.id} + LIMIT 1 + ` + : []; + const existing = existingRows[0]; + const payloadJson = yield* encodeProviderThreadPayload( + attributePendingBackgroundTasks( + event.payload, + existing === undefined + ? undefined + : yield* decodeProviderThreadPayload(existing.payload_json), + event.runId, + ), + ); const payload = parseEncodedPayload(payloadJson); yield* sql` INSERT INTO orchestration_v2_projection_provider_threads ( @@ -5611,27 +5661,29 @@ export const layer: Layer.Layer = ), ); + const selectThread = (threadId: ThreadId) => + sql` + SELECT payload_json FROM orchestration_v2_projection_threads + WHERE thread_id = ${threadId} + `.pipe( + Effect.flatMap((rows) => + rows[0] === undefined ? Effect.succeed(null) : decodeThreadPayload(rows[0].payload_json), + ), + Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })), + ); + const getThread: ProjectionStoreV2Shape["getThread"] = Effect.fn("ProjectionStore.getThread")( function* (threadId) { - const rows = yield* sql` - SELECT payload_json FROM orchestration_v2_projection_threads - WHERE thread_id = ${threadId} - `; - if (rows[0] === undefined) { - return yield* new ProjectionStoreThreadNotFoundError({ threadId }); - } - return yield* decodeThreadPayload(rows[0].payload_json); + const thread = yield* selectThread(threadId); + if (thread === null) return yield* new ProjectionStoreThreadNotFoundError({ threadId }); + return thread; }, - (effect, threadId) => - effect.pipe( - Effect.mapError((cause) => - isProjectionStoreThreadNotFoundError(cause) - ? cause - : new ProjectionStoreReadError({ threadId, cause }), - ), - ), ); + const findThread: ProjectionStoreV2Shape["findThread"] = Effect.fn( + "ProjectionStore.findThread", + )(selectThread); + const requireThread = Effect.fn("ProjectionStore.requireThread")(function* ( threadId: ThreadId, ) { @@ -9292,6 +9344,7 @@ export const layer: Layer.Layer = getThreadShell: readOnReader(getThreadShell), findGuestShareThreadId: readOnReader(findGuestShareThreadId), getThread: readOnReader(getThread), + findThread: readOnReader(findThread), getSettlementCandidates: readOnReader(getSettlementCandidates), getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests), getThreadTitles: readOnReader(getThreadTitles), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 532d019ddd6fb..069e36ceef916 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -226,6 +226,7 @@ it.effect( getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"), findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"), getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)), + findThread: () => Effect.die("unused findThread"), getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"), getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"), getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"), diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts index bb0b3380c38c4..4cb350a380a84 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts @@ -325,6 +325,24 @@ const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* ( yield* reactor.drain; }); +const sweepFor = Effect.fn("sweepPullRequestSyncHarnessFor")(function* ( + fixture: Harness, + reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"], + minutes: number, +) { + for (let minute = 0; minute < minutes; minute++) yield* sweepAgain(fixture, reactor); +}); + +const failingGitLabLink = makeLink(13, null, { + host: "gitlab.com", + url: "https://gitlab.com/owner/repository/-/merge_requests/13", +}); + +const gitLabCliFailure = new PullRequestOperationError({ + operation: "summary", + detail: "GitLab CLI command failed", +}); + function runUpdated( threadId: ThreadId, status: OrchestrationV2Run["status"], @@ -1839,6 +1857,76 @@ describe("PullRequestSyncReactor", () => { }), ); + it.effect( + "caps the failed-read backoff at the slow cadence and restarts it after a success", + () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const failing = yield* Ref.make(true); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([makeThread("one", { pullRequests: [failingGitLabLink] })]), + summary: (input) => + Ref.get(failing).pipe( + Effect.flatMap((fails) => + fails ? Effect.fail(gitLabCliFailure) : Effect.succeed(makeSummary(input)), + ), + ), + }); + yield* Effect.gen(function* () { + const reactor = yield* startAndSweep(fixture); + const readMinutes = [0]; + const sweepMinutes = Effect.fnUntraced(function* (from: number, to: number) { + for (let minute = from; minute <= to; minute++) { + const before = (yield* Ref.get(fixture.summaryCalls)).length; + yield* sweepAgain(fixture, reactor); + if ((yield* Ref.get(fixture.summaryCalls)).length > before) + readMinutes.push(minute); + } + }); + + yield* sweepMinutes(1, 60); + assert.deepStrictEqual(readMinutes, [0, 1, 3, 7, 15, 30, 45, 60]); + + yield* Ref.set(failing, false); + yield* sweepMinutes(61, 75); + yield* Ref.set(failing, true); + readMinutes.length = 0; + yield* sweepMinutes(76, 80); + assert.deepStrictEqual(readMinutes, [76, 77, 79]); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + + it.effect("reads a backed-off link at once when a refresh asks, then keeps backing off", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([makeThread("one", { pullRequests: [failingGitLabLink] })]), + summary: () => Effect.fail(gitLabCliFailure), + }); + yield* Effect.gen(function* () { + const reactor = yield* startAndSweep(fixture); + yield* sweepFor(fixture, reactor, 4); + const backedOffReads = (yield* Ref.get(fixture.summaryCalls)).length; + + yield* reactor.requestSync(failingGitLabLink); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 1); + + // The refresh failed at minute 4 with the backoff doubled to 8 minutes. + yield* sweepFor(fixture, reactor, 7); + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 1); + yield* sweepAgain(fixture, reactor); + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 2); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + it.effect.each([ "gh pr merge 7 --squash 2>&1 | tail -3", "cafe pr merge 7 --squash", diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts index 96f0be4e59dc6..d962ee8f672d0 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts @@ -48,6 +48,8 @@ export const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000; // A pull request closed this long ago is rarely reopened, so the sweep stops reading it, as it // does merged ones. A reader that sees it open, or a requested refresh, still reads it at once. const CLOSED_FINAL_AFTER_MS = 24 * 60 * 60 * 1_000; +// A link whose host read failed waits a sweep, then twice as long after each further failure. +const FAILED_READ_BACKOFF_MS = 60 * 1_000; const isChangeRequestCloseCommand = (command: string) => sourceControlDefinitions.definitions.some( @@ -369,6 +371,7 @@ export const make = Effect.gen(function* () { // linking dozens of pull requests) is read together and shares the summary batches. let requestedSweepQueued = false; const retryStacks = new Set(); + const failedReads = new Map(); // Group keys the host answered not-found for, or this server cannot read (no CLI, signed out, // unsupported host); they are read on the slow cadence until a read succeeds. const missing = new Set(); @@ -376,6 +379,7 @@ export const make = Effect.gen(function* () { const pausedUntil = new Map(); const isDue = (key: string, entries: ReadonlyArray, nowMs: number): boolean => { + if ((failedReads.get(key)?.retryAtMs ?? 0) > nowMs) return false; if (requested.has(key)) return true; const active = entries.filter((entry) => isUnsettled(entry.thread)); if (active.length === 0) return false; @@ -425,12 +429,17 @@ export const make = Effect.gen(function* () { // A host-level refresh reaches every project, each retaining its own pending retry. for (const [key, entries] of groups) { - if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key); + if (!pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) continue; + requested.add(key); + // A new request reads at once; a failure after it backs off further, not from the start. + const failed = failedReads.get(key); + if (failed !== undefined) failedReads.set(key, { ...failed, retryAtMs: nowMs }); } pendingRequests.clear(); for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key); for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key); + for (const key of failedReads.keys()) if (!groups.has(key)) failedReads.delete(key); for (const key of missing) if (!groups.has(key)) missing.delete(key); for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key); @@ -599,6 +608,7 @@ export const make = Effect.gen(function* () { } // The host answered, so the cadence clock ticks even if a dispatch below is rejected. lastSyncedAt.set(key, nowMs); + failedReads.delete(key); requested.delete(key); yield* Effect.forEach( entries, @@ -624,6 +634,13 @@ export const make = Effect.gen(function* () { const retryAt = rateLimitRetryAt(cause); if (retryAt !== undefined) { pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0)); + } else { + const previous = failedReads.get(key); + const backoffMs = + previous === undefined + ? FAILED_READ_BACKOFF_MS + : Math.min(previous.backoffMs * 2, SLOW_SYNC_INTERVAL_MS); + failedReads.set(key, { retryAtMs: nowMs + backoffMs, backoffMs }); } const reason = skipReason(cause); const skip = skips.get(reason); diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 5b69a7efa3377..3485765a0ed93 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -137,8 +137,9 @@ interface WatchLife { readonly reads: number; } -const lifeKey = ({ thread, link, watch }: WatchTarget) => - `${thread.id} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`; +const lifeKeyOf = (threadId: string, link: ThreadPullRequestLink, watch: ThreadPullRequestWatch) => + `${threadId} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`; +const lifeKey = ({ thread, link, watch }: WatchTarget) => lifeKeyOf(thread.id, link, watch); const minutes = (ms: number) => Math.max(0, Math.round(ms / 60_000)); @@ -863,6 +864,20 @@ export const make = Effect.gen(function* () { ); } }); + // A watch's first read is its baseline, so it reads now: CI that finishes before the next + // sweep would otherwise be taken as old news and never wake the thread. + yield* forkParked( + Stream.runForEach(engine.streamDomainEvents, (event) => { + if (event.type !== "thread.pull-request-synced") return Effect.void; + const unread = visibleThreadPullRequests(event.payload.pullRequests ?? []).flatMap( + (link) => + link.watch === undefined || lives.has(lifeKeyOf(event.threadId, link, link.watch)) + ? [] + : [threadPullRequestKeyOf(link)], + ); + return Effect.forEach(new Set(unread), readOnChange, { discard: true }); + }).pipe(Effect.catchCause(logFailure("pull request watch event stream failed", {}))), + ); yield* forkParked( sweep.pipe( Effect.andThen(follow), diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 23a95bc2bd20f..9dae3e539c09e 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -227,8 +227,8 @@ export function delegatedTaskRuns( } /** - * A follow-up task's runs still owe a subagent they started its result, or the child still - * awaits background work, as the original task waits on both. + * A follow-up task's runs still owe a subagent they started its result, or still await + * background work they started, as the original task waits on both. */ export function delegatedTaskAwaitsWork( runs: ReadonlyArray, @@ -245,7 +245,11 @@ export function delegatedTaskAwaitsWork( return ( child.subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)) || child.providerThreads.some((thread) => - backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []), + backgroundWorkHoldsCompletion( + (thread.pendingBackgroundTasks ?? []).filter( + (task) => task.runId !== undefined && runIds.has(task.runId), + ), + ), ) ); } diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 9a35624ecfe5f..8a3540a6a61f0 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -3183,6 +3183,21 @@ it.effect.each([ }), ); +it.effect("keeps a provider's stop reason on a completed run", () => + Effect.gen(function* () { + const reason = "sessionStart hook (user): Plugin guard blocked this session."; + const { written } = yield* captureRootRunTermination({ + key: "completed-stop-reason", + shouldFinalizeRun: () => Effect.succeed(true), + events: (ids) => Stream.make({ ...rootTerminalEvent(ids, "completed"), reason }), + }); + assert.deepEqual( + written.map((item) => (item.type === "system_notice" ? item.message : item.type)), + [reason], + ); + }), +); + it.effect("records a finished run as failed when its ownership check cannot be read", () => Effect.gen(function* () { const { observed } = yield* captureRootRunTermination({ diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index d29b47bbbb821..d7a021a873799 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -46,6 +46,7 @@ import * as CheckpointService from "./CheckpointService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { PROVIDER_STOP_REASON_SIGNAL } from "@t3tools/provider-core/server/subagentProjection"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import type { ProjectionStoreV2Error } from "./ProjectionStore.ts"; @@ -915,6 +916,42 @@ export const layer: Layer.Layer< }, ] : []), + // Codex reports a hook that stops the turn as completed; keep its reason visible. + ...(input.terminal.status === "completed" && input.terminal.reason !== undefined + ? [ + { + id: yield* allocateEventId(), + type: "turn-item.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { + id: idAllocator.derive.runSignalTurnItem({ + runId: input.run.id, + signal: PROVIDER_STOP_REASON_SIGNAL, + }), + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + providerThreadId: input.providerThread.id, + providerTurnId: input.rootNode.providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: input.run.ordinal * 100 + 98, + status: "completed" as const, + title: "Stopped by the provider", + startedAt: completedAt, + completedAt, + updatedAt: completedAt, + type: "system_notice" as const, + level: "warning" as const, + message: input.terminal.reason, + }, + }, + ] + : []), ...(input.terminal.status === "failed" && !input.failureItemPersisted ? [ { diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index 87204d763d2df..2f764233ba97b 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -10,6 +10,7 @@ import { EventId, TurnItemId, type OrchestrationV2Run, + type OrchestrationV2TurnItem, type OrchestrationV2AppThread, ProjectId, ProviderInstanceId, @@ -27,7 +28,9 @@ import { makeSubagentConversationArtifacts, endOrphanedNativeSubagent, endRunlessRootTurns, + PROVIDER_STOP_REASON_SIGNAL, } from "@t3tools/provider-core/server/subagentProjection"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -400,6 +403,36 @@ it("exposes the provider failure rather than a progress message from the failed assert.isNull(result.messageId); }); +it("reports a provider's stop reason for a completed run without an assistant result", () => { + const { projection, run } = taskFixture(); + const notice = { + id: IdAllocator.derive.runSignalTurnItem({ + runId: run.id, + signal: PROVIDER_STOP_REASON_SIGNAL, + }), + threadId: parentThreadId, + runId: run.id, + nodeId: NodeId.make("root"), + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 98, + status: "completed", + title: "Stopped by the provider", + startedAt: childCreatedAt, + completedAt: childCreatedAt, + updatedAt: childCreatedAt, + type: "system_notice", + level: "warning", + message: "sessionStart hook (user): Plugin guard blocked this session.", + } satisfies OrchestrationV2TurnItem; + assert.equal( + subagentResultForRun({ ...projection, turnItems: [notice] }, run).text, + `Child task completed without an assistant result.\n\n${notice.message}`, + ); +}); + it("keeps the final report of a run that failed after its turn ended", () => { const { projection, run } = taskFixture(); const failedRun = { ...run, status: "failed" as const }; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 0614a14861abd..b2d12935aa2f8 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -21,6 +21,7 @@ import { RuntimeRequestId, TurnItemId, type ModelSelection, + type OrchestrationV2DomainEvent, type OrchestrationV2Run, type OrchestrationV2ShellSnapshot, type OrchestrationV2RuntimeRequest, @@ -5450,6 +5451,135 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect( + "reads a pull request when its watch starts, so checks that pass before a sweep wake", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("runtime-pull-request-watch-start-read"); + const projectId = ProjectId.make("pr-watch-start-read-project"); + yield* seedProject({ + projectId, + title: "Watch start read", + workspaceRoot: "/workspace/watch-start-read", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("pr-watch-start-read-create"), + threadId, + projectId, + title: "Watch start read", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + + let checks: PullRequestDetail["checks"] = [ + { name: "lint", status: "pending", description: null, url: null, required: true }, + ]; + const detailReads = yield* Queue.unbounded(); + const watchListings = yield* Queue.unbounded(); + const domainEvents = yield* Queue.unbounded(); + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + // Earlier tests can leave watches in other projects; only this one's reads count. + detail: (input) => + (input.projectId === projectId + ? Queue.offer(detailReads, undefined) + : Effect.void + ).pipe( + Effect.as({ + ...watchedPullRequestDetail({ + projectId, + number: 16, + at: "2026-10-02T12:00:00.000Z", + }), + headSha: "bbbbbbbbbb", + checks, + }), + ), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + invalidate: () => Effect.void, + changes: () => Stream.never, + }), + // Events come from a queue that exists before the reactor subscribes, so none is missed. + Layer.mock(Orchestrator.OrchestratorV2)({ + dispatch: orchestrator.dispatch, + streamDomainEvents: Stream.fromQueue(domainEvents), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadsWithPullRequests: (id) => + projections + .getThreadsWithPullRequests(id) + .pipe(Effect.tap(() => Queue.offer(watchListings, undefined))), + }), + ); + const wakes = Effect.map( + orchestrator.getThreadRecords(threadId, ["messages"]), + ({ messages }) => + messages.filter( + (message) => message.notification !== undefined && message.notification !== null, + ), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* reactor.start(); + // The first sweep listed watches before this one existed, so it cannot be the read below. + yield* Queue.take(watchListings); + + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 16 }; + const started = yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-start-read-start"), + threadId, + ...key, + watching: true, + link: { url: "https://github.com/pingdotgg/t3code/pull/16", source: "agent" }, + }); + yield* Queue.offerAll( + domainEvents, + started.storedEvents.map((stored) => stored.event), + ); + // The clock never moves, so no sweep can be the read that sees the checks running. + yield* Queue.take(detailReads); + + checks = [ + { name: "lint", status: "success", description: null, url: null, required: true }, + ]; + // A sweep waits for the watch-start read in flight. + yield* reactor.sweep; + yield* worker.drain(); + const woken = yield* wakes; + assert.lengthOf(woken, 1); + assert.equal(woken[0]!.notification?.summary, "#16: checks passed"); + + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-start-read-end"), + threadId, + ...key, + watching: false, + }); + yield* worker.drain(); + }), + ); + it.effect("wakes for checks that complete after the no-checks notice on the same head", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts index 6c11f179dd4e0..9de3d50a316f1 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_background_monitor_wake/output.ts @@ -39,7 +39,9 @@ export function assertClaudeBackgroundMonitorWakeOutput( .filter((task) => task.taskId === MONITOR_TASK_ID); // The first roster precedes task_started linking the Monitor call, so that entry reads command. assert.isAbove(rosterTasks.length, 1); - for (const task of rosterTasks.slice(1)) { + for (const { runId, ...task } of rosterTasks.slice(1)) { + // Adapter rosters carry no run; server rewrites of the stored thread carry the projection's stamp. + if (runId !== undefined) assert.equal(runId, monitorItem?.runId); assert.deepEqual(task, { taskId: MONITOR_TASK_ID, description: "Background monitor test", diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 97a2e97e78fad..9c62ddb1a2b84 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -225,6 +225,24 @@ function makeRecordLimitTranscript(cwd: string, overflow: boolean): string { : records; } +// Pi retains every entry, keeping tool results as links outside the history budget. +function makePiToolResultTranscript(sessionId: string, cwd: string, recordCount: number): string { + const entry = (id: number, message: { readonly role: string; readonly content: string }) => + encodeTranscriptRecord({ + type: "message", + id: `e${id}`, + parentId: id === 0 ? null : `e${id - 1}`, + message, + }); + return [ + encodeTranscriptRecord({ type: "session", version: 3, id: sessionId, cwd }), + entry(0, { role: "user", content: "Imported prompt" }), + ...Array.from({ length: recordCount - 2 }, (_, index) => + entry(index + 1, { role: "toolResult", content: "Tool output" }), + ), + ].join("\n"); +} + const makeFileIdentityFixture = Effect.fn("AgentSessionScanner.test.makeFileIdentityFixture")( function* (originalInode = 10_000_000_000_000_001n, replacementInode = 10_000_000_000_000_000n) { const path = yield* Path.Path; @@ -2282,22 +2300,20 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const claudeHomePath = yield* makeTempDir("t3code-record-budget-claude-"); const codexHomePath = yield* makeTempDir("t3code-record-budget-codex-"); const workspace = yield* makeTempDir("t3code-record-budget-workspace-"); - const exactLimit = makeRecordLimitTranscript(workspace, false); - // The newer transcript has 100,001 records; the older one has exactly 100,000. - for (const [sessionId, contents, mtimeMs] of [ - ["excessive", exactLimit.replace("record-limit-session", "excessive") + "{}\n", nowMs], - ["older", exactLimit, nowMs - 1_000], + // The newer transcript retains 100,001 records; the older one exactly 100,000. + for (const [sessionId, recordCount, mtimeMs] of [ + ["excessive", 100_001, nowMs], + ["older", 100_000, nowMs - 1_000], ] as const) { yield* writeTranscript({ filePath: path.join( - codexHomePath, + claudeHomePath, + "pi-agent", "sessions", - "2026", - "08", - "24", - `rollout-${sessionId}.jsonl`, + "--workspace--", + `${sessionId}.jsonl`, ), - contents, + contents: makePiToolResultTranscript(sessionId, workspace, recordCount), mtimeMs, }); } @@ -2307,9 +2323,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { workspaceRoot: workspace, }); expect(outcomes.map((outcome) => outcome._tag)).toEqual(["Skipped", "Importable"]); - expect(outcomes[1]).toMatchObject({ - thread: { providerSessionId: "record-limit-session" }, - }); + expect(outcomes[1]).toMatchObject({ thread: { providerSessionId: "older" } }); }), ); @@ -2326,26 +2340,13 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { for (const [index, recordCount] of recordCounts.entries()) { yield* writeTranscript({ filePath: path.join( - codexHomePath, + claudeHomePath, + "pi-agent", "sessions", - "2026", - "08", - "24", - `rollout-${index}.jsonl`, + "--workspace--", + `${index}.jsonl`, ), - contents: - [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: `session-${index}`, cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Imported prompt" }, - }), - ].join("\n") + - "\n" + - "{}\n".repeat(recordCount - 2), + contents: makePiToolResultTranscript(`session-${index}`, workspace, recordCount), mtimeMs: nowMs - index * 1_000, }); } diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index c1f42586b2f33..1e300d1fe0410 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1242,7 +1242,6 @@ export const make = Effect.gen(function* () { let claudeFields = emptyClaudeFields; let historyBytes = prefix?.historyBytes ?? 0; let recordBytes = 0; - let recordCount = 0; let bytesRead = 0; const reserve = (bytes: number) => { recordBytes += bytes; @@ -1258,9 +1257,6 @@ export const make = Effect.gen(function* () { const finishRecord = () => { reader.write(decoder.decode()); - recordCount += 1; - // Claude keeps a bounded window, so only the byte budgets limit its length. - if (recordCount > MAX_IMPORT_RECORDS && source !== "claudeAgent") return false; const value = reader.finish(); const decoded = decodeTranscriptValue(value); if (Option.isNone(decoded) && source === "pi") { @@ -1292,7 +1288,7 @@ export const make = Effect.gen(function* () { reader = createTranscriptJsonReader(reserve, selectTranscriptPath); decoder = new TextDecoder(); recordStarted = false; - return true; + return records.length <= MAX_IMPORT_RECORDS; }; while (bytesRead < readBytes) { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47c4a4c9a20ec..01b659b0944ad 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -219,7 +219,7 @@ import * as RunFinalizationService from "./orchestration-v2/RunFinalizationServi import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts"; import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts"; -import { acceptsPrivateNetworkConnection, loopbackUrlHostForAddress } from "./startupAccess.ts"; +import { closeNonPrivateNetworkConnections, loopbackUrlHostForAddress } from "./startupAccess.ts"; import * as OrchestrationHttp from "./orchestration-v2/http.ts"; import * as ProjectHttp from "./project/http.ts"; import * as NetService from "@t3tools/shared/Net"; @@ -364,17 +364,14 @@ const layerHttpServer = Layer.unwrap( privateNetworkOnly: config.privateNetworkOnly, }); yield* ManagedLimits.closeTailscaleServeTo(policy, { host: bindHost, port: config.port }); + const runSync = Effect.runSyncWith(yield* Effect.context()); return NodeHttpServer.layer( () => { const server = rejectRequestsUntilServing( keepIdleConnections(guardHttpResponseWriteErrors(NodeHttp.createServer())), ); if (config.privateNetworkOnly) { - server.on("connection", (socket) => { - if (!acceptsPrivateNetworkConnection(socket)) { - socket.destroy(); - } - }); + runSync(closeNonPrivateNetworkConnections(server)); } return server; }, diff --git a/apps/server/src/speech/SpeechService.ts b/apps/server/src/speech/SpeechService.ts index b4ae198b9447d..58fc6a9e1f5d5 100644 --- a/apps/server/src/speech/SpeechService.ts +++ b/apps/server/src/speech/SpeechService.ts @@ -582,8 +582,9 @@ const make = Effect.gen(function* () { const silenceModelPath = Effect.fn("SpeechService.silenceModelPath")(function* ( loaded: LoadedModel, options: SpeechTranscriptionOptions, + nativeStreaming: boolean, ) { - if (!options.speechSilenceFiltering && (loaded.supportsStreaming || loaded.supportsLongForm)) + if (!options.speechSilenceFiltering && (nativeStreaming || loaded.supportsLongForm)) return undefined; return yield* acquireSilenceModel("recording"); }); @@ -619,7 +620,7 @@ const make = Effect.gen(function* () { ), catch: (cause) => speechError("model preparation", cause), }); - const vadPath = yield* silenceModelPath(loaded, options); + const vadPath = yield* silenceModelPath(loaded, options, false); const dictionary = normalizeSpeechCustomWords(options.speechCustomWords); const customWords = dictionary.map(({ term }) => term); // The vocabulary capability guarantees plain transcription, not translation. @@ -755,7 +756,7 @@ const make = Effect.gen(function* () { loadModel(modelPath, definition, signal, settings.speechAcceleration), ); loaded = streamModel; - const vadPath = yield* silenceModelPath(streamModel, options); + const vadPath = yield* silenceModelPath(streamModel, options, streamModel.supportsStreaming); let translateToEnglish = false; const beginStream = async () => { translateToEnglish = diff --git a/apps/server/src/speech/native.test.ts b/apps/server/src/speech/native.test.ts index a41f917b2a682..cb7254891a51b 100644 --- a/apps/server/src/speech/native.test.ts +++ b/apps/server/src/speech/native.test.ts @@ -299,6 +299,28 @@ it("decodes complete stable chunks before Stop and returns the ordered final tai } }); +it("uses bounded offline chunks for a native streaming model without opening a session", async () => { + const moduleUrl = `data:text/javascript,${encodeURIComponent(` + export const TranscribeModel = { load: async () => ({ + capabilities: { supportsStreaming: true, maxAudioMs: 4000 }, + supports: () => false, + createSession: () => { throw new Error("Offline inference must not open a stream"); }, + transcribe: async pcm => { + if (pcm.length > 32000) throw new Error("Model input limit exceeded"); + return { text: String(pcm.length) }; + }, + }) }; + `)}`; + const model = await loadNativeSpeechModel("asr.gguf", new AbortController().signal, moduleUrl); + try { + expect( + await model.transcribe(new Float32Array(48002).fill(0.8), { timestamps: "none" }, false), + ).toEqual({ text: "32000 16002" }); + } finally { + await model.dispose(); + } +}); + it("preserves withheld audio on VAD failure while keeping ASR failures distinct", async () => { for (const streaming of [false, true]) { const model = await loadNativeSpeechModel( diff --git a/apps/server/src/speech/native.ts b/apps/server/src/speech/native.ts index 70c5d21c6038d..2bd2631c63fba 100644 --- a/apps/server/src/speech/native.ts +++ b/apps/server/src/speech/native.ts @@ -28,7 +28,7 @@ const resetAsr = () => { stream = session = undefined; }; const newAudio = (filterSilence) => createSpeechAudio({ - frameSamples: 512, filterSilence, nativeStreaming: model.capabilities.supportsStreaming, + frameSamples: 512, filterSilence, nativeStreaming, longForm: model.supports("long_form"), maxAudioMs: model.capabilities.maxAudioMs, }); const openAsr = async () => { @@ -45,7 +45,7 @@ const begin = async (message, live) => { scored = revision = 0; heardAudio = false; useVad = Boolean(message.vadPath) && (message.filterSilence || - (!model.capabilities.supportsStreaming && !model.supports("long_form"))); + (!nativeStreaming && !model.supports("long_form"))); if (useVad) { try { if (!vadModel) { diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 159778b3c7e03..7290d6063db9b 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -1,10 +1,17 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeHttp from "node:http"; +import * as NodeNet from "node:net"; import type * as NodeOS from "node:os"; import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Logger from "effect/Logger"; import * as NetAddress from "effect/net/NetAddress"; +import * as TestClock from "effect/testing/TestClock"; import { acceptsPrivateNetworkConnection, + closeNonPrivateNetworkConnections, loopbackUrlHostForAddress, resolveHeadlessConnectionString, } from "./startupAccess.ts"; @@ -104,3 +111,51 @@ describe("acceptsPrivateNetworkConnection", () => { expect(accepts(undefined, "192.168.1.31")).toBe(false); }); }); + +describe("closeNonPrivateNetworkConnections", () => { + it.effect("logs the local and remote address of a connection it closes", () => + Effect.gen(function* () { + const warnings: Array> = []; + const server = NodeHttp.createServer(); + yield* closeNonPrivateNetworkConnections(server).pipe( + Effect.provide( + Logger.layer([Logger.make((entry) => warnings.push(entry))], { + mergeWithExisting: false, + }), + ), + ); + + // An unconnected socket: Node reports neither address. + const socket = new NodeNet.Socket(); + server.emit("connection", socket); + + expect(socket.destroyed).toBe(true); + expect(warnings.map((entry) => entry.logLevel)).toEqual(["Warn"]); + const line = Logger.formatLogFmt.log(warnings[0]!); + expect(line).toMatch(/localAddress\W+undefined/); + expect(line).toMatch(/remoteAddress\W+undefined/); + }), + ); + + it.effect("logs a flood of closed connections at most once a minute, with a count", () => + Effect.gen(function* () { + const warnings: Array> = []; + const server = NodeHttp.createServer(); + yield* closeNonPrivateNetworkConnections(server).pipe( + Effect.provide( + Logger.layer([Logger.make((entry) => warnings.push(entry))], { + mergeWithExisting: false, + }), + ), + ); + const sockets = Array.from({ length: 1000 }, () => new NodeNet.Socket()); + for (const socket of sockets) server.emit("connection", socket); + yield* TestClock.adjust("1 minute"); + server.emit("connection", new NodeNet.Socket()); + + expect(sockets.every((socket) => socket.destroyed)).toBe(true); + expect(warnings).toHaveLength(2); + expect(Logger.formatLogFmt.log(warnings[1]!)).toMatch(/closedSinceLastLog\W+999/); + }), + ); +}); diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index 1720300bd7beb..ee372a1ab1514 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - The private-network gate guards the node:http server. +import type * as NodeHttp from "node:http"; import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; @@ -10,6 +12,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import { QrCode } from "@t3tools/shared/qrCode"; import { buildPairingAppLink } from "@t3tools/shared/remote"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import { HttpServer } from "effect/http"; import * as NetAddress from "effect/net/NetAddress"; @@ -81,6 +84,44 @@ export const acceptsPrivateNetworkConnection = (socket: { (address) => address !== undefined && isPrivateNetworkAddress(address), ); +const CLOSED_CONNECTION_LOG_INTERVAL_NANOS = 60_000_000_000n; + +/** + * Closing is silent to the client, so closed connections are logged with both + * addresses: the first at once, then at most one line a minute with a count, so + * a connect flood from outside cannot grow the service log without bound. + */ +// Untraced: the captured context would otherwise tie every later warning to a span that ended at startup. +export const closeNonPrivateNetworkConnections = Effect.fnUntraced(function* ( + server: NodeHttp.Server, +) { + const runSync = Effect.runSyncWith(yield* Effect.context()); + let nextLogAt: bigint | undefined; + let closedSinceLastLog = 0; + server.on("connection", (socket) => { + if (acceptsPrivateNetworkConnection(socket)) return; + // Read before destroy: Node forgets localAddress once the handle closes. + const addresses = { localAddress: socket.localAddress, remoteAddress: socket.remoteAddress }; + socket.destroy(); + runSync( + Effect.gen(function* () { + // Monotonic: a wall clock set backwards must not silence the warnings. + const now = yield* Clock.monotonicTimeNanos; + if (nextLogAt !== undefined && now < nextLogAt) { + closedSinceLastLog += 1; + return; + } + nextLogAt = now + CLOSED_CONNECTION_LOG_INTERVAL_NANOS; + yield* Effect.logWarning("closed a connection outside the private network", { + ...addresses, + ...(closedSinceLastLog > 0 ? { closedSinceLastLog } : {}), + }); + closedSinceLastLog = 0; + }), + ); + }); +}); + export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string => NetAddress.isUnspecified(address.address) ? "127.0.0.1" diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index bc22117ba74ab..f00017e4001ec 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -258,6 +258,32 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); + it.effect("reports an optional file as absent when the workspace root was removed", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const path = yield* Path.Path; + const cwd = path.join(yield* makeTempDir, "removed-worktree"); + + const result = yield* workspaceFileSystem.readFile({ + cwd, + relativePath: "t3.json", + allowMissing: true, + }); + expect(result).toEqual({ + relativePath: "t3.json", + contents: "", + byteLength: 0, + truncated: false, + exists: false, + }); + + const error = yield* workspaceFileSystem + .readFile({ cwd, relativePath: "t3.json" }) + .pipe(Effect.flip); + expect(error).toMatchObject({ operation: "realpath-workspace-root" }); + }), + ); + it.effect("finishes short reads before decoding UTF-8 text", () => Effect.gen(function* () { const files = yield* WorkspaceFileSystem.WorkspaceFileSystem; diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index 494472e4ce68d..98047345d4ff6 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -315,7 +315,17 @@ export const make = Effect.gen(function* () { operation: "realpath-workspace-root", cause, }), - }); + }).pipe( + // Storage cleanup removes idle worktrees but keeps their path, so nothing below them exists. + Effect.catchIf( + (error) => + input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT", + () => Effect.succeed(null), + ), + ); + if (realWorkspaceRoot === null) { + return { relativePath: target.relativePath, realTargetPath: null }; + } const resolved = yield* Effect.tryPromise({ try: async () => { let candidate = target.absolutePath; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8e8b30bab3270..6defac543eaac 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3031,6 +3031,7 @@ export const layerWsRpc = ( if ( input.resource._tag === "attachment" || input.resource._tag === "native-app-icon" || + input.resource._tag === "environment-theme-background" || input.resource._tag === "tool-output-image" || input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET || // A network path is served only from the thread's project, looked up below. diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index faa71137db049..d1873481ee510 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -37,6 +37,7 @@ import { } from "./composerDraftStore"; import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme"; import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme"; +import { startThemeBackground } from "./themeBackground"; import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage"; import { startHostEnvironmentLookup } from "./state/primaryEnvironment"; import { @@ -264,6 +265,7 @@ export function startAppServices(): AppRouter { startDocumentTitle(router); startHostEnvironmentLookup(); startEnvironmentThemeRepaint(); + startThemeBackground(); startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); startModelPreferencesMigration(); diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.ts index f7f53ca2c3e4f..ec9cf15bb7e42 100644 --- a/apps/web/src/cloud/publicConfig.ts +++ b/apps/web/src/cloud/publicConfig.ts @@ -61,9 +61,18 @@ export function resolveCloudPublicConfig(): CloudPublicConfig { }; } +let desktopRelayTelemetry: boolean | null = null; + +/** Whether relay spans may be exported now; the desktop host may not know yet at startup. */ +export function relayTelemetryEnabled(): boolean | null { + if (typeof window === "undefined" || !window.desktopBridge) return true; + desktopRelayTelemetry ??= window.desktopBridge.getRelayTelemetryEnabled(); + return desktopRelayTelemetry; +} + export function resolveRelayTracingConfig() { // The relay exporter is created during module initialization, so this must be synchronous. - if (typeof window !== "undefined" && window.desktopBridge?.getRelayTelemetryEnabled() === false) { + if (relayTelemetryEnabled() === false) { return null; } const { relayTracing } = resolveCloudPublicConfig(); diff --git a/apps/web/src/components/AppRouteModal.browser.test.tsx b/apps/web/src/components/AppRouteModal.browser.test.tsx index 004e07744e22e..c0864d31c178f 100644 --- a/apps/web/src/components/AppRouteModal.browser.test.tsx +++ b/apps/web/src/components/AppRouteModal.browser.test.tsx @@ -5,6 +5,8 @@ import { render } from "../../test/render"; import { useCommitOnBlur } from "../hooks/useCommitOnBlur"; import { AppRouteModal } from "./AppRouteModal"; +vi.mock("./chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null })); + function CommitOnBlurField({ onCommit }: { onCommit: (next: string) => void }) { return ; } diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 0c8a8a670d2f6..f4cde43a8cccc 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -4,6 +4,7 @@ import { useRef, useState, type CSSProperties, type ReactNode } from "react"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; import { useCloseAppModal } from "./sidebar/mainAppLocation"; +import { GlobalVoiceInputIndicator } from "./chat/GlobalVoiceInputIndicator"; import { Button } from "./ui/button"; import { DialogBackdrop } from "./ui/dialog"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; @@ -89,6 +90,7 @@ export function AppRouteModal({ label, children }: { label: string; children: Re className="absolute inset-x-0 top-0 hidden h-(--app-modal-titlebar-height) [-webkit-app-region:drag] max-sm:block" /> {children} + diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx index 324c2c839ccd9..a072ecc107e26 100644 --- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx @@ -308,6 +308,7 @@ it("preserves keyboard activation of a file-options button", async () => { copyMarkdown="[Readme](readme.md)" theme="dark" onOpenInPanel={vi.fn()} + resolveDragPath={async () => "/work/readme.md"} resolveCopyPaths={async () => ({ relativePath: "readme.md", fullPath: "/work/readme.md" })} openInEditorMenuLabel="Open in editor" />, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index b48485fc61212..455f18304ab20 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1,3 +1,4 @@ +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment"; import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks"; import { @@ -941,6 +942,9 @@ function useChatMarkdownState({ ) : undefined } + resolveDragPath={async () => + resolvePathLinkTarget((await resolveHostPath()).absolutePath, cwd ?? "") + } resolveCopyPaths={async () => markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd) } diff --git a/apps/web/src/components/ChatView.logic.browser.test.ts b/apps/web/src/components/ChatView.logic.browser.test.ts index 880a640cc6e20..724c77538d315 100644 --- a/apps/web/src/components/ChatView.logic.browser.test.ts +++ b/apps/web/src/components/ChatView.logic.browser.test.ts @@ -21,11 +21,33 @@ it("keeps keyboard focus on a sidebar row on window return, but not a clicked ro await userEvent.click(clicked); expect(document.activeElement).toBe(clicked); - expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(true); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection())).toBe( + true, + ); await userEvent.tab(); expect(document.activeElement).toBe(tabbed); - expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection())).toBe( + false, + ); +}); + +it("leaves a text selection in the timeline alone on window return", async () => { + const timeline = document.createElement("div"); + timeline.tabIndex = -1; + const reply = document.createElement("p"); + reply.textContent = "Steel bridges are also easy to recycle at the end of their life."; + timeline.append(reply); + document.body.append(timeline); + using _timeline = { [Symbol.dispose]: () => timeline.remove() }; + + await userEvent.tripleClick(reply); + expect(document.activeElement).toBe(timeline); + expect(document.getSelection()?.toString()).toContain("Steel bridges"); + expect( + shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection()), + "refocusing the composer would clear the selected reply text", + ).toBe(false); }); it("keeps focus in a region with its own keys on window return", async () => { @@ -38,7 +60,9 @@ it("keeps focus in a region with its own keys on window return", async () => { await userEvent.click(region); expect(document.activeElement).toBe(region); - expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection())).toBe( + false, + ); }); it("refocuses the composer on window return from a clicked area after a bare key press", async () => { @@ -61,7 +85,7 @@ it("refocuses the composer on window return from a clicked area after a bare key // A window switch can deliver a lone modifier key without moving focus. await userEvent.keyboard("{Shift}"); expect( - shouldRefocusComposerOnWindowFocus(document.activeElement), + shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection()), "a clicked area counts as reached from the keyboard after a bare key press", ).toBe(true); @@ -70,5 +94,7 @@ it("refocuses the composer on window return from a clicked area after a bare key await userEvent.keyboard("{F6}"); controller.move(1); expect(document.activeElement).toBe(conversation); - expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection())).toBe( + false, + ); }); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index e528246e7aea1..cc9e43b847dfd 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1096,15 +1096,17 @@ export function hasServerAcknowledgedLocalDispatch(input: { ); } -// Window return puts the caret in the composer unless focus is deliberate: another text field, -// a terminal, an open dialog, menu, or popup, a region, timeline, or sidebar row reached from the -// keyboard, or a region with its own keys (aria-keyshortcuts). A plain focused button or a clicked -// row yields to the composer. +// Window return puts the caret in the composer unless focus or a selection is deliberate: another +// text field, a terminal, an open dialog, menu, or popup, a region, timeline, or sidebar row reached +// from the keyboard, a region with its own keys (aria-keyshortcuts), or selected text the composer +// would clear. A plain focused button or a clicked row yields to the composer. export function shouldRefocusComposerOnWindowFocus( activeElement: | (Pick & { isContentEditable?: boolean }) | null, + selection: Pick | null, ): boolean { + if (selection !== null && !selection.isCollapsed) return false; if (activeElement === null || activeElement.tagName === "BODY") return true; if ( activeElement.tagName === "INPUT" || diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b1bbfc5c56fa6..e4ee6ec455122 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2208,7 +2208,7 @@ export default function ChatView(props: ChatViewProps) { if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return; if ( !isInSideChatPane(document.activeElement) && - shouldRefocusComposerOnWindowFocus(document.activeElement) + shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection()) ) { focusComposerStable(); } diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 692a135ad883b..58e9a29b57c1d 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -7,7 +7,17 @@ import { useRetainedContextPayloads, } from "./chat/composerContextUndo"; -import type { ServerProviderSkill } from "@t3tools/contracts"; +import { + ComposerContextId, + type ComposerContextRecord, + EnvironmentId, + type ServerProviderSkill, +} from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; import type { Editor } from "@tiptap/core"; import { redoDepth, undoDepth } from "@tiptap/pm/history"; import { NodeSelection } from "@tiptap/pm/state"; @@ -54,12 +64,16 @@ function Composer({ skills, onChange, onCommandKeyDown = () => false, + importContextFragment, + literalText = false, }: { value: string; richTextEnabled: boolean; skills: ReadonlyArray; onChange?: ComposerPromptEditorProps["onChange"] | undefined; onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"] | undefined; + importContextFragment?: ComposerPromptEditorProps["importContextFragment"]; + literalText?: boolean; }) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); return ( @@ -78,6 +92,8 @@ function Composer({ }} onPaste={() => {}} onCommandKeyDown={onCommandKeyDown} + importContextFragment={importContextFragment} + literalText={literalText} /> ); } @@ -482,6 +498,55 @@ it.each([ expect(serializeEditorDoc(editor.state.doc).value).toBe(pasted); }); +it.each([ + { literalText: false, imports: 1 }, + { literalText: true, imports: 0 }, +])( + "imports a copied snapshot's context over its image file: %o", + async ({ literalText, imports }) => { + const record = { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "shot.png", + attachmentId: "snapshot", + name: "shot.png", + mimeType: "image/png", + sizeBytes: 3, + } satisfies ComposerContextRecord; + const importContextFragment = vi.fn(() => new Map([[record.contextId, record.contextId]])); + await using screen = await render( + , + ); + const editor = editorIn(screen.container); + await act(async () => { + const clipboardData = new DataTransfer(); + clipboardData.items.add( + new File([new Uint8Array([1, 2, 3])], "shot.png", { type: "image/png" }), + ); + clipboardData.setData("text/plain", formatComposerContextReference(record)); + clipboardData.setData( + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [record], + })!, + ); + editor.view.dom.dispatchEvent( + new ClipboardEvent("paste", { clipboardData, cancelable: true }), + ); + }); + expect(importContextFragment).toHaveBeenCalledTimes(imports); + }, +); + it.each(["x\r\n\r\ny", "x\r\ry"])( "pastes %j with the same blank line as x\\n\\ny", async (text) => { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index d89f57068e9cf..59d37fbe8c788 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1,3 +1,5 @@ +import { useNativeFileDrag } from "../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { useAtomValue } from "@effect/atom-react"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills"; @@ -136,7 +138,11 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView"; import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal"; import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight"; -import { importPastedComposerText, readPastedPlainText } from "./composerInlineTokenPaste"; +import { + importPastedComposerText, + readPastedComposerContext, + readPastedPlainText, +} from "./composerInlineTokenPaste"; import { didComposerSelectionChangeVisibly } from "./composerSelection"; import { captureComposerAttachmentInsertion, @@ -281,8 +287,12 @@ const ComposerMentionExtension = Node.create({ function ComposerMentionNodeView({ node }: NodeViewProps) { const actions = use(ComposerContextActionsContext); const path = (node.attrs.path as string) ?? ""; + const nativeDrag = useNativeFileDrag(actions.environmentId, () => + resolvePathLinkTarget(path, actions.cwd ?? ""), + ); const chip = ( } @@ -1398,7 +1408,12 @@ function ComposerPromptEditorTiptapInner( }, handlePaste: (view, event) => { const clipboardData = event.clipboardData; - if (!clipboardData || clipboardData.files.length > 0) return false; + if (!clipboardData) return false; + if ( + clipboardData.files.length > 0 && + (literalText || !readPastedComposerContext(clipboardData)?.records.length) + ) + return false; const pastedText = readPastedPlainText(clipboardData); if (!pastedText) return false; event.preventDefault(); diff --git a/apps/web/src/components/ContextChip.tsx b/apps/web/src/components/ContextChip.tsx index 13a19167fe929..dabe1f4844532 100644 --- a/apps/web/src/components/ContextChip.tsx +++ b/apps/web/src/components/ContextChip.tsx @@ -6,7 +6,7 @@ import type * as React from "react"; import { cn } from "~/lib/utils"; const contextChipVariants = cva( - "inline-flex max-w-full items-center gap-[0.2em] font-medium leading-[normal] text-(--context-chip-ink) [--context-chip-ink:var(--context-chip-accent)] [--document-icon-stroke:var(--context-chip-ink)] [&_svg]:block [&_svg]:size-[1em] [&_svg]:shrink-0 [&_svg]:self-center [button&,a&,[data-popup-open]&]:cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-current rounded-sm disabled:cursor-default", + "inline-flex max-w-full items-center gap-[0.2em] font-medium leading-[normal] text-(--context-chip-ink) [--context-chip-ink:var(--context-chip-message-ink,var(--context-chip-accent))] [--document-icon-stroke:var(--context-chip-ink)] [&_svg]:block [&_svg]:size-[1em] [&_svg]:shrink-0 [&_svg]:self-center [button&,a&,[data-popup-open]&]:cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-current rounded-sm disabled:cursor-default", { defaultVariants: { kind: "neutral" }, variants: { @@ -30,7 +30,9 @@ const contextChipVariants = cva( thread: "[--context-chip-accent:var(--context-chip-thread)]", environment: "[--context-chip-accent:var(--context-chip-environment)]", citation: "[--context-chip-accent:var(--context-chip-citation)]", - "doc-pdf": "[--context-chip-accent:var(--context-chip-doc-pdf)]", + // PDF red reads as the invalid state, so only the icon carries it. + "doc-pdf": + "[--context-chip-accent:var(--context-chip-doc-pdf)] [--context-chip-ink:var(--context-chip-message-ink,currentColor)] [--document-icon-stroke:var(--context-chip-message-ink,var(--context-chip-accent))]", "doc-word": "[--context-chip-accent:var(--context-chip-doc-word)]", "doc-spreadsheet": "[--context-chip-accent:var(--context-chip-doc-spreadsheet)]", "doc-slides": "[--context-chip-accent:var(--context-chip-doc-slides)]", @@ -43,7 +45,7 @@ const contextChipVariants = cva( state: { unresolved: "data-[state=unresolved]:[--context-chip-accent:currentColor]", invalid: - "data-[state=invalid]:[--context-chip-accent:var(--context-chip-invalid,var(--destructive-foreground))]", + "data-[state=invalid]:[--context-chip-accent:var(--context-chip-invalid,var(--destructive-foreground))] data-[state=invalid]:[--context-chip-ink:var(--context-chip-message-ink,var(--context-chip-accent))]", }, }, }, 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.tsx b/apps/web/src/components/Sidebar.tsx index 3cb77464473b4..e6cdb90d5c86d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -55,6 +55,7 @@ import { } from "@t3tools/client-runtime/environment"; import { AuthOrchestrationOperateScope, + type ContextMenuSource, ProjectId, type ScopedThreadRef, type ThreadId, @@ -1250,7 +1251,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve void handleNewThread(scopeProjectRef(group.environmentId, group.id)); }); const handleProjectFolderContextMenu = useStableCallback( - (group: SidebarProjectSnapshot, position: { x: number; y: number }) => { + ( + group: SidebarProjectSnapshot, + position: { x: number; y: number }, + source: ContextMenuSource, + ) => { const api = readLocalApi(); if (!api) return; void (async () => { @@ -1269,6 +1274,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve { id: "project-settings", label: "Project settings", icon: "settings" }, ], position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2283,7 +2289,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleMultiSelectContextMenu = useStableCallback( - async (position: { x: number; y: number }) => { + async (position: { x: number; y: number }, source: ContextMenuSource) => { const api = readLocalApi(); if (!api) return; const selectedThreadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; @@ -2381,6 +2387,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, ], position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; @@ -2534,7 +2541,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleDraftContextMenu = useStableCallback( - (draftId: DraftId, position: { x: number; y: number }) => { + (draftId: DraftId, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); const session = useComposerDraftStore.getState().getDraftSession(draftId); @@ -2556,6 +2563,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve hasProject: projectGroup != null, }), position, + source, ), ); if (clicked._tag === "Failure") return; @@ -2585,14 +2593,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const handleThreadContextMenu = useStableCallback( - (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { + (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) => { void (async () => { const api = readLocalApi(); if (!api) return; const threadKey = scopedThreadKey(threadRef); const selectionState = useThreadSelectionStore.getState(); if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { - await handleMultiSelectContextMenu(position); + await handleMultiSelectContextMenu(position, source); return; } const thread = threadByKeyRef.current.get(threadKey); @@ -2659,6 +2667,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve snoozePresets, }), position, + source, ), ); if (clicked._tag === "Failure" || clicked.value === null) return; diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index a7b7da0a6b53b..5217b068f9a35 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -8,7 +8,7 @@ import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; -import { BackgroundThreadContext } from "./chat/backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -229,7 +229,9 @@ export function ThreadRouteView({ className="h-svh min-h-0 overflow-hidden overscroll-y-none md:h-dvh" inert={background} > - {view} + + {view} + {background ? null : redirect} ); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index be3144efb40b9..69250e47b89c3 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,9 +1,10 @@ +import { copySnapshot } from "./copySnapshot"; import { VoiceInputSetup } from "./VoiceInputSetup"; import { useComposerTypingGuard } from "./useComposerTypingGuard"; import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion"; import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; -import { BackgroundThreadContext } from "./backgroundThread"; +import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; import { resolveCompatibleRuntimeMode, runtimeModeConfig, @@ -106,9 +107,12 @@ import { composerFileNeedsReattach, composerDraftHasUserContent, composerTargetKey, + readComposerDraftPrompt, + resolveLiveComposerDraftTarget, useComposerDraftStore, useComposerThreadDraft, } from "../../composerDraftStore"; +import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../../threadRoutes"; import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; import { useComposerTriggerState } from "./useComposerTriggerState"; @@ -148,6 +152,7 @@ import { type TerminalContextSelection, } from "../../lib/terminalContext"; import { + formatComposerContextReference, threadContextRecord, toKindScopedComposerContextId, } from "@t3tools/shared/composerContextReferences"; @@ -717,7 +722,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview(composerImages, imageId); + const preview = buildExpandedImagePreview( + composerImages, + imageId, + copyComposerSnapshotStable, + ); if (preview) onExpandImage(preview); }, openFile: setPreviewFileId, @@ -1046,6 +1055,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. @@ -1334,7 +1344,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; @@ -1346,6 +1360,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, @@ -1823,6 +1850,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 { @@ -2416,6 +2466,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) allImages={composerImages} resolvedTheme={resolvedTheme} onExpandImage={onExpandImage} + onCopySnapshot={copyComposerSnapshotStable} onShowMore={expandMobileComposer} /> ) : null; @@ -2760,9 +2811,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 })) ) { @@ -2775,7 +2830,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; } @@ -3315,6 +3370,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentId={environmentId} attachmentDraftTarget={attachmentDraftTarget} canOperateThread={canOperateThread} + onCopySnapshot={copyComposerSnapshotStable} onExpandImage={onExpandImage} onFileOpen={onFileOpen} onRemoveImage={removeComposerImage} @@ -3799,6 +3855,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/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/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 448e6f90a8ed0..2606ae7b898db 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -2083,7 +2083,7 @@ it("renders automatic compaction as one live divider that finishes with its reas await expect .element( screen.getByRole("separator", { - name: "Context automatically compacted before cache expiry 899K → 19K tokens", + name: "Auto-compacted before cache expiry 899K → 19K tokens", }), ) .toBeVisible(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 1cd8066dbcd32..f834c7cc355b9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -686,7 +686,7 @@ describe("deriveMessagesTimelineRows", () => { active: true, label: "Compacting before the cache expires…", }, - "Context automatically compacted before cache expiry", + "Auto-compacted before cache expiry", ], ["onReturn", { kind: "working", compacting: true }, "Context compacted before sending"], [undefined, { kind: "context-compaction", active: true }, undefined], diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index e9a884fde6a17..87bacfd7ca2a2 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -548,13 +548,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { const flatModels = (() => { const out: ModelPickerItem[] = []; + const seenKeys = new Set(); for (const [instanceId, models] of modelOptionsByInstance) { const entry = entryByInstanceId.get(instanceId); if (!entry) { continue; } for (const model of models) { + const key = modelPickerModelKey(instanceId, model.slug); if ( + seenKeys.has(key) || !shouldIncludeModelPickerOption({ entry, option: model, @@ -564,6 +567,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ) { continue; } + seenKeys.add(key); out.push({ slug: model.slug, name: model.name, diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index da9d7d50a5396..cc246a1f9967c 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -232,7 +232,7 @@ describe("open in editor announcement", () => { using _timers = fakeTimers(); const regions = () => [...document.querySelectorAll('body > [aria-live="polite"]')]; const spoken = async () => { - await act(async () => vi.runAllTimers()); + await act(async () => vi.advanceTimersByTime(250)); return regions() .map((region) => region.textContent) .join(""); diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx index bf196f52542c2..06bb36a34c07f 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.test.tsx @@ -4,6 +4,7 @@ import { ProviderInstanceId, type ModelSelection, } from "@t3tools/contracts"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -176,6 +177,73 @@ it("keeps a docked picker open after a pick and hands focus to that model's effo await expect.element(search).not.toBeInTheDocument(); }); +it("lists a model reported twice by one provider once, with contiguous jump shortcuts", async () => { + const instanceId = ProviderInstanceId.make("claude"); + const entries = deriveProviderInstanceEntries([ + { + instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }, + ]); + const options = new Map([ + [ + instanceId, + ["a", "b", "c", "c", "d", "d"].map((slug) => ({ + slug, + name: `Model ${slug.toUpperCase()}`, + })), + ], + ]); + const keybindings = compileResolvedKeybindingsConfig( + ([1, 2, 3, 4, 5, 6] as const).map((index) => ({ + key: `mod+${index}`, + command: `modelPicker.jump.${index}` as const, + when: "modelPickerOpen", + })), + ); + + await using screen = await render( + {}} + />, + ); + await screen.getByRole("button", { name: "Choose model" }).click(); + await expect.element(page.getByRole("option", { name: /Model A/ })).toBeVisible(); + await vi.waitFor(() => + expect( + page + .getByRole("option") + .elements() + .map((row) => [ + row.textContent?.match(/Model [A-Z]/)?.[0], + row.querySelector("kbd")?.textContent?.slice(-1), + ]), + ).toEqual([ + ["Model A", "1"], + ["Model B", "2"], + ["Model C", "3"], + ["Model D", "4"], + ]), + ); +}); + it("opens on the active provider when every favorite belongs to a disabled provider", async () => { const entries = deriveProviderInstanceEntries( ["Codex", "Claude"].map((name) => ({ diff --git a/apps/web/src/components/chat/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/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 3fee2134c3f58..7cd57ed18c0c1 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,3 +1,4 @@ +import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; import { @@ -102,7 +103,7 @@ const MEDIA_EDGE_CLASS_NAME = "relative after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:ring-1 after:ring-inset after:ring-black/9 dark:after:ring-white/12"; const BUBBLE_CHIP_CLASS_NAME = - "[&_[data-slot=context-chip]]:[--context-chip-ink:var(--context-chip-message,var(--context-chip-accent))]"; + "[&_[data-slot=context-chip]]:[--context-chip-message-ink:var(--context-chip-message)]"; function UserFileCard({ file, @@ -597,6 +598,25 @@ function UserTimelineRow({ row }: { row: Extract { + const image = userImages.find((candidate) => candidate.id === id); + const record = resolvedContext.records + .map(asKnownContextRecord) + .find((candidate) => candidate?.kind === "image" && candidate.attachmentId === id); + if (!image?.previewUrl || record?.kind !== "image") + throw new Error("Snapshot is no longer available."); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ctx.activeThreadEnvironmentId, messageId: row.message.id }, + records: [{ ...record, ...(image.source ? { source: image.source } : {}) }], + }); + if (!fragment) throw new Error("The snapshot is too large to copy."); + await copySnapshotToClipboard( + image.previewUrl, + formatComposerContextReference(record), + fragment, + ); + }; const onBodyCopyCapture = (event: React.ClipboardEvent) => { if (resolvedContext.records.length === 0 || !event.clipboardData) return; const selection = window.getSelection(); @@ -661,7 +681,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(userImages, image.id); + const preview = buildExpandedImagePreview(userImages, image.id, copySnapshot); if (preview) onImageExpand(preview); }} onOpenFile={onFileOpen} @@ -737,7 +757,7 @@ function UserTimelineRow({ row }: { row: Extract { - const preview = buildExpandedImagePreview(regularImages, image.id); + const preview = buildExpandedImagePreview(regularImages, image.id, copySnapshot); if (!preview) return; ctx.onImageExpand(preview); }} @@ -772,7 +792,10 @@ function UserTimelineRow({ row }: { row: Extract )} {image.previewUrl && image.source?.kind === "snap-shot" ? ( - + copySnapshot(image.id)} + /> ) : null}
))} diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx index 39801a908b952..e345472b1f972 100644 --- a/apps/web/src/components/chat/UserMessageContextChips.tsx +++ b/apps/web/src/components/chat/UserMessageContextChips.tsx @@ -1,3 +1,5 @@ +import { useNativeFileDrag } from "../../useNativeFileDrag"; +import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isSvgAttachment } from "@t3tools/shared/image"; import { useRenderedAppearance } from "../../hooks/useTheme"; @@ -68,11 +70,15 @@ function UserMessageMentionChip(props: { copyMarkdown: string; }) { const ctx = use(TimelineRowCtx); + const nativeDrag = useNativeFileDrag(ctx.activeThreadEnvironmentId, () => + resolvePathLinkTarget(props.record.path, ctx.workspaceRoot ?? ""), + ); return ( } aria-label={`Preview ${props.record.path}`} diff --git a/apps/web/src/components/chat/backgroundThread.ts b/apps/web/src/components/chat/backgroundThread.ts index b3dfee09a663c..e402bc5e62165 100644 --- a/apps/web/src/components/chat/backgroundThread.ts +++ b/apps/web/src/components/chat/backgroundThread.ts @@ -5,3 +5,6 @@ import { createContext } from "react"; * parent's panel; its global shortcuts and listeners stand down. */ export const BackgroundThreadContext = createContext(false); + +/** True only for a thread kept mounted out of sight under Settings or Usage. */ +export const HiddenThreadContext = createContext(false); diff --git a/apps/web/src/components/chat/copySnapshot.test.ts b/apps/web/src/components/chat/copySnapshot.test.ts new file mode 100644 index 0000000000000..9ac7080f7b0f7 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.test.ts @@ -0,0 +1,75 @@ +import { ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + decodeComposerContextClipboardHtml, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { expect, it } from "vite-plus/test"; + +import { copySnapshot } from "./copySnapshot"; + +it.each([false, true])( + "preserves image bytes and snapshot metadata, custom format rejected: %s", + async (rejectCustom) => { + class Item { + constructor(readonly data: Record>) {} + } + let clipboard: Item | undefined; + const write = async ([item]: Item[]) => { + if (rejectCustom && item?.data[COMPOSER_CONTEXT_CLIPBOARD_MIME]) + throw new Error("Unsupported format"); + clipboard = item; + await Promise.all(Object.values(item!.data)); + }; + const originals = { + navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"), + ClipboardItem: Object.getOwnPropertyDescriptor(globalThis, "ClipboardItem"), + }; + using _globals = { + [Symbol.dispose]() { + for (const key of ["navigator", "ClipboardItem"] as const) { + const descriptor = originals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }, + }; + Object.defineProperty(globalThis, "navigator", { + configurable: true, + value: { clipboard: { write } }, + }); + Object.defineProperty(globalThis, "ClipboardItem", { configurable: true, value: Item }); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: EnvironmentId.make("snapshot-source") }, + records: [ + { + version: 1, + kind: "image", + contextId: ComposerContextId.make("image_snapshot"), + label: "Snapshot", + attachmentId: "snapshot", + name: "snapshot.png", + mimeType: "image/png", + sizeBytes: 3, + source: { + kind: "snap-shot", + capturedAt: "2026-01-01T00:00:00.000Z", + appName: "Finder", + windowTitle: "Downloads", + accessibleText: "Downloads", + }, + }, + ], + })!; + const image = "data:image/png;base64,AQID"; + await copySnapshot(image, "Snapshot", fragment); + const png = await clipboard!.data["image/png"]!; + expect(png.type).toBe("image/png"); + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual([1, 2, 3]); + expect( + decodeComposerContextClipboardHtml(await (await clipboard!.data["text/html"]!).text()), + ).toEqual(JSON.parse(fragment)); + expect(await (await clipboard!.data["text/plain"]!).text()).toBe("Snapshot"); + }, +); diff --git a/apps/web/src/components/chat/copySnapshot.ts b/apps/web/src/components/chat/copySnapshot.ts new file mode 100644 index 0000000000000..118121e753647 --- /dev/null +++ b/apps/web/src/components/chat/copySnapshot.ts @@ -0,0 +1,33 @@ +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextClipboardHtml, +} from "@t3tools/shared/composerContextClipboard"; + +import { readMediaPng } from "../media/mediaContent"; + +export async function copySnapshot(src: string, text: string, fragment: string): Promise { + if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") { + throw new Error("Snapshot copying requires a secure browser connection."); + } + const formats = { + "image/png": readMediaPng(src), + "text/plain": new Blob([text], { type: "text/plain" }), + "text/html": new Blob([encodeComposerContextClipboardHtml(text, fragment)], { + type: "text/html", + }), + }; + // Start writing within the click gesture, before the image fetch or decode completes. + try { + await navigator.clipboard.write([ + new ClipboardItem({ + ...formats, + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: new Blob([fragment], { + type: COMPOSER_CONTEXT_CLIPBOARD_MIME, + }), + }), + ]); + } catch { + // HTML carries the same snapshot metadata when custom clipboard formats are unsupported. + await navigator.clipboard.write([new ClipboardItem(formats)]); + } +} diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index e2bf9676b8b6d..d48e965895ddd 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -48,6 +48,7 @@ function deferred() { it.each([ { kind: "file", edit: "delete" }, { kind: "image", edit: "delete" }, + { kind: "image", edit: "retain" }, { kind: "file", edit: "undo" }, { kind: "file", edit: "retain" }, { kind: "file", edit: "switch" }, @@ -124,7 +125,17 @@ it.each([ const attachment = ( kind === "file" ? { ...attachmentFields, kind: "file" as const } - : { ...attachmentFields, kind: "image" as const } + : { + ...attachmentFields, + kind: "image" as const, + source: { + kind: "snap-shot" as const, + appName: "Finder", + windowTitle: "Downloads", + capturedAt: "2026-01-01T00:00:00.000Z", + accessibleText: "Downloads", + }, + } ) satisfies ComposerContextRecord; const annotation = { version: 1, @@ -182,6 +193,10 @@ it.each([ const draft = store.getComposerDraft(target)!; expect(draft.prompt).toBe(promptRef.current); const attachments = kind === "file" ? draft.files : draft.images; + if (kind === "image" && edit === "retain") + expect(draft.images[0]?.source).toEqual( + attachment.kind === "image" ? attachment.source : undefined, + ); expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 0cc66d6a71d19..265278faec747 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -246,6 +246,7 @@ export function useComposerContextImport(input: { sizeBytes: file.size, previewUrl: URL.createObjectURL(file), file, + ...(record.source ? { source: record.source } : {}), }, ], { diff --git a/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx b/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx index 9662e0e0899bc..4810e8b5e2183 100644 --- a/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCandidatePicker.tsx @@ -32,7 +32,6 @@ export function PullRequestCandidatePicker({ truncated, truncatedLabel, candidateKey, - disabled, onSelect, children, }: { @@ -54,7 +53,6 @@ export function PullRequestCandidatePicker({ truncated: boolean; truncatedLabel: string; candidateKey: (candidate: T) => string; - disabled: boolean; onSelect: (candidate: T) => void; children: (candidate: T) => ReactNode; }) { @@ -123,13 +121,7 @@ export function PullRequestCandidatePicker({

) : ( candidates.map((candidate, index) => ( - + {children(candidate)} )) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index c9bcfc1a378fd..95bef6edeec91 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -1,5 +1,5 @@ import { ArrowLeftIcon, FileDiffIcon } from "lucide-react"; -import type { ComponentProps, ReactNode } from "react"; +import { useEffect, useRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "~/lib/utils"; @@ -77,6 +77,10 @@ export function PullRequestDetailTabBar({ inert?: boolean; children?: ReactNode; }) { + // A pointer passing over a tab is not intent; it must rest like a list row does. + const pointerIntent = useRef | undefined>(undefined); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- A rest timer still pending when the bar unmounts must not read for a closed panel. + useEffect(() => () => clearTimeout(pointerIntent.current), []); return (